push 378fe7a60681a28e8b22f62dcfe122d585b92570
[wine/hacks.git] / dlls / gdi32 / region.c
blobf9d078c0619242881d0ad2be5c3647796f1e993d
1 /*
2 * GDI region objects. Shamelessly ripped out from the X11 distribution
3 * Thanks for the nice licence.
5 * Copyright 1993, 1994, 1995 Alexandre Julliard
6 * Modifications and additions: Copyright 1998 Huw Davies
7 * 1999 Alex Korobka
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.
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.
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
24 /************************************************************************
26 Copyright (c) 1987, 1988 X Consortium
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:
35 The above copyright notice and this permission notice shall be included in
36 all copies or substantial portions of the Software.
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.
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.
50 Copyright 1987, 1988 by Digital Equipment Corporation, Maynard, Massachusetts.
52 All Rights Reserved
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.
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.
70 ************************************************************************/
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.
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".
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.
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...
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"
106 WINE_DEFAULT_DEBUG_CHANNEL(region);
108 typedef struct {
109 INT size;
110 INT numRects;
111 RECT *rects;
112 RECT extents;
113 } WINEREGION;
115 /* GDI logical region object */
116 typedef struct
118 GDIOBJHDR header;
119 WINEREGION rgn;
120 } RGNOBJ;
123 static HGDIOBJ REGION_SelectObject( HGDIOBJ handle, HDC hdc );
124 static BOOL REGION_DeleteObject( HGDIOBJ handle );
126 static const struct gdi_obj_funcs region_funcs =
128 REGION_SelectObject, /* pSelectObject */
129 NULL, /* pGetObjectA */
130 NULL, /* pGetObjectW */
131 NULL, /* pUnrealizeObject */
132 REGION_DeleteObject /* pDeleteObject */
135 /* 1 if two RECTs overlap.
136 * 0 if two RECTs do not overlap.
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)
145 static BOOL add_rect( WINEREGION *reg, INT left, INT top, INT right, INT bottom )
147 RECT *rect;
148 if (reg->numRects >= reg->size)
150 RECT *newrects = HeapReAlloc( GetProcessHeap(), 0, reg->rects, 2 * sizeof(RECT) * reg->size );
151 if (!newrects) return FALSE;
152 reg->rects = newrects;
153 reg->size *= 2;
155 rect = reg->rects + reg->numRects++;
156 rect->left = left;
157 rect->top = top;
158 rect->right = right;
159 rect->bottom = bottom;
160 return TRUE;
163 #define EMPTY_REGION(pReg) do { \
164 (pReg)->numRects = 0; \
165 (pReg)->extents.left = (pReg)->extents.top = 0; \
166 (pReg)->extents.right = (pReg)->extents.bottom = 0; \
167 } while(0)
169 #define INRECT(r, x, y) \
170 ( ( ((r).right > x)) && \
171 ( ((r).left <= x)) && \
172 ( ((r).bottom > y)) && \
173 ( ((r).top <= y)) )
177 * number of points to buffer before sending them off
178 * to scanlines() : Must be an even number
180 #define NUMPTSTOBUFFER 200
183 * used to allocate buffers for points and link
184 * the buffers together
187 typedef struct _POINTBLOCK {
188 POINT pts[NUMPTSTOBUFFER];
189 struct _POINTBLOCK *next;
190 } POINTBLOCK;
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.
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.
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.
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.
229 #define BRESINITPGON(dy, x1, x2, xStart, d, m, m1, incr1, incr2) { \
230 int dx; /* local storage */ \
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; \
255 #define BRESINCRPGON(d, minval, m, m1, incr1, incr2) { \
256 if (m1 > 0) { \
257 if (d > 0) { \
258 minval += m1; \
259 d += incr1; \
261 else { \
262 minval += m; \
263 d += incr2; \
265 } else {\
266 if (d >= 0) { \
267 minval += m1; \
268 d += incr1; \
270 else { \
271 minval += m; \
272 d += incr2; \
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.
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;
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)
296 #define BRESINCRPGONSTRUCT(bres) \
297 BRESINCRPGON(bres.d, bres.minor_axis, bres.m, bres.m1, bres.incr1, bres.incr2)
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.
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.
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).
348 * for the winding number rule
350 #define CLOCKWISE 1
351 #define COUNTERCLOCKWISE -1
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;
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;
370 typedef struct {
371 INT ymax; /* ymax for the polygon */
372 INT ymin; /* ymin for the polygon */
373 ScanLineList scanlines; /* header node */
374 } EdgeTable;
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.
382 #define SLLSPERBLOCK 25
384 typedef struct _ScanLineListBlock {
385 ScanLineList SLLs[SLLSPERBLOCK];
386 struct _ScanLineListBlock *next;
387 } ScanLineListBlock;
392 * a few macros for the inner loops of the fill code where
393 * performance considerations don't allow a procedure call.
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.
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; \
411 else { \
412 BRESINCRPGONSTRUCT(pAET->bres); \
413 pPrevAET = pAET; \
414 pAET = pAET->next; \
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.
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; \
433 else { \
434 BRESINCRPGONSTRUCT(pAET->bres); \
435 pPrevAET = pAET; \
436 pAET = pAET->next; \
440 /* Note the parameter order is different from the X11 equivalents */
442 static BOOL REGION_CopyRegion(WINEREGION *d, WINEREGION *s);
443 static BOOL REGION_OffsetRegion(WINEREGION *d, WINEREGION *s, INT x, INT y);
444 static BOOL REGION_IntersectRegion(WINEREGION *d, WINEREGION *s1, WINEREGION *s2);
445 static BOOL REGION_UnionRegion(WINEREGION *d, WINEREGION *s1, WINEREGION *s2);
446 static BOOL REGION_SubtractRegion(WINEREGION *d, WINEREGION *s1, WINEREGION *s2);
447 static BOOL REGION_XorRegion(WINEREGION *d, WINEREGION *s1, WINEREGION *s2);
448 static BOOL REGION_UnionRectWithRegion(const RECT *rect, WINEREGION *rgn);
450 #define RGN_DEFAULT_RECTS 2
453 /***********************************************************************
454 * get_region_type
456 static inline INT get_region_type( const RGNOBJ *obj )
458 switch(obj->rgn.numRects)
460 case 0: return NULLREGION;
461 case 1: return SIMPLEREGION;
462 default: return COMPLEXREGION;
467 /***********************************************************************
468 * REGION_DumpRegion
469 * Outputs the contents of a WINEREGION
471 static void REGION_DumpRegion(WINEREGION *pReg)
473 RECT *pRect, *pRectEnd = pReg->rects + pReg->numRects;
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;
485 /***********************************************************************
486 * init_region
488 * Initialize a new empty region.
490 static BOOL init_region( WINEREGION *pReg, INT n )
492 if (!(pReg->rects = HeapAlloc(GetProcessHeap(), 0, n * sizeof( RECT )))) return FALSE;
493 pReg->size = n;
494 EMPTY_REGION(pReg);
495 return TRUE;
498 /***********************************************************************
499 * destroy_region
501 static void destroy_region( WINEREGION *pReg )
503 HeapFree( GetProcessHeap(), 0, pReg->rects );
506 /***********************************************************************
507 * REGION_DeleteObject
509 static BOOL REGION_DeleteObject( HGDIOBJ handle )
511 RGNOBJ *rgn = free_gdi_handle( handle );
513 if (!rgn) return FALSE;
514 HeapFree( GetProcessHeap(), 0, rgn->rgn.rects );
515 HeapFree( GetProcessHeap(), 0, rgn );
516 return TRUE;
519 /***********************************************************************
520 * REGION_SelectObject
522 static HGDIOBJ REGION_SelectObject( HGDIOBJ handle, HDC hdc )
524 return ULongToHandle(SelectClipRgn( hdc, handle ));
528 /***********************************************************************
529 * REGION_OffsetRegion
530 * Offset a WINEREGION by x,y
532 static BOOL REGION_OffsetRegion( WINEREGION *rgn, WINEREGION *srcrgn, INT x, INT y )
534 if( rgn != srcrgn)
536 if (!REGION_CopyRegion( rgn, srcrgn)) return FALSE;
538 if(x || y) {
539 int nbox = rgn->numRects;
540 RECT *pbox = rgn->rects;
542 if(nbox) {
543 while(nbox--) {
544 pbox->left += x;
545 pbox->right += x;
546 pbox->top += y;
547 pbox->bottom += y;
548 pbox++;
550 rgn->extents.left += x;
551 rgn->extents.right += x;
552 rgn->extents.top += y;
553 rgn->extents.bottom += y;
556 return TRUE;
559 /***********************************************************************
560 * OffsetRgn (GDI32.@)
562 * Moves a region by the specified X- and Y-axis offsets.
564 * PARAMS
565 * hrgn [I] Region to offset.
566 * x [I] Offset right if positive or left if negative.
567 * y [I] Offset down if positive or up if negative.
569 * RETURNS
570 * Success:
571 * NULLREGION - The new region is empty.
572 * SIMPLEREGION - The new region can be represented by one rectangle.
573 * COMPLEXREGION - The new region can only be represented by more than
574 * one rectangle.
575 * Failure: ERROR
577 INT WINAPI OffsetRgn( HRGN hrgn, INT x, INT y )
579 RGNOBJ * obj = GDI_GetObjPtr( hrgn, OBJ_REGION );
580 INT ret;
582 TRACE("%p %d,%d\n", hrgn, x, y);
584 if (!obj)
585 return ERROR;
587 REGION_OffsetRegion( &obj->rgn, &obj->rgn, x, y);
589 ret = get_region_type( obj );
590 GDI_ReleaseObj( hrgn );
591 return ret;
595 /***********************************************************************
596 * GetRgnBox (GDI32.@)
598 * Retrieves the bounding rectangle of the region. The bounding rectangle
599 * is the smallest rectangle that contains the entire region.
601 * PARAMS
602 * hrgn [I] Region to retrieve bounding rectangle from.
603 * rect [O] Rectangle that will receive the coordinates of the bounding
604 * rectangle.
606 * RETURNS
607 * NULLREGION - The new region is empty.
608 * SIMPLEREGION - The new region can be represented by one rectangle.
609 * COMPLEXREGION - The new region can only be represented by more than
610 * one rectangle.
612 INT WINAPI GetRgnBox( HRGN hrgn, LPRECT rect )
614 RGNOBJ * obj = GDI_GetObjPtr( hrgn, OBJ_REGION );
615 if (obj)
617 INT ret;
618 rect->left = obj->rgn.extents.left;
619 rect->top = obj->rgn.extents.top;
620 rect->right = obj->rgn.extents.right;
621 rect->bottom = obj->rgn.extents.bottom;
622 TRACE("%p (%d,%d-%d,%d)\n", hrgn,
623 rect->left, rect->top, rect->right, rect->bottom);
624 ret = get_region_type( obj );
625 GDI_ReleaseObj(hrgn);
626 return ret;
628 return ERROR;
632 /***********************************************************************
633 * CreateRectRgn (GDI32.@)
635 * Creates a simple rectangular region.
637 * PARAMS
638 * left [I] Left coordinate of rectangle.
639 * top [I] Top coordinate of rectangle.
640 * right [I] Right coordinate of rectangle.
641 * bottom [I] Bottom coordinate of rectangle.
643 * RETURNS
644 * Success: Handle to region.
645 * Failure: NULL.
647 HRGN WINAPI CreateRectRgn(INT left, INT top, INT right, INT bottom)
649 HRGN hrgn;
650 RGNOBJ *obj;
652 if (!(obj = HeapAlloc( GetProcessHeap(), 0, sizeof(*obj) ))) return 0;
654 /* Allocate 2 rects by default to reduce the number of reallocs */
655 if (!init_region( &obj->rgn, RGN_DEFAULT_RECTS ))
657 HeapFree( GetProcessHeap(), 0, obj );
658 return 0;
660 if (!(hrgn = alloc_gdi_handle( &obj->header, OBJ_REGION, &region_funcs )))
662 HeapFree( GetProcessHeap(), 0, obj->rgn.rects );
663 HeapFree( GetProcessHeap(), 0, obj );
664 return 0;
666 TRACE( "%d,%d-%d,%d returning %p\n", left, top, right, bottom, hrgn );
667 SetRectRgn(hrgn, left, top, right, bottom);
668 return hrgn;
672 /***********************************************************************
673 * CreateRectRgnIndirect (GDI32.@)
675 * Creates a simple rectangular region.
677 * PARAMS
678 * rect [I] Coordinates of rectangular region.
680 * RETURNS
681 * Success: Handle to region.
682 * Failure: NULL.
684 HRGN WINAPI CreateRectRgnIndirect( const RECT* rect )
686 return CreateRectRgn( rect->left, rect->top, rect->right, rect->bottom );
690 /***********************************************************************
691 * SetRectRgn (GDI32.@)
693 * Sets a region to a simple rectangular region.
695 * PARAMS
696 * hrgn [I] Region to convert.
697 * left [I] Left coordinate of rectangle.
698 * top [I] Top coordinate of rectangle.
699 * right [I] Right coordinate of rectangle.
700 * bottom [I] Bottom coordinate of rectangle.
702 * RETURNS
703 * Success: Non-zero.
704 * Failure: Zero.
706 * NOTES
707 * Allows either or both left and top to be greater than right or bottom.
709 BOOL WINAPI SetRectRgn( HRGN hrgn, INT left, INT top,
710 INT right, INT bottom )
712 RGNOBJ * obj;
714 TRACE("%p %d,%d-%d,%d\n", hrgn, left, top, right, bottom );
716 if (!(obj = GDI_GetObjPtr( hrgn, OBJ_REGION ))) return FALSE;
718 if (left > right) { INT tmp = left; left = right; right = tmp; }
719 if (top > bottom) { INT tmp = top; top = bottom; bottom = tmp; }
721 if((left != right) && (top != bottom))
723 obj->rgn.rects->left = obj->rgn.extents.left = left;
724 obj->rgn.rects->top = obj->rgn.extents.top = top;
725 obj->rgn.rects->right = obj->rgn.extents.right = right;
726 obj->rgn.rects->bottom = obj->rgn.extents.bottom = bottom;
727 obj->rgn.numRects = 1;
729 else
730 EMPTY_REGION(&obj->rgn);
732 GDI_ReleaseObj( hrgn );
733 return TRUE;
737 /***********************************************************************
738 * CreateRoundRectRgn (GDI32.@)
740 * Creates a rectangular region with rounded corners.
742 * PARAMS
743 * left [I] Left coordinate of rectangle.
744 * top [I] Top coordinate of rectangle.
745 * right [I] Right coordinate of rectangle.
746 * bottom [I] Bottom coordinate of rectangle.
747 * ellipse_width [I] Width of the ellipse at each corner.
748 * ellipse_height [I] Height of the ellipse at each corner.
750 * RETURNS
751 * Success: Handle to region.
752 * Failure: NULL.
754 * NOTES
755 * If ellipse_width or ellipse_height is less than 2 logical units then
756 * it is treated as though CreateRectRgn() was called instead.
758 HRGN WINAPI CreateRoundRectRgn( INT left, INT top,
759 INT right, INT bottom,
760 INT ellipse_width, INT ellipse_height )
762 RGNOBJ * obj;
763 HRGN hrgn = 0;
764 int asq, bsq, d, xd, yd;
765 RECT rect;
767 /* Make the dimensions sensible */
769 if (left > right) { INT tmp = left; left = right; right = tmp; }
770 if (top > bottom) { INT tmp = top; top = bottom; bottom = tmp; }
772 ellipse_width = abs(ellipse_width);
773 ellipse_height = abs(ellipse_height);
775 /* Check parameters */
777 if (ellipse_width > right-left) ellipse_width = right-left;
778 if (ellipse_height > bottom-top) ellipse_height = bottom-top;
780 /* Check if we can do a normal rectangle instead */
782 if ((ellipse_width < 2) || (ellipse_height < 2))
783 return CreateRectRgn( left, top, right, bottom );
785 /* Create region */
787 d = (ellipse_height < 128) ? ((3 * ellipse_height) >> 2) : 64;
788 if (!(obj = HeapAlloc( GetProcessHeap(), 0, sizeof(*obj) ))) return 0;
789 if (!init_region( &obj->rgn, d ))
791 HeapFree( GetProcessHeap(), 0, obj );
792 return 0;
795 /* Ellipse algorithm, based on an article by K. Porter */
796 /* in DDJ Graphics Programming Column, 8/89 */
798 asq = ellipse_width * ellipse_width / 4; /* a^2 */
799 bsq = ellipse_height * ellipse_height / 4; /* b^2 */
800 d = bsq - asq * ellipse_height / 2 + asq / 4; /* b^2 - a^2b + a^2/4 */
801 xd = 0;
802 yd = asq * ellipse_height; /* 2a^2b */
804 rect.left = left + ellipse_width / 2;
805 rect.right = right - ellipse_width / 2;
807 /* Loop to draw first half of quadrant */
809 while (xd < yd)
811 if (d > 0) /* if nearest pixel is toward the center */
813 /* move toward center */
814 rect.top = top++;
815 rect.bottom = rect.top + 1;
816 if (!REGION_UnionRectWithRegion( &rect, &obj->rgn )) goto done;
817 rect.top = --bottom;
818 rect.bottom = rect.top + 1;
819 if (!REGION_UnionRectWithRegion( &rect, &obj->rgn )) goto done;
820 yd -= 2*asq;
821 d -= yd;
823 rect.left--; /* next horiz point */
824 rect.right++;
825 xd += 2*bsq;
826 d += bsq + xd;
829 /* Loop to draw second half of quadrant */
831 d += (3 * (asq-bsq) / 2 - (xd+yd)) / 2;
832 while (yd >= 0)
834 /* next vertical point */
835 rect.top = top++;
836 rect.bottom = rect.top + 1;
837 if (!REGION_UnionRectWithRegion( &rect, &obj->rgn )) goto done;
838 rect.top = --bottom;
839 rect.bottom = rect.top + 1;
840 if (!REGION_UnionRectWithRegion( &rect, &obj->rgn )) goto done;
841 if (d < 0) /* if nearest pixel is outside ellipse */
843 rect.left--; /* move away from center */
844 rect.right++;
845 xd += 2*bsq;
846 d += xd;
848 yd -= 2*asq;
849 d += asq - yd;
852 /* Add the inside rectangle */
854 if (top <= bottom)
856 rect.top = top;
857 rect.bottom = bottom;
858 if (!REGION_UnionRectWithRegion( &rect, &obj->rgn )) goto done;
861 hrgn = alloc_gdi_handle( &obj->header, OBJ_REGION, &region_funcs );
863 TRACE("(%d,%d-%d,%d %dx%d): ret=%p\n",
864 left, top, right, bottom, ellipse_width, ellipse_height, hrgn );
865 done:
866 if (!hrgn)
868 HeapFree( GetProcessHeap(), 0, obj->rgn.rects );
869 HeapFree( GetProcessHeap(), 0, obj );
871 return hrgn;
875 /***********************************************************************
876 * CreateEllipticRgn (GDI32.@)
878 * Creates an elliptical region.
880 * PARAMS
881 * left [I] Left coordinate of bounding rectangle.
882 * top [I] Top coordinate of bounding rectangle.
883 * right [I] Right coordinate of bounding rectangle.
884 * bottom [I] Bottom coordinate of bounding rectangle.
886 * RETURNS
887 * Success: Handle to region.
888 * Failure: NULL.
890 * NOTES
891 * This is a special case of CreateRoundRectRgn() where the width of the
892 * ellipse at each corner is equal to the width the rectangle and
893 * the same for the height.
895 HRGN WINAPI CreateEllipticRgn( INT left, INT top,
896 INT right, INT bottom )
898 return CreateRoundRectRgn( left, top, right, bottom,
899 right-left, bottom-top );
903 /***********************************************************************
904 * CreateEllipticRgnIndirect (GDI32.@)
906 * Creates an elliptical region.
908 * PARAMS
909 * rect [I] Pointer to bounding rectangle of the ellipse.
911 * RETURNS
912 * Success: Handle to region.
913 * Failure: NULL.
915 * NOTES
916 * This is a special case of CreateRoundRectRgn() where the width of the
917 * ellipse at each corner is equal to the width the rectangle and
918 * the same for the height.
920 HRGN WINAPI CreateEllipticRgnIndirect( const RECT *rect )
922 return CreateRoundRectRgn( rect->left, rect->top, rect->right,
923 rect->bottom, rect->right - rect->left,
924 rect->bottom - rect->top );
927 /***********************************************************************
928 * GetRegionData (GDI32.@)
930 * Retrieves the data that specifies the region.
932 * PARAMS
933 * hrgn [I] Region to retrieve the region data from.
934 * count [I] The size of the buffer pointed to by rgndata in bytes.
935 * rgndata [I] The buffer to receive data about the region.
937 * RETURNS
938 * Success: If rgndata is NULL then the required number of bytes. Otherwise,
939 * the number of bytes copied to the output buffer.
940 * Failure: 0.
942 * NOTES
943 * The format of the Buffer member of RGNDATA is determined by the iType
944 * member of the region data header.
945 * Currently this is always RDH_RECTANGLES, which specifies that the format
946 * is the array of RECT's that specify the region. The length of the array
947 * is specified by the nCount member of the region data header.
949 DWORD WINAPI GetRegionData(HRGN hrgn, DWORD count, LPRGNDATA rgndata)
951 DWORD size;
952 RGNOBJ *obj = GDI_GetObjPtr( hrgn, OBJ_REGION );
954 TRACE(" %p count = %d, rgndata = %p\n", hrgn, count, rgndata);
956 if(!obj) return 0;
958 size = obj->rgn.numRects * sizeof(RECT);
959 if(count < (size + sizeof(RGNDATAHEADER)) || rgndata == NULL)
961 GDI_ReleaseObj( hrgn );
962 if (rgndata) /* buffer is too small, signal it by return 0 */
963 return 0;
964 else /* user requested buffer size with rgndata NULL */
965 return size + sizeof(RGNDATAHEADER);
968 rgndata->rdh.dwSize = sizeof(RGNDATAHEADER);
969 rgndata->rdh.iType = RDH_RECTANGLES;
970 rgndata->rdh.nCount = obj->rgn.numRects;
971 rgndata->rdh.nRgnSize = size;
972 rgndata->rdh.rcBound.left = obj->rgn.extents.left;
973 rgndata->rdh.rcBound.top = obj->rgn.extents.top;
974 rgndata->rdh.rcBound.right = obj->rgn.extents.right;
975 rgndata->rdh.rcBound.bottom = obj->rgn.extents.bottom;
977 memcpy( rgndata->Buffer, obj->rgn.rects, size );
979 GDI_ReleaseObj( hrgn );
980 return size + sizeof(RGNDATAHEADER);
984 static void translate( POINT *pt, UINT count, const XFORM *xform )
986 while (count--)
988 double x = pt->x;
989 double y = pt->y;
990 pt->x = floor( x * xform->eM11 + y * xform->eM21 + xform->eDx + 0.5 );
991 pt->y = floor( x * xform->eM12 + y * xform->eM22 + xform->eDy + 0.5 );
992 pt++;
997 /***********************************************************************
998 * ExtCreateRegion (GDI32.@)
1000 * Creates a region as specified by the transformation data and region data.
1002 * PARAMS
1003 * lpXform [I] World-space to logical-space transformation data.
1004 * dwCount [I] Size of the data pointed to by rgndata, in bytes.
1005 * rgndata [I] Data that specifies the region.
1007 * RETURNS
1008 * Success: Handle to region.
1009 * Failure: NULL.
1011 * NOTES
1012 * See GetRegionData().
1014 HRGN WINAPI ExtCreateRegion( const XFORM* lpXform, DWORD dwCount, const RGNDATA* rgndata)
1016 HRGN hrgn = 0;
1017 RGNOBJ *obj;
1019 if (!rgndata)
1021 SetLastError( ERROR_INVALID_PARAMETER );
1022 return 0;
1025 if (rgndata->rdh.dwSize < sizeof(RGNDATAHEADER))
1026 return 0;
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);
1032 if (lpXform)
1034 RECT *pCurRect, *pEndRect;
1036 hrgn = CreateRectRgn( 0, 0, 0, 0 );
1038 pEndRect = (RECT *)rgndata->Buffer + rgndata->rdh.nCount;
1039 for (pCurRect = (RECT *)rgndata->Buffer; pCurRect < pEndRect; pCurRect++)
1041 static const INT count = 4;
1042 HRGN poly_hrgn;
1043 POINT pt[4];
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;
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 );
1059 return hrgn;
1062 if (!(obj = HeapAlloc( GetProcessHeap(), 0, sizeof(*obj) ))) return 0;
1064 if (init_region( &obj->rgn, rgndata->rdh.nCount ))
1066 RECT *pCurRect, *pEndRect;
1068 pEndRect = (RECT *)rgndata->Buffer + rgndata->rdh.nCount;
1069 for(pCurRect = (RECT *)rgndata->Buffer; pCurRect < pEndRect; pCurRect++)
1071 if (pCurRect->left < pCurRect->right && pCurRect->top < pCurRect->bottom)
1073 if (!REGION_UnionRectWithRegion( pCurRect, &obj->rgn )) goto done;
1076 hrgn = alloc_gdi_handle( &obj->header, OBJ_REGION, &region_funcs );
1078 else
1080 HeapFree( GetProcessHeap(), 0, obj );
1081 return 0;
1084 done:
1085 if (!hrgn)
1087 HeapFree( GetProcessHeap(), 0, obj->rgn.rects );
1088 HeapFree( GetProcessHeap(), 0, obj );
1090 TRACE("%p %d %p returning %p\n", lpXform, dwCount, rgndata, hrgn );
1091 return hrgn;
1095 /***********************************************************************
1096 * PtInRegion (GDI32.@)
1098 * Tests whether the specified point is inside a region.
1100 * PARAMS
1101 * hrgn [I] Region to test.
1102 * x [I] X-coordinate of point to test.
1103 * y [I] Y-coordinate of point to test.
1105 * RETURNS
1106 * Non-zero if the point is inside the region or zero otherwise.
1108 BOOL WINAPI PtInRegion( HRGN hrgn, INT x, INT y )
1110 RGNOBJ * obj;
1111 BOOL ret = FALSE;
1113 if ((obj = GDI_GetObjPtr( hrgn, OBJ_REGION )))
1115 int i;
1117 if (obj->rgn.numRects > 0 && INRECT(obj->rgn.extents, x, y))
1118 for (i = 0; i < obj->rgn.numRects; i++)
1119 if (INRECT (obj->rgn.rects[i], x, y))
1121 ret = TRUE;
1122 break;
1124 GDI_ReleaseObj( hrgn );
1126 return ret;
1130 /***********************************************************************
1131 * RectInRegion (GDI32.@)
1133 * Tests if a rectangle is at least partly inside the specified region.
1135 * PARAMS
1136 * hrgn [I] Region to test.
1137 * rect [I] Rectangle to test.
1139 * RETURNS
1140 * Non-zero if the rectangle is partially inside the region or
1141 * zero otherwise.
1143 BOOL WINAPI RectInRegion( HRGN hrgn, const RECT *rect )
1145 RGNOBJ * obj;
1146 BOOL ret = FALSE;
1148 if ((obj = GDI_GetObjPtr( hrgn, OBJ_REGION )))
1150 RECT *pCurRect, *pRectEnd;
1152 /* this is (just) a useful optimization */
1153 if ((obj->rgn.numRects > 0) && EXTENTCHECK(&obj->rgn.extents, rect))
1155 for (pCurRect = obj->rgn.rects, pRectEnd = pCurRect +
1156 obj->rgn.numRects; pCurRect < pRectEnd; pCurRect++)
1158 if (pCurRect->bottom <= rect->top)
1159 continue; /* not far enough down yet */
1161 if (pCurRect->top >= rect->bottom)
1162 break; /* too far down */
1164 if (pCurRect->right <= rect->left)
1165 continue; /* not far enough over yet */
1167 if (pCurRect->left >= rect->right) {
1168 continue;
1171 ret = TRUE;
1172 break;
1175 GDI_ReleaseObj(hrgn);
1177 return ret;
1180 /***********************************************************************
1181 * EqualRgn (GDI32.@)
1183 * Tests whether one region is identical to another.
1185 * PARAMS
1186 * hrgn1 [I] The first region to compare.
1187 * hrgn2 [I] The second region to compare.
1189 * RETURNS
1190 * Non-zero if both regions are identical or zero otherwise.
1192 BOOL WINAPI EqualRgn( HRGN hrgn1, HRGN hrgn2 )
1194 RGNOBJ *obj1, *obj2;
1195 BOOL ret = FALSE;
1197 if ((obj1 = GDI_GetObjPtr( hrgn1, OBJ_REGION )))
1199 if ((obj2 = GDI_GetObjPtr( hrgn2, OBJ_REGION )))
1201 int i;
1203 if ( obj1->rgn.numRects != obj2->rgn.numRects ) goto done;
1204 if ( obj1->rgn.numRects == 0 )
1206 ret = TRUE;
1207 goto done;
1210 if (obj1->rgn.extents.left != obj2->rgn.extents.left) goto done;
1211 if (obj1->rgn.extents.right != obj2->rgn.extents.right) goto done;
1212 if (obj1->rgn.extents.top != obj2->rgn.extents.top) goto done;
1213 if (obj1->rgn.extents.bottom != obj2->rgn.extents.bottom) goto done;
1214 for( i = 0; i < obj1->rgn.numRects; i++ )
1216 if (obj1->rgn.rects[i].left != obj2->rgn.rects[i].left) goto done;
1217 if (obj1->rgn.rects[i].right != obj2->rgn.rects[i].right) goto done;
1218 if (obj1->rgn.rects[i].top != obj2->rgn.rects[i].top) goto done;
1219 if (obj1->rgn.rects[i].bottom != obj2->rgn.rects[i].bottom) goto done;
1221 ret = TRUE;
1222 done:
1223 GDI_ReleaseObj(hrgn2);
1225 GDI_ReleaseObj(hrgn1);
1227 return ret;
1230 /***********************************************************************
1231 * REGION_UnionRectWithRegion
1232 * Adds a rectangle to a WINEREGION
1234 static BOOL REGION_UnionRectWithRegion(const RECT *rect, WINEREGION *rgn)
1236 WINEREGION region;
1238 region.rects = &region.extents;
1239 region.numRects = 1;
1240 region.size = 1;
1241 region.extents = *rect;
1242 return REGION_UnionRegion(rgn, rgn, &region);
1246 /***********************************************************************
1247 * REGION_CreateFrameRgn
1249 * Create a region that is a frame around another region.
1250 * Compute the intersection of the region moved in all 4 directions
1251 * ( +x, -x, +y, -y) and subtract from the original.
1252 * The result looks slightly better than in Windows :)
1254 BOOL REGION_FrameRgn( HRGN hDest, HRGN hSrc, INT x, INT y )
1256 WINEREGION tmprgn;
1257 BOOL bRet = FALSE;
1258 RGNOBJ* destObj = NULL;
1259 RGNOBJ *srcObj = GDI_GetObjPtr( hSrc, OBJ_REGION );
1261 tmprgn.rects = NULL;
1262 if (!srcObj) return FALSE;
1263 if (srcObj->rgn.numRects != 0)
1265 if (!(destObj = GDI_GetObjPtr( hDest, OBJ_REGION ))) goto done;
1266 if (!init_region( &tmprgn, srcObj->rgn.numRects )) goto done;
1268 if (!REGION_OffsetRegion( &destObj->rgn, &srcObj->rgn, -x, 0)) goto done;
1269 if (!REGION_OffsetRegion( &tmprgn, &srcObj->rgn, x, 0)) goto done;
1270 if (!REGION_IntersectRegion( &destObj->rgn, &destObj->rgn, &tmprgn )) goto done;
1271 if (!REGION_OffsetRegion( &tmprgn, &srcObj->rgn, 0, -y)) goto done;
1272 if (!REGION_IntersectRegion( &destObj->rgn, &destObj->rgn, &tmprgn )) goto done;
1273 if (!REGION_OffsetRegion( &tmprgn, &srcObj->rgn, 0, y)) goto done;
1274 if (!REGION_IntersectRegion( &destObj->rgn, &destObj->rgn, &tmprgn )) goto done;
1275 if (!REGION_SubtractRegion( &destObj->rgn, &srcObj->rgn, &destObj->rgn )) goto done;
1276 bRet = TRUE;
1278 done:
1279 HeapFree( GetProcessHeap(), 0, tmprgn.rects );
1280 if (destObj) GDI_ReleaseObj ( hDest );
1281 GDI_ReleaseObj( hSrc );
1282 return bRet;
1286 /***********************************************************************
1287 * CombineRgn (GDI32.@)
1289 * Combines two regions with the specified operation and stores the result
1290 * in the specified destination region.
1292 * PARAMS
1293 * hDest [I] The region that receives the combined result.
1294 * hSrc1 [I] The first source region.
1295 * hSrc2 [I] The second source region.
1296 * mode [I] The way in which the source regions will be combined. See notes.
1298 * RETURNS
1299 * Success:
1300 * NULLREGION - The new region is empty.
1301 * SIMPLEREGION - The new region can be represented by one rectangle.
1302 * COMPLEXREGION - The new region can only be represented by more than
1303 * one rectangle.
1304 * Failure: ERROR
1306 * NOTES
1307 * The two source regions can be the same region.
1308 * The mode can be one of the following:
1309 *| RGN_AND - Intersection of the regions
1310 *| RGN_OR - Union of the regions
1311 *| RGN_XOR - Unions of the regions minus any intersection.
1312 *| RGN_DIFF - Difference (subtraction) of the regions.
1314 INT WINAPI CombineRgn(HRGN hDest, HRGN hSrc1, HRGN hSrc2, INT mode)
1316 RGNOBJ *destObj = GDI_GetObjPtr( hDest, OBJ_REGION );
1317 INT result = ERROR;
1319 TRACE(" %p,%p -> %p mode=%x\n", hSrc1, hSrc2, hDest, mode );
1320 if (destObj)
1322 RGNOBJ *src1Obj = GDI_GetObjPtr( hSrc1, OBJ_REGION );
1324 if (src1Obj)
1326 TRACE("dump src1Obj:\n");
1327 if(TRACE_ON(region))
1328 REGION_DumpRegion(&src1Obj->rgn);
1329 if (mode == RGN_COPY)
1331 if (REGION_CopyRegion( &destObj->rgn, &src1Obj->rgn ))
1332 result = get_region_type( destObj );
1334 else
1336 RGNOBJ *src2Obj = GDI_GetObjPtr( hSrc2, OBJ_REGION );
1338 if (src2Obj)
1340 TRACE("dump src2Obj:\n");
1341 if(TRACE_ON(region))
1342 REGION_DumpRegion(&src2Obj->rgn);
1343 switch (mode)
1345 case RGN_AND:
1346 if (REGION_IntersectRegion( &destObj->rgn, &src1Obj->rgn, &src2Obj->rgn ))
1347 result = get_region_type( destObj );
1348 break;
1349 case RGN_OR:
1350 if (REGION_UnionRegion( &destObj->rgn, &src1Obj->rgn, &src2Obj->rgn ))
1351 result = get_region_type( destObj );
1352 break;
1353 case RGN_XOR:
1354 if (REGION_XorRegion( &destObj->rgn, &src1Obj->rgn, &src2Obj->rgn ))
1355 result = get_region_type( destObj );
1356 break;
1357 case RGN_DIFF:
1358 if (REGION_SubtractRegion( &destObj->rgn, &src1Obj->rgn, &src2Obj->rgn ))
1359 result = get_region_type( destObj );
1360 break;
1362 GDI_ReleaseObj( hSrc2 );
1365 GDI_ReleaseObj( hSrc1 );
1367 TRACE("dump destObj:\n");
1368 if(TRACE_ON(region))
1369 REGION_DumpRegion(&destObj->rgn);
1371 GDI_ReleaseObj( hDest );
1373 return result;
1376 /***********************************************************************
1377 * REGION_SetExtents
1378 * Re-calculate the extents of a region
1380 static void REGION_SetExtents (WINEREGION *pReg)
1382 RECT *pRect, *pRectEnd, *pExtents;
1384 if (pReg->numRects == 0)
1386 pReg->extents.left = 0;
1387 pReg->extents.top = 0;
1388 pReg->extents.right = 0;
1389 pReg->extents.bottom = 0;
1390 return;
1393 pExtents = &pReg->extents;
1394 pRect = pReg->rects;
1395 pRectEnd = &pRect[pReg->numRects - 1];
1398 * Since pRect is the first rectangle in the region, it must have the
1399 * smallest top and since pRectEnd is the last rectangle in the region,
1400 * it must have the largest bottom, because of banding. Initialize left and
1401 * right from pRect and pRectEnd, resp., as good things to initialize them
1402 * to...
1404 pExtents->left = pRect->left;
1405 pExtents->top = pRect->top;
1406 pExtents->right = pRectEnd->right;
1407 pExtents->bottom = pRectEnd->bottom;
1409 while (pRect <= pRectEnd)
1411 if (pRect->left < pExtents->left)
1412 pExtents->left = pRect->left;
1413 if (pRect->right > pExtents->right)
1414 pExtents->right = pRect->right;
1415 pRect++;
1419 /***********************************************************************
1420 * REGION_CopyRegion
1422 static BOOL REGION_CopyRegion(WINEREGION *dst, WINEREGION *src)
1424 if (dst != src) /* don't want to copy to itself */
1426 if (dst->size < src->numRects)
1428 RECT *rects = HeapReAlloc( GetProcessHeap(), 0, dst->rects, src->numRects * sizeof(RECT) );
1429 if (!rects) return FALSE;
1430 dst->rects = rects;
1431 dst->size = src->numRects;
1433 dst->numRects = src->numRects;
1434 dst->extents.left = src->extents.left;
1435 dst->extents.top = src->extents.top;
1436 dst->extents.right = src->extents.right;
1437 dst->extents.bottom = src->extents.bottom;
1438 memcpy(dst->rects, src->rects, src->numRects * sizeof(RECT));
1440 return TRUE;
1443 /***********************************************************************
1444 * REGION_Coalesce
1446 * Attempt to merge the rects in the current band with those in the
1447 * previous one. Used only by REGION_RegionOp.
1449 * Results:
1450 * The new index for the previous band.
1452 * Side Effects:
1453 * If coalescing takes place:
1454 * - rectangles in the previous band will have their bottom fields
1455 * altered.
1456 * - pReg->numRects will be decreased.
1459 static INT REGION_Coalesce (
1460 WINEREGION *pReg, /* Region to coalesce */
1461 INT prevStart, /* Index of start of previous band */
1462 INT curStart /* Index of start of current band */
1464 RECT *pPrevRect; /* Current rect in previous band */
1465 RECT *pCurRect; /* Current rect in current band */
1466 RECT *pRegEnd; /* End of region */
1467 INT curNumRects; /* Number of rectangles in current band */
1468 INT prevNumRects; /* Number of rectangles in previous band */
1469 INT bandtop; /* top coordinate for current band */
1471 pRegEnd = &pReg->rects[pReg->numRects];
1473 pPrevRect = &pReg->rects[prevStart];
1474 prevNumRects = curStart - prevStart;
1477 * Figure out how many rectangles are in the current band. Have to do
1478 * this because multiple bands could have been added in REGION_RegionOp
1479 * at the end when one region has been exhausted.
1481 pCurRect = &pReg->rects[curStart];
1482 bandtop = pCurRect->top;
1483 for (curNumRects = 0;
1484 (pCurRect != pRegEnd) && (pCurRect->top == bandtop);
1485 curNumRects++)
1487 pCurRect++;
1490 if (pCurRect != pRegEnd)
1493 * If more than one band was added, we have to find the start
1494 * of the last band added so the next coalescing job can start
1495 * at the right place... (given when multiple bands are added,
1496 * this may be pointless -- see above).
1498 pRegEnd--;
1499 while (pRegEnd[-1].top == pRegEnd->top)
1501 pRegEnd--;
1503 curStart = pRegEnd - pReg->rects;
1504 pRegEnd = pReg->rects + pReg->numRects;
1507 if ((curNumRects == prevNumRects) && (curNumRects != 0)) {
1508 pCurRect -= curNumRects;
1510 * The bands may only be coalesced if the bottom of the previous
1511 * matches the top scanline of the current.
1513 if (pPrevRect->bottom == pCurRect->top)
1516 * Make sure the bands have rects in the same places. This
1517 * assumes that rects have been added in such a way that they
1518 * cover the most area possible. I.e. two rects in a band must
1519 * have some horizontal space between them.
1523 if ((pPrevRect->left != pCurRect->left) ||
1524 (pPrevRect->right != pCurRect->right))
1527 * The bands don't line up so they can't be coalesced.
1529 return (curStart);
1531 pPrevRect++;
1532 pCurRect++;
1533 prevNumRects -= 1;
1534 } while (prevNumRects != 0);
1536 pReg->numRects -= curNumRects;
1537 pCurRect -= curNumRects;
1538 pPrevRect -= curNumRects;
1541 * The bands may be merged, so set the bottom of each rect
1542 * in the previous band to that of the corresponding rect in
1543 * the current band.
1547 pPrevRect->bottom = pCurRect->bottom;
1548 pPrevRect++;
1549 pCurRect++;
1550 curNumRects -= 1;
1551 } while (curNumRects != 0);
1554 * If only one band was added to the region, we have to backup
1555 * curStart to the start of the previous band.
1557 * If more than one band was added to the region, copy the
1558 * other bands down. The assumption here is that the other bands
1559 * came from the same region as the current one and no further
1560 * coalescing can be done on them since it's all been done
1561 * already... curStart is already in the right place.
1563 if (pCurRect == pRegEnd)
1565 curStart = prevStart;
1567 else
1571 *pPrevRect++ = *pCurRect++;
1572 } while (pCurRect != pRegEnd);
1577 return (curStart);
1580 /***********************************************************************
1581 * REGION_RegionOp
1583 * Apply an operation to two regions. Called by REGION_Union,
1584 * REGION_Inverse, REGION_Subtract, REGION_Intersect...
1586 * Results:
1587 * None.
1589 * Side Effects:
1590 * The new region is overwritten.
1592 * Notes:
1593 * The idea behind this function is to view the two regions as sets.
1594 * Together they cover a rectangle of area that this function divides
1595 * into horizontal bands where points are covered only by one region
1596 * or by both. For the first case, the nonOverlapFunc is called with
1597 * each the band and the band's upper and lower extents. For the
1598 * second, the overlapFunc is called to process the entire band. It
1599 * is responsible for clipping the rectangles in the band, though
1600 * this function provides the boundaries.
1601 * At the end of each band, the new region is coalesced, if possible,
1602 * to reduce the number of rectangles in the region.
1605 static BOOL REGION_RegionOp(
1606 WINEREGION *destReg, /* Place to store result */
1607 WINEREGION *reg1, /* First region in operation */
1608 WINEREGION *reg2, /* 2nd region in operation */
1609 BOOL (*overlapFunc)(WINEREGION*, RECT*, RECT*, RECT*, RECT*, INT, INT), /* Function to call for over-lapping bands */
1610 BOOL (*nonOverlap1Func)(WINEREGION*, RECT*, RECT*, INT, INT), /* Function to call for non-overlapping bands in region 1 */
1611 BOOL (*nonOverlap2Func)(WINEREGION*, RECT*, RECT*, INT, INT) /* Function to call for non-overlapping bands in region 2 */
1613 WINEREGION newReg;
1614 RECT *r1; /* Pointer into first region */
1615 RECT *r2; /* Pointer into 2d region */
1616 RECT *r1End; /* End of 1st region */
1617 RECT *r2End; /* End of 2d region */
1618 INT ybot; /* Bottom of intersection */
1619 INT ytop; /* Top of intersection */
1620 INT prevBand; /* Index of start of
1621 * previous band in newReg */
1622 INT curBand; /* Index of start of current
1623 * band in newReg */
1624 RECT *r1BandEnd; /* End of current band in r1 */
1625 RECT *r2BandEnd; /* End of current band in r2 */
1626 INT top; /* Top of non-overlapping band */
1627 INT bot; /* Bottom of non-overlapping band */
1630 * Initialization:
1631 * set r1, r2, r1End and r2End appropriately, preserve the important
1632 * parts of the destination region until the end in case it's one of
1633 * the two source regions, then mark the "new" region empty, allocating
1634 * another array of rectangles for it to use.
1636 r1 = reg1->rects;
1637 r2 = reg2->rects;
1638 r1End = r1 + reg1->numRects;
1639 r2End = r2 + reg2->numRects;
1642 * Allocate a reasonable number of rectangles for the new region. The idea
1643 * is to allocate enough so the individual functions don't need to
1644 * reallocate and copy the array, which is time consuming, yet we don't
1645 * have to worry about using too much memory. I hope to be able to
1646 * nuke the Xrealloc() at the end of this function eventually.
1648 if (!init_region( &newReg, max(reg1->numRects,reg2->numRects) * 2 )) return FALSE;
1651 * Initialize ybot and ytop.
1652 * In the upcoming loop, ybot and ytop serve different functions depending
1653 * on whether the band being handled is an overlapping or non-overlapping
1654 * band.
1655 * In the case of a non-overlapping band (only one of the regions
1656 * has points in the band), ybot is the bottom of the most recent
1657 * intersection and thus clips the top of the rectangles in that band.
1658 * ytop is the top of the next intersection between the two regions and
1659 * serves to clip the bottom of the rectangles in the current band.
1660 * For an overlapping band (where the two regions intersect), ytop clips
1661 * the top of the rectangles of both regions and ybot clips the bottoms.
1663 if (reg1->extents.top < reg2->extents.top)
1664 ybot = reg1->extents.top;
1665 else
1666 ybot = reg2->extents.top;
1669 * prevBand serves to mark the start of the previous band so rectangles
1670 * can be coalesced into larger rectangles. qv. miCoalesce, above.
1671 * In the beginning, there is no previous band, so prevBand == curBand
1672 * (curBand is set later on, of course, but the first band will always
1673 * start at index 0). prevBand and curBand must be indices because of
1674 * the possible expansion, and resultant moving, of the new region's
1675 * array of rectangles.
1677 prevBand = 0;
1681 curBand = newReg.numRects;
1684 * This algorithm proceeds one source-band (as opposed to a
1685 * destination band, which is determined by where the two regions
1686 * intersect) at a time. r1BandEnd and r2BandEnd serve to mark the
1687 * rectangle after the last one in the current band for their
1688 * respective regions.
1690 r1BandEnd = r1;
1691 while ((r1BandEnd != r1End) && (r1BandEnd->top == r1->top))
1693 r1BandEnd++;
1696 r2BandEnd = r2;
1697 while ((r2BandEnd != r2End) && (r2BandEnd->top == r2->top))
1699 r2BandEnd++;
1703 * First handle the band that doesn't intersect, if any.
1705 * Note that attention is restricted to one band in the
1706 * non-intersecting region at once, so if a region has n
1707 * bands between the current position and the next place it overlaps
1708 * the other, this entire loop will be passed through n times.
1710 if (r1->top < r2->top)
1712 top = max(r1->top,ybot);
1713 bot = min(r1->bottom,r2->top);
1715 if ((top != bot) && (nonOverlap1Func != NULL))
1717 if (!nonOverlap1Func(&newReg, r1, r1BandEnd, top, bot)) return FALSE;
1720 ytop = r2->top;
1722 else if (r2->top < r1->top)
1724 top = max(r2->top,ybot);
1725 bot = min(r2->bottom,r1->top);
1727 if ((top != bot) && (nonOverlap2Func != NULL))
1729 if (!nonOverlap2Func(&newReg, r2, r2BandEnd, top, bot)) return FALSE;
1732 ytop = r1->top;
1734 else
1736 ytop = r1->top;
1740 * If any rectangles got added to the region, try and coalesce them
1741 * with rectangles from the previous band. Note we could just do
1742 * this test in miCoalesce, but some machines incur a not
1743 * inconsiderable cost for function calls, so...
1745 if (newReg.numRects != curBand)
1747 prevBand = REGION_Coalesce (&newReg, prevBand, curBand);
1751 * Now see if we've hit an intersecting band. The two bands only
1752 * intersect if ybot > ytop
1754 ybot = min(r1->bottom, r2->bottom);
1755 curBand = newReg.numRects;
1756 if (ybot > ytop)
1758 if (!overlapFunc(&newReg, r1, r1BandEnd, r2, r2BandEnd, ytop, ybot)) return FALSE;
1761 if (newReg.numRects != curBand)
1763 prevBand = REGION_Coalesce (&newReg, prevBand, curBand);
1767 * If we've finished with a band (bottom == ybot) we skip forward
1768 * in the region to the next band.
1770 if (r1->bottom == ybot)
1772 r1 = r1BandEnd;
1774 if (r2->bottom == ybot)
1776 r2 = r2BandEnd;
1778 } while ((r1 != r1End) && (r2 != r2End));
1781 * Deal with whichever region still has rectangles left.
1783 curBand = newReg.numRects;
1784 if (r1 != r1End)
1786 if (nonOverlap1Func != NULL)
1790 r1BandEnd = r1;
1791 while ((r1BandEnd < r1End) && (r1BandEnd->top == r1->top))
1793 r1BandEnd++;
1795 if (!nonOverlap1Func(&newReg, r1, r1BandEnd, max(r1->top,ybot), r1->bottom))
1796 return FALSE;
1797 r1 = r1BandEnd;
1798 } while (r1 != r1End);
1801 else if ((r2 != r2End) && (nonOverlap2Func != NULL))
1805 r2BandEnd = r2;
1806 while ((r2BandEnd < r2End) && (r2BandEnd->top == r2->top))
1808 r2BandEnd++;
1810 if (!nonOverlap2Func(&newReg, r2, r2BandEnd, max(r2->top,ybot), r2->bottom))
1811 return FALSE;
1812 r2 = r2BandEnd;
1813 } while (r2 != r2End);
1816 if (newReg.numRects != curBand)
1818 REGION_Coalesce (&newReg, prevBand, curBand);
1822 * A bit of cleanup. To keep regions from growing without bound,
1823 * we shrink the array of rectangles to match the new number of
1824 * rectangles in the region. This never goes to 0, however...
1826 * Only do this stuff if the number of rectangles allocated is more than
1827 * twice the number of rectangles in the region (a simple optimization...).
1829 if ((newReg.numRects < (newReg.size >> 1)) && (newReg.numRects > 2))
1831 RECT *new_rects = HeapReAlloc( GetProcessHeap(), 0, newReg.rects, newReg.numRects * sizeof(RECT) );
1832 if (new_rects)
1834 newReg.rects = new_rects;
1835 newReg.size = newReg.numRects;
1838 HeapFree( GetProcessHeap(), 0, destReg->rects );
1839 destReg->rects = newReg.rects;
1840 destReg->size = newReg.size;
1841 destReg->numRects = newReg.numRects;
1842 return TRUE;
1845 /***********************************************************************
1846 * Region Intersection
1847 ***********************************************************************/
1850 /***********************************************************************
1851 * REGION_IntersectO
1853 * Handle an overlapping band for REGION_Intersect.
1855 * Results:
1856 * None.
1858 * Side Effects:
1859 * Rectangles may be added to the region.
1862 static BOOL REGION_IntersectO(WINEREGION *pReg, RECT *r1, RECT *r1End,
1863 RECT *r2, RECT *r2End, INT top, INT bottom)
1866 INT left, right;
1868 while ((r1 != r1End) && (r2 != r2End))
1870 left = max(r1->left, r2->left);
1871 right = min(r1->right, r2->right);
1874 * If there's any overlap between the two rectangles, add that
1875 * overlap to the new region.
1876 * There's no need to check for subsumption because the only way
1877 * such a need could arise is if some region has two rectangles
1878 * right next to each other. Since that should never happen...
1880 if (left < right)
1882 if (!add_rect( pReg, left, top, right, bottom )) return FALSE;
1886 * Need to advance the pointers. Shift the one that extends
1887 * to the right the least, since the other still has a chance to
1888 * overlap with that region's next rectangle, if you see what I mean.
1890 if (r1->right < r2->right)
1892 r1++;
1894 else if (r2->right < r1->right)
1896 r2++;
1898 else
1900 r1++;
1901 r2++;
1904 return TRUE;
1907 /***********************************************************************
1908 * REGION_IntersectRegion
1910 static BOOL REGION_IntersectRegion(WINEREGION *newReg, WINEREGION *reg1,
1911 WINEREGION *reg2)
1913 /* check for trivial reject */
1914 if ( (!(reg1->numRects)) || (!(reg2->numRects)) ||
1915 (!EXTENTCHECK(&reg1->extents, &reg2->extents)))
1916 newReg->numRects = 0;
1917 else
1918 if (!REGION_RegionOp (newReg, reg1, reg2, REGION_IntersectO, NULL, NULL)) return FALSE;
1921 * Can't alter newReg's extents before we call miRegionOp because
1922 * it might be one of the source regions and miRegionOp depends
1923 * on the extents of those regions being the same. Besides, this
1924 * way there's no checking against rectangles that will be nuked
1925 * due to coalescing, so we have to examine fewer rectangles.
1927 REGION_SetExtents(newReg);
1928 return TRUE;
1931 /***********************************************************************
1932 * Region Union
1933 ***********************************************************************/
1935 /***********************************************************************
1936 * REGION_UnionNonO
1938 * Handle a non-overlapping band for the union operation. Just
1939 * Adds the rectangles into the region. Doesn't have to check for
1940 * subsumption or anything.
1942 * Results:
1943 * None.
1945 * Side Effects:
1946 * pReg->numRects is incremented and the final rectangles overwritten
1947 * with the rectangles we're passed.
1950 static BOOL REGION_UnionNonO(WINEREGION *pReg, RECT *r, RECT *rEnd, INT top, INT bottom)
1952 while (r != rEnd)
1954 if (!add_rect( pReg, r->left, top, r->right, bottom )) return FALSE;
1955 r++;
1957 return TRUE;
1960 /***********************************************************************
1961 * REGION_UnionO
1963 * Handle an overlapping band for the union operation. Picks the
1964 * left-most rectangle each time and merges it into the region.
1966 * Results:
1967 * None.
1969 * Side Effects:
1970 * Rectangles are overwritten in pReg->rects and pReg->numRects will
1971 * be changed.
1974 static BOOL REGION_UnionO (WINEREGION *pReg, RECT *r1, RECT *r1End,
1975 RECT *r2, RECT *r2End, INT top, INT bottom)
1977 #define MERGERECT(r) \
1978 if ((pReg->numRects != 0) && \
1979 (pReg->rects[pReg->numRects-1].top == top) && \
1980 (pReg->rects[pReg->numRects-1].bottom == bottom) && \
1981 (pReg->rects[pReg->numRects-1].right >= r->left)) \
1983 if (pReg->rects[pReg->numRects-1].right < r->right) \
1984 pReg->rects[pReg->numRects-1].right = r->right; \
1986 else \
1988 if (!add_rect( pReg, r->left, top, r->right, bottom )) return FALSE; \
1990 r++;
1992 while ((r1 != r1End) && (r2 != r2End))
1994 if (r1->left < r2->left)
1996 MERGERECT(r1);
1998 else
2000 MERGERECT(r2);
2004 if (r1 != r1End)
2008 MERGERECT(r1);
2009 } while (r1 != r1End);
2011 else while (r2 != r2End)
2013 MERGERECT(r2);
2015 return TRUE;
2016 #undef MERGERECT
2019 /***********************************************************************
2020 * REGION_UnionRegion
2022 static BOOL REGION_UnionRegion(WINEREGION *newReg, WINEREGION *reg1, WINEREGION *reg2)
2024 BOOL ret = TRUE;
2026 /* checks all the simple cases */
2029 * Region 1 and 2 are the same or region 1 is empty
2031 if ( (reg1 == reg2) || (!(reg1->numRects)) )
2033 if (newReg != reg2)
2034 ret = REGION_CopyRegion(newReg, reg2);
2035 return ret;
2039 * if nothing to union (region 2 empty)
2041 if (!(reg2->numRects))
2043 if (newReg != reg1)
2044 ret = REGION_CopyRegion(newReg, reg1);
2045 return ret;
2049 * Region 1 completely subsumes region 2
2051 if ((reg1->numRects == 1) &&
2052 (reg1->extents.left <= reg2->extents.left) &&
2053 (reg1->extents.top <= reg2->extents.top) &&
2054 (reg1->extents.right >= reg2->extents.right) &&
2055 (reg1->extents.bottom >= reg2->extents.bottom))
2057 if (newReg != reg1)
2058 ret = REGION_CopyRegion(newReg, reg1);
2059 return ret;
2063 * Region 2 completely subsumes region 1
2065 if ((reg2->numRects == 1) &&
2066 (reg2->extents.left <= reg1->extents.left) &&
2067 (reg2->extents.top <= reg1->extents.top) &&
2068 (reg2->extents.right >= reg1->extents.right) &&
2069 (reg2->extents.bottom >= reg1->extents.bottom))
2071 if (newReg != reg2)
2072 ret = REGION_CopyRegion(newReg, reg2);
2073 return ret;
2076 if ((ret = REGION_RegionOp (newReg, reg1, reg2, REGION_UnionO, REGION_UnionNonO, REGION_UnionNonO)))
2078 newReg->extents.left = min(reg1->extents.left, reg2->extents.left);
2079 newReg->extents.top = min(reg1->extents.top, reg2->extents.top);
2080 newReg->extents.right = max(reg1->extents.right, reg2->extents.right);
2081 newReg->extents.bottom = max(reg1->extents.bottom, reg2->extents.bottom);
2083 return ret;
2086 /***********************************************************************
2087 * Region Subtraction
2088 ***********************************************************************/
2090 /***********************************************************************
2091 * REGION_SubtractNonO1
2093 * Deal with non-overlapping band for subtraction. Any parts from
2094 * region 2 we discard. Anything from region 1 we add to the region.
2096 * Results:
2097 * None.
2099 * Side Effects:
2100 * pReg may be affected.
2103 static BOOL REGION_SubtractNonO1 (WINEREGION *pReg, RECT *r, RECT *rEnd, INT top, INT bottom)
2105 while (r != rEnd)
2107 if (!add_rect( pReg, r->left, top, r->right, bottom )) return FALSE;
2108 r++;
2110 return TRUE;
2114 /***********************************************************************
2115 * REGION_SubtractO
2117 * Overlapping band subtraction. x1 is the left-most point not yet
2118 * checked.
2120 * Results:
2121 * None.
2123 * Side Effects:
2124 * pReg may have rectangles added to it.
2127 static BOOL REGION_SubtractO (WINEREGION *pReg, RECT *r1, RECT *r1End,
2128 RECT *r2, RECT *r2End, INT top, INT bottom)
2130 INT left = r1->left;
2132 while ((r1 != r1End) && (r2 != r2End))
2134 if (r2->right <= left)
2137 * Subtrahend missed the boat: go to next subtrahend.
2139 r2++;
2141 else if (r2->left <= left)
2144 * Subtrahend precedes minuend: nuke left edge of minuend.
2146 left = r2->right;
2147 if (left >= r1->right)
2150 * Minuend completely covered: advance to next minuend and
2151 * reset left fence to edge of new minuend.
2153 r1++;
2154 if (r1 != r1End)
2155 left = r1->left;
2157 else
2160 * Subtrahend now used up since it doesn't extend beyond
2161 * minuend
2163 r2++;
2166 else if (r2->left < r1->right)
2169 * Left part of subtrahend covers part of minuend: add uncovered
2170 * part of minuend to region and skip to next subtrahend.
2172 if (!add_rect( pReg, left, top, r2->left, bottom )) return FALSE;
2173 left = r2->right;
2174 if (left >= r1->right)
2177 * Minuend used up: advance to new...
2179 r1++;
2180 if (r1 != r1End)
2181 left = r1->left;
2183 else
2186 * Subtrahend used up
2188 r2++;
2191 else
2194 * Minuend used up: add any remaining piece before advancing.
2196 if (r1->right > left)
2198 if (!add_rect( pReg, left, top, r1->right, bottom )) return FALSE;
2200 r1++;
2201 left = r1->left;
2206 * Add remaining minuend rectangles to region.
2208 while (r1 != r1End)
2210 if (!add_rect( pReg, left, top, r1->right, bottom )) return FALSE;
2211 r1++;
2212 if (r1 != r1End)
2214 left = r1->left;
2217 return TRUE;
2220 /***********************************************************************
2221 * REGION_SubtractRegion
2223 * Subtract regS from regM and leave the result in regD.
2224 * S stands for subtrahend, M for minuend and D for difference.
2226 * Results:
2227 * TRUE.
2229 * Side Effects:
2230 * regD is overwritten.
2233 static BOOL REGION_SubtractRegion(WINEREGION *regD, WINEREGION *regM, WINEREGION *regS )
2235 /* check for trivial reject */
2236 if ( (!(regM->numRects)) || (!(regS->numRects)) ||
2237 (!EXTENTCHECK(&regM->extents, &regS->extents)) )
2238 return REGION_CopyRegion(regD, regM);
2240 if (!REGION_RegionOp (regD, regM, regS, REGION_SubtractO, REGION_SubtractNonO1, NULL))
2241 return FALSE;
2244 * Can't alter newReg's extents before we call miRegionOp because
2245 * it might be one of the source regions and miRegionOp depends
2246 * on the extents of those regions being the unaltered. Besides, this
2247 * way there's no checking against rectangles that will be nuked
2248 * due to coalescing, so we have to examine fewer rectangles.
2250 REGION_SetExtents (regD);
2251 return TRUE;
2254 /***********************************************************************
2255 * REGION_XorRegion
2257 static BOOL REGION_XorRegion(WINEREGION *dr, WINEREGION *sra, WINEREGION *srb)
2259 WINEREGION tra, trb;
2260 BOOL ret;
2262 if (!init_region( &tra, sra->numRects + 1 )) return FALSE;
2263 if ((ret = init_region( &trb, srb->numRects + 1 )))
2265 ret = REGION_SubtractRegion(&tra,sra,srb) &&
2266 REGION_SubtractRegion(&trb,srb,sra) &&
2267 REGION_UnionRegion(dr,&tra,&trb);
2268 destroy_region(&trb);
2270 destroy_region(&tra);
2271 return ret;
2274 /**************************************************************************
2276 * Poly Regions
2278 *************************************************************************/
2280 #define LARGE_COORDINATE 0x7fffffff /* FIXME */
2281 #define SMALL_COORDINATE 0x80000000
2283 /***********************************************************************
2284 * REGION_InsertEdgeInET
2286 * Insert the given edge into the edge table.
2287 * First we must find the correct bucket in the
2288 * Edge table, then find the right slot in the
2289 * bucket. Finally, we can insert it.
2292 static void REGION_InsertEdgeInET(EdgeTable *ET, EdgeTableEntry *ETE,
2293 INT scanline, ScanLineListBlock **SLLBlock, INT *iSLLBlock)
2296 EdgeTableEntry *start, *prev;
2297 ScanLineList *pSLL, *pPrevSLL;
2298 ScanLineListBlock *tmpSLLBlock;
2301 * find the right bucket to put the edge into
2303 pPrevSLL = &ET->scanlines;
2304 pSLL = pPrevSLL->next;
2305 while (pSLL && (pSLL->scanline < scanline))
2307 pPrevSLL = pSLL;
2308 pSLL = pSLL->next;
2312 * reassign pSLL (pointer to ScanLineList) if necessary
2314 if ((!pSLL) || (pSLL->scanline > scanline))
2316 if (*iSLLBlock > SLLSPERBLOCK-1)
2318 tmpSLLBlock = HeapAlloc( GetProcessHeap(), 0, sizeof(ScanLineListBlock));
2319 if(!tmpSLLBlock)
2321 WARN("Can't alloc SLLB\n");
2322 return;
2324 (*SLLBlock)->next = tmpSLLBlock;
2325 tmpSLLBlock->next = NULL;
2326 *SLLBlock = tmpSLLBlock;
2327 *iSLLBlock = 0;
2329 pSLL = &((*SLLBlock)->SLLs[(*iSLLBlock)++]);
2331 pSLL->next = pPrevSLL->next;
2332 pSLL->edgelist = NULL;
2333 pPrevSLL->next = pSLL;
2335 pSLL->scanline = scanline;
2338 * now insert the edge in the right bucket
2340 prev = NULL;
2341 start = pSLL->edgelist;
2342 while (start && (start->bres.minor_axis < ETE->bres.minor_axis))
2344 prev = start;
2345 start = start->next;
2347 ETE->next = start;
2349 if (prev)
2350 prev->next = ETE;
2351 else
2352 pSLL->edgelist = ETE;
2355 /***********************************************************************
2356 * REGION_CreateEdgeTable
2358 * This routine creates the edge table for
2359 * scan converting polygons.
2360 * The Edge Table (ET) looks like:
2362 * EdgeTable
2363 * --------
2364 * | ymax | ScanLineLists
2365 * |scanline|-->------------>-------------->...
2366 * -------- |scanline| |scanline|
2367 * |edgelist| |edgelist|
2368 * --------- ---------
2369 * | |
2370 * | |
2371 * V V
2372 * list of ETEs list of ETEs
2374 * where ETE is an EdgeTableEntry data structure,
2375 * and there is one ScanLineList per scanline at
2376 * which an edge is initially entered.
2379 static void REGION_CreateETandAET(const INT *Count, INT nbpolygons,
2380 const POINT *pts, EdgeTable *ET, EdgeTableEntry *AET,
2381 EdgeTableEntry *pETEs, ScanLineListBlock *pSLLBlock)
2383 const POINT *top, *bottom;
2384 const POINT *PrevPt, *CurrPt, *EndPt;
2385 INT poly, count;
2386 int iSLLBlock = 0;
2387 int dy;
2391 * initialize the Active Edge Table
2393 AET->next = NULL;
2394 AET->back = NULL;
2395 AET->nextWETE = NULL;
2396 AET->bres.minor_axis = SMALL_COORDINATE;
2399 * initialize the Edge Table.
2401 ET->scanlines.next = NULL;
2402 ET->ymax = SMALL_COORDINATE;
2403 ET->ymin = LARGE_COORDINATE;
2404 pSLLBlock->next = NULL;
2406 EndPt = pts - 1;
2407 for(poly = 0; poly < nbpolygons; poly++)
2409 count = Count[poly];
2410 EndPt += count;
2411 if(count < 2)
2412 continue;
2414 PrevPt = EndPt;
2417 * for each vertex in the array of points.
2418 * In this loop we are dealing with two vertices at
2419 * a time -- these make up one edge of the polygon.
2421 while (count--)
2423 CurrPt = pts++;
2426 * find out which point is above and which is below.
2428 if (PrevPt->y > CurrPt->y)
2430 bottom = PrevPt, top = CurrPt;
2431 pETEs->ClockWise = 0;
2433 else
2435 bottom = CurrPt, top = PrevPt;
2436 pETEs->ClockWise = 1;
2440 * don't add horizontal edges to the Edge table.
2442 if (bottom->y != top->y)
2444 pETEs->ymax = bottom->y-1;
2445 /* -1 so we don't get last scanline */
2448 * initialize integer edge algorithm
2450 dy = bottom->y - top->y;
2451 BRESINITPGONSTRUCT(dy, top->x, bottom->x, pETEs->bres);
2453 REGION_InsertEdgeInET(ET, pETEs, top->y, &pSLLBlock,
2454 &iSLLBlock);
2456 if (PrevPt->y > ET->ymax)
2457 ET->ymax = PrevPt->y;
2458 if (PrevPt->y < ET->ymin)
2459 ET->ymin = PrevPt->y;
2460 pETEs++;
2463 PrevPt = CurrPt;
2468 /***********************************************************************
2469 * REGION_loadAET
2471 * This routine moves EdgeTableEntries from the
2472 * EdgeTable into the Active Edge Table,
2473 * leaving them sorted by smaller x coordinate.
2476 static void REGION_loadAET(EdgeTableEntry *AET, EdgeTableEntry *ETEs)
2478 EdgeTableEntry *pPrevAET;
2479 EdgeTableEntry *tmp;
2481 pPrevAET = AET;
2482 AET = AET->next;
2483 while (ETEs)
2485 while (AET && (AET->bres.minor_axis < ETEs->bres.minor_axis))
2487 pPrevAET = AET;
2488 AET = AET->next;
2490 tmp = ETEs->next;
2491 ETEs->next = AET;
2492 if (AET)
2493 AET->back = ETEs;
2494 ETEs->back = pPrevAET;
2495 pPrevAET->next = ETEs;
2496 pPrevAET = ETEs;
2498 ETEs = tmp;
2502 /***********************************************************************
2503 * REGION_computeWAET
2505 * This routine links the AET by the
2506 * nextWETE (winding EdgeTableEntry) link for
2507 * use by the winding number rule. The final
2508 * Active Edge Table (AET) might look something
2509 * like:
2511 * AET
2512 * ---------- --------- ---------
2513 * |ymax | |ymax | |ymax |
2514 * | ... | |... | |... |
2515 * |next |->|next |->|next |->...
2516 * |nextWETE| |nextWETE| |nextWETE|
2517 * --------- --------- ^--------
2518 * | | |
2519 * V-------------------> V---> ...
2522 static void REGION_computeWAET(EdgeTableEntry *AET)
2524 register EdgeTableEntry *pWETE;
2525 register int inside = 1;
2526 register int isInside = 0;
2528 AET->nextWETE = NULL;
2529 pWETE = AET;
2530 AET = AET->next;
2531 while (AET)
2533 if (AET->ClockWise)
2534 isInside++;
2535 else
2536 isInside--;
2538 if ((!inside && !isInside) ||
2539 ( inside && isInside))
2541 pWETE->nextWETE = AET;
2542 pWETE = AET;
2543 inside = !inside;
2545 AET = AET->next;
2547 pWETE->nextWETE = NULL;
2550 /***********************************************************************
2551 * REGION_InsertionSort
2553 * Just a simple insertion sort using
2554 * pointers and back pointers to sort the Active
2555 * Edge Table.
2558 static BOOL REGION_InsertionSort(EdgeTableEntry *AET)
2560 EdgeTableEntry *pETEchase;
2561 EdgeTableEntry *pETEinsert;
2562 EdgeTableEntry *pETEchaseBackTMP;
2563 BOOL changed = FALSE;
2565 AET = AET->next;
2566 while (AET)
2568 pETEinsert = AET;
2569 pETEchase = AET;
2570 while (pETEchase->back->bres.minor_axis > AET->bres.minor_axis)
2571 pETEchase = pETEchase->back;
2573 AET = AET->next;
2574 if (pETEchase != pETEinsert)
2576 pETEchaseBackTMP = pETEchase->back;
2577 pETEinsert->back->next = AET;
2578 if (AET)
2579 AET->back = pETEinsert->back;
2580 pETEinsert->next = pETEchase;
2581 pETEchase->back->next = pETEinsert;
2582 pETEchase->back = pETEinsert;
2583 pETEinsert->back = pETEchaseBackTMP;
2584 changed = TRUE;
2587 return changed;
2590 /***********************************************************************
2591 * REGION_FreeStorage
2593 * Clean up our act.
2595 static void REGION_FreeStorage(ScanLineListBlock *pSLLBlock)
2597 ScanLineListBlock *tmpSLLBlock;
2599 while (pSLLBlock)
2601 tmpSLLBlock = pSLLBlock->next;
2602 HeapFree( GetProcessHeap(), 0, pSLLBlock );
2603 pSLLBlock = tmpSLLBlock;
2608 /***********************************************************************
2609 * REGION_PtsToRegion
2611 * Create an array of rectangles from a list of points.
2613 static BOOL REGION_PtsToRegion(int numFullPtBlocks, int iCurPtBlock,
2614 POINTBLOCK *FirstPtBlock, WINEREGION *reg)
2616 RECT *rects;
2617 POINT *pts;
2618 POINTBLOCK *CurPtBlock;
2619 int i;
2620 RECT *extents;
2621 INT numRects;
2623 extents = &reg->extents;
2625 numRects = ((numFullPtBlocks * NUMPTSTOBUFFER) + iCurPtBlock) >> 1;
2626 if (!init_region( reg, numRects )) return FALSE;
2628 reg->size = numRects;
2629 CurPtBlock = FirstPtBlock;
2630 rects = reg->rects - 1;
2631 numRects = 0;
2632 extents->left = LARGE_COORDINATE, extents->right = SMALL_COORDINATE;
2634 for ( ; numFullPtBlocks >= 0; numFullPtBlocks--) {
2635 /* the loop uses 2 points per iteration */
2636 i = NUMPTSTOBUFFER >> 1;
2637 if (!numFullPtBlocks)
2638 i = iCurPtBlock >> 1;
2639 for (pts = CurPtBlock->pts; i--; pts += 2) {
2640 if (pts->x == pts[1].x)
2641 continue;
2642 if (numRects && pts->x == rects->left && pts->y == rects->bottom &&
2643 pts[1].x == rects->right &&
2644 (numRects == 1 || rects[-1].top != rects->top) &&
2645 (i && pts[2].y > pts[1].y)) {
2646 rects->bottom = pts[1].y + 1;
2647 continue;
2649 numRects++;
2650 rects++;
2651 rects->left = pts->x; rects->top = pts->y;
2652 rects->right = pts[1].x; rects->bottom = pts[1].y + 1;
2653 if (rects->left < extents->left)
2654 extents->left = rects->left;
2655 if (rects->right > extents->right)
2656 extents->right = rects->right;
2658 CurPtBlock = CurPtBlock->next;
2661 if (numRects) {
2662 extents->top = reg->rects->top;
2663 extents->bottom = rects->bottom;
2664 } else {
2665 extents->left = 0;
2666 extents->top = 0;
2667 extents->right = 0;
2668 extents->bottom = 0;
2670 reg->numRects = numRects;
2672 return(TRUE);
2675 /***********************************************************************
2676 * CreatePolyPolygonRgn (GDI32.@)
2678 HRGN WINAPI CreatePolyPolygonRgn(const POINT *Pts, const INT *Count,
2679 INT nbpolygons, INT mode)
2681 HRGN hrgn = 0;
2682 RGNOBJ *obj;
2683 EdgeTableEntry *pAET; /* Active Edge Table */
2684 INT y; /* current scanline */
2685 int iPts = 0; /* number of pts in buffer */
2686 EdgeTableEntry *pWETE; /* Winding Edge Table Entry*/
2687 ScanLineList *pSLL; /* current scanLineList */
2688 POINT *pts; /* output buffer */
2689 EdgeTableEntry *pPrevAET; /* ptr to previous AET */
2690 EdgeTable ET; /* header node for ET */
2691 EdgeTableEntry AET; /* header node for AET */
2692 EdgeTableEntry *pETEs; /* EdgeTableEntries pool */
2693 ScanLineListBlock SLLBlock; /* header for scanlinelist */
2694 int fixWAET = FALSE;
2695 POINTBLOCK FirstPtBlock, *curPtBlock; /* PtBlock buffers */
2696 POINTBLOCK *tmpPtBlock;
2697 int numFullPtBlocks = 0;
2698 INT poly, total;
2700 TRACE("%p, count %d, polygons %d, mode %d\n", Pts, *Count, nbpolygons, mode);
2702 /* special case a rectangle */
2704 if (((nbpolygons == 1) && ((*Count == 4) ||
2705 ((*Count == 5) && (Pts[4].x == Pts[0].x) && (Pts[4].y == Pts[0].y)))) &&
2706 (((Pts[0].y == Pts[1].y) &&
2707 (Pts[1].x == Pts[2].x) &&
2708 (Pts[2].y == Pts[3].y) &&
2709 (Pts[3].x == Pts[0].x)) ||
2710 ((Pts[0].x == Pts[1].x) &&
2711 (Pts[1].y == Pts[2].y) &&
2712 (Pts[2].x == Pts[3].x) &&
2713 (Pts[3].y == Pts[0].y))))
2714 return CreateRectRgn( min(Pts[0].x, Pts[2].x), min(Pts[0].y, Pts[2].y),
2715 max(Pts[0].x, Pts[2].x), max(Pts[0].y, Pts[2].y) );
2717 for(poly = total = 0; poly < nbpolygons; poly++)
2718 total += Count[poly];
2719 if (! (pETEs = HeapAlloc( GetProcessHeap(), 0, sizeof(EdgeTableEntry) * total )))
2720 return 0;
2722 pts = FirstPtBlock.pts;
2723 REGION_CreateETandAET(Count, nbpolygons, Pts, &ET, &AET, pETEs, &SLLBlock);
2724 pSLL = ET.scanlines.next;
2725 curPtBlock = &FirstPtBlock;
2727 if (mode != WINDING) {
2729 * for each scanline
2731 for (y = ET.ymin; y < ET.ymax; y++) {
2733 * Add a new edge to the active edge table when we
2734 * get to the next edge.
2736 if (pSLL != NULL && y == pSLL->scanline) {
2737 REGION_loadAET(&AET, pSLL->edgelist);
2738 pSLL = pSLL->next;
2740 pPrevAET = &AET;
2741 pAET = AET.next;
2744 * for each active edge
2746 while (pAET) {
2747 pts->x = pAET->bres.minor_axis, pts->y = y;
2748 pts++, iPts++;
2751 * send out the buffer
2753 if (iPts == NUMPTSTOBUFFER) {
2754 tmpPtBlock = HeapAlloc( GetProcessHeap(), 0, sizeof(POINTBLOCK));
2755 if(!tmpPtBlock) goto done;
2756 curPtBlock->next = tmpPtBlock;
2757 curPtBlock = tmpPtBlock;
2758 pts = curPtBlock->pts;
2759 numFullPtBlocks++;
2760 iPts = 0;
2762 EVALUATEEDGEEVENODD(pAET, pPrevAET, y);
2764 REGION_InsertionSort(&AET);
2767 else {
2769 * for each scanline
2771 for (y = ET.ymin; y < ET.ymax; y++) {
2773 * Add a new edge to the active edge table when we
2774 * get to the next edge.
2776 if (pSLL != NULL && y == pSLL->scanline) {
2777 REGION_loadAET(&AET, pSLL->edgelist);
2778 REGION_computeWAET(&AET);
2779 pSLL = pSLL->next;
2781 pPrevAET = &AET;
2782 pAET = AET.next;
2783 pWETE = pAET;
2786 * for each active edge
2788 while (pAET) {
2790 * add to the buffer only those edges that
2791 * are in the Winding active edge table.
2793 if (pWETE == pAET) {
2794 pts->x = pAET->bres.minor_axis, pts->y = y;
2795 pts++, iPts++;
2798 * send out the buffer
2800 if (iPts == NUMPTSTOBUFFER) {
2801 tmpPtBlock = HeapAlloc( GetProcessHeap(), 0,
2802 sizeof(POINTBLOCK) );
2803 if(!tmpPtBlock) goto done;
2804 curPtBlock->next = tmpPtBlock;
2805 curPtBlock = tmpPtBlock;
2806 pts = curPtBlock->pts;
2807 numFullPtBlocks++;
2808 iPts = 0;
2810 pWETE = pWETE->nextWETE;
2812 EVALUATEEDGEWINDING(pAET, pPrevAET, y, fixWAET);
2816 * recompute the winding active edge table if
2817 * we just resorted or have exited an edge.
2819 if (REGION_InsertionSort(&AET) || fixWAET) {
2820 REGION_computeWAET(&AET);
2821 fixWAET = FALSE;
2826 if (!(obj = HeapAlloc( GetProcessHeap(), 0, sizeof(*obj) ))) goto done;
2828 if (!REGION_PtsToRegion(numFullPtBlocks, iPts, &FirstPtBlock, &obj->rgn))
2830 HeapFree( GetProcessHeap(), 0, obj );
2831 goto done;
2833 if (!(hrgn = alloc_gdi_handle( &obj->header, OBJ_REGION, &region_funcs )))
2835 HeapFree( GetProcessHeap(), 0, obj->rgn.rects );
2836 HeapFree( GetProcessHeap(), 0, obj );
2839 done:
2840 REGION_FreeStorage(SLLBlock.next);
2841 for (curPtBlock = FirstPtBlock.next; --numFullPtBlocks >= 0;) {
2842 tmpPtBlock = curPtBlock->next;
2843 HeapFree( GetProcessHeap(), 0, curPtBlock );
2844 curPtBlock = tmpPtBlock;
2846 HeapFree( GetProcessHeap(), 0, pETEs );
2847 return hrgn;
2851 /***********************************************************************
2852 * CreatePolygonRgn (GDI32.@)
2854 HRGN WINAPI CreatePolygonRgn( const POINT *points, INT count,
2855 INT mode )
2857 return CreatePolyPolygonRgn( points, &count, 1, mode );