Source

pygame / pygame / draw.py

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
#!/usr/bin/env python

'''Pygame module for drawing shapes.

Draw several simple shapes to a Surface. These functions will work for
rendering to any format of Surface. Rendering to hardware Surfaces will
be slower than regular software Surfaces.

Most of the functions take a width argument to represent the size of
stroke around the edge of the shape. If a width of 0 is passed the
function will actually solid fill the entire shape.

All the drawing functions respect the clip area for the Surface, and
will be constrained to that area. The functions return a rectangle
representing the bounding area of changed pixels.

Most of the arguments accept a color argument that is an RGB triplet.
These can also accept an RGBA quadruplet. The alpha value will be written
directly into the Surface if it contains pixel alphas, but the draw
function will not draw transparently. The color argument can also be an
integer pixel value that is already mapped to the Surface's pixel format.

These functions must temporarily lock the Surface they are operating on.
Many sequential drawing calls can be sped up by locking and unlocking
the Surface object around the draw calls.
'''

__docformat__ = 'restructuredtext'
__version__ = '$Id$'

from copy import copy

from SDL import *

import pygame.base
import pygame.rect

def _get_color(color, surface):
    rgba = pygame.base._rgba_from_obj(color)
    if rgba:
        color = SDL_MapRGBA(surface._surf.format, 
                            rgba[0], rgba[1], rgba[2], rgba[3])
    if type(color) not in (int, long):
        raise 'invalid color argument'
    return color

def _get_rect(rect):
    rect = copy(rect)
    rect.normalize()
    return rect._r

_LEFT = 0x1
_RIGHT = 0x2
_TOP = 0x4
_BOTTOM = 0x8

def _endpoint_code(x, y, l, r, t, b):
    code = 0
    if x < l:
        code |= _LEFT
    if y < t:
        code |= _TOP
    if x > r:
        code |= _RIGHT
    if y > b:
        code |= _BOTTOM
    return code

def _clip_line(x1, y1, x2, y2, left, right, top, bottom):
    while True:
        code1 = _endpoint_code(x1, y1, left, right, top, bottom)
        code2 = _endpoint_code(x2, y2, left, right, top, bottom)
        if code1 == 0 and code2 == 0:
            return x1, y1, x2, y2
        elif code1 & code2 != 0:
            return None, None, None, None
        else:
            if code1 == 0:
                x1, x2 = x2, x1
                y1, y2 = y2, y1
                code1 = code2
            if x1 != x2:
                m = (y2 - y1) / float(x2 - x1)
            else:
                m = 1.0         # impossible; trivial rejection
            if code1 & _LEFT:
                y1 += int((left - x1) * m)
                x1 = left
            if code1 & _RIGHT:
                y1 += int((right - x1) * m)
                x1 = right
            if code1 & _BOTTOM:
                if x1 != x2:
                    x1 += int((bottom - y1) / m)
                y1 = bottom
            if code1 & _TOP:
                if x1 != x2:
                    x1 += int((top - y1) / m)
                y1 = top

def rect(surface, color, rect, width=0):
    '''Draw a rectangle shape.

    Draws a rectangular shape on the Surface. The given Rect is the area of
    the rectangle. The width argument is the thickness to draw the outer edge.
    If width is zero then the rectangle will be filled.
     
    Keep in mind the Surface.fill() method works just as well for drawing
    filled rectangles. In fact the Surface.fill() can be hardware accelerated
    on some platforms with both software and hardware display modes.

    :Parameters:
        `surface` : `Surface`
            Surface to draw on.
        `color` : int, int, int
            RGB fill color.
        `rect` : `Rect` or int, int, int, int
            Rectangle boundary.
        `width` : int
            Edge thickness, or zero to fill region.

    :rtype: `Rect`
    :return: Affected bounding box.
    '''    
    color = _get_color(color, surface)
    rect = _get_rect(rect)
    if width == 0:
        SDL_FillRect(surface._surf, rect, color)
    else:
        # TODO clip edges wholly outside clip
        hw = width / 2
        r = SDL_Rect(rect.x, rect.y - hw, rect.w, width)
        SDL_FillRect(surface._surf, r, color)
        r.y += rect.h
        SDL_FillRect(surface._surf, r, color)
        r.x -= hw
        r.w = width
        r.y = rect.y
        r.h = rect.h + 1
        SDL_FillRect(surface._surf, r, color)
        r.x += rect.w
        SDL_FillRect(surface._surf, r, color)
        # XXX returned clip rectangle wrong
    return pygame.rect.Rect(rect)

def polygon(surface, color, pointlist, width=0):
    '''Draw a shape with any number of sides.

    Draws a polygonal shape on the Surface. The pointlist argument is the
    vertices of the polygon. The width argument is the thickness to draw the
    outer edge. If width is zero then the polygon will be filled.

    For aapolygon, use aalines with the 'closed' parameter.
    
    :Parameters:
        `surface` : `Surface`
            Surface to draw on.
        `color` : int, int, int
            RGB fill color.
        `pointlist` : list of (int, int)
            Each list element is a vertex of the polygon.
        `width` : int
            Edge thickness, or zero to fill region.

    :rtype: `Rect`
    :return: Affected bounding box.
    '''    
    if width > 0:
        return lines(surface, color, True, pointlist, width)

def circle(surface, color, pos, radius, width=0):
    '''Draw a circle around a point.

    Draws a circular shape on the Surface. The pos argument is the center of
    the circle, and radius is the size. The width argument is the thickness to
    draw the outer edge. If width is zero then the circle will be filled.

    :Parameters:
        `surface` : `Surface`
            Surface to draw on.
        `color` : int, int, int
            RGB fill color.
        `pos` : int, int
            Center point of circle.
        `radius` : int
            Radius of circle, in pixels.
        `width` : int
            Edge thickness, or zero to fill region.

    :rtype: `Rect`
    :return: Affected bounding box.
    '''     

def ellipse(surface, color, rect, width=0):
    '''Draw a round shape inside a rectangle.

    Draws an elliptical shape on the Surface. The given rectangle is the area
    that the circle will fill. The width argument is the thickness to draw the
    outer edge. If width is zero then the ellipse will be filled.
    
    :Parameters:
        `surface` : `Surface`
            Surface to draw on.
        `color` : int, int, int
            RGB fill color.
        `rect` : `Rect` or int, int, int, int
            Ellipse boundary.
        `width` : int
            Edge thickness, or zero to fill region.

    :rtype: `Rect`
    :return: Affected bounding box.
    '''     

def arc(surface, color, rect, start_angle, stop_angle, width=1):
    '''Draw a partial section of an ellipse.

    Draws an elliptical arc on the Surface. The rect argument is the area that
    the ellipse will fill. The two angle arguments are the initial and final
    angle in radians, with the zero on the right. The width argument is the
    thickness to draw the outer edge.

    :Parameters:
        `surface` : `Surface`
            Surface to draw on.
        `color` : int, int, int
            RGB fill color.
        `rect` : `Rect` or int, int, int, int
            Ellipse boundary.
        `start_angle` : float
            Angle to start drawing arc at, in radians.
        `stop_angle` : float
            Angle to stop drawing arc at, in radians.
        `width` : int
            Edge thickness.

    :rtype: `Rect`
    :return: Affected bounding box.
    '''     

def line(surface, color, start_pos, end_pos, width=1):
    '''Draw a straight line segment.

    Draw a straight line segment on a Surface. There are no endcaps, the
    ends are squared off for thick lines.

    :Parameters:
        `surface` : `Surface`
            Surface to draw on.
        `color` : int, int, int
            RGB fill color.
        `start_pos` : int, int
            X, Y coordinates of first vertex.
        `end_pos` : int, int
            X, Y coordinates of second vertex.
        `width` : int
            Line thickness.

    :rtype: `Rect`
    :return: Affected bounding box.
    '''
    if width < 1:
        return

    color = _get_color(color, surface)

    if start_pos[0] == end_pos[0]:
        # Vertical
        y1 = min(start_pos[1], end_pos[1])
        y2 = max(start_pos[1], end_pos[1])
        r = SDL_Rect(start_pos[0] - width / 2, y1, width, y2 - y1)
        SDL_FillRect(surface._surf, r, color)
    elif start_pos[1] == end_pos[1]:
        # Horizontal
        x1 = min(start_pos[0], end_pos[0])
        x2 = max(start_pos[0], end_pos[0])
        r = SDL_Rect(x1, start_pos[1] - width / 2, x2 - x1, width)
        SDL_FillRect(surface._surf, r, color)
    elif width > 1:
        # Optimise me (scanlines instead of multiple lines)
        if abs(end_pos[0] - start_pos[0]) > abs(end_pos[1] - start_pos[1]):
            xinc, yinc = 0, 1
        else:
            xinc, yinc = 1, 0
        x1 = start_pos[0] - width * xinc / 2
        y1 = start_pos[1] - width * yinc / 2
        x2 = end_pos[0] - width * xinc / 2
        y2 = end_pos[1] - width * yinc / 2
        for i in range(width):
            line(surface, color, (x1, y1), (x2, y2), 1)
            x1 += xinc
            y1 += yinc
            x2 += xinc
            y2 += yinc
    else:
        if surface._surf.format.BytesPerPixel == 3:
            raise NotImplementedError, 'TODO'

        clip = surface._surf.clip_rect
        x1, y1, x2, y2 = _clip_line(start_pos[0], start_pos[1], 
                                    end_pos[0], end_pos[1], 
                                    clip.x, clip.x + clip.w - 1,
                                    clip.y, clip.y + clip.h - 1)
        if x1 is None:
            return

        pixels = surface._surf.pixels.as_ctypes()
        pitch = surface._surf.pitch / surface._surf.format.BytesPerPixel
        dx = x2 - x1
        dy = y2 - y1
        signx = 1 - (dx < 0) * 2
        signy = 1 - (dy < 0) * 2
        dx = signx * dx + 1
        dy = signy * dy + 1
        pixel = y1 * pitch + x1
        incx = signx
        incy = signy * pitch
        if dx < dy:
            dx, dy = dy, dx
            incx, incy = incy, incx
        x = 0
        y = 0

        while x < dx:
            pixels[pixel] = color
            y += dy
            if y > dx:
                y -= dx
                pixel += incy
            x += 1
            pixel += incx

    return None # XXX return clipped rect
    
def lines(surface, color, closed, pointlist, width=1):
    '''Draw multiple contiguous line segments.

    Draw a sequence of lines on a Surface. The pointlist argument is a series
    of points that are connected by a line. If the closed argument is true an
    additional line segment is drawn between the first and last points.

    This does not draw any endcaps or miter joints. Lines with sharp corners
    and wide line widths can have improper looking corners.
    
    :Parameters:
        `surface` : `Surface`
            Surface to draw on.
        `color` : int, int, int
            RGB fill color.
        `closed` : bool
            True if line segments form a closed polygon, otherwise False.
        `pointlist` : list of (int, int)
            List of X, Y coordinates giving vertices.
        `width` : int
            Line thickness.

    :rtype: `Rect`
    :return: Affected bounding box.
    '''
    if width < 1:
        return

    color = _get_color(color, surface)

    if len(pointlist) < 2:
        raise ValueError, 'points argument must contain more than one point'

    last = pointlist[0]
    for point in pointlist[1:]:
        line(surface, color, last, point, width)
        last = point
    if closed:
        line(surface, color, last, pointlist[0], width)

    # XXX return clipped rect

def aaline(surface, color, startpos, endpos, blend=1):
    '''Draw a line with antialiasing.

    Draws an anti-aliased line on a surface. This will respect the clipping
    rectangle. A bounding box of the affected area is returned returned as a
    rectangle. If blend is true, the shades will be be blended with existing
    pixel shades instead of overwriting them. This function accepts floating
    point values for the end points. 
    
    :Parameters:
        `surface` : `Surface`
            Surface to draw on.
        `color` : int, int, int
            RGB fill color.
        `start_pos` : float, float
            X, Y coordinates of first vertex.
        `end_pos` : float, float
            X, Y coordinates of second vertex.
        `width` : int
            Line thickness.

    :rtype: `Rect`
    :return: Affected bounding box.
    '''

def aalines(surface, color, closed, pointlist, blend=1):
    '''Draw multiple contiguous line segments with antialiasing.

    Draws a sequence on a surface. You must pass at least two points in the
    sequence of points. The closed argument is a simple boolean and if true, a
    line will be draw between the first and last points. The boolean blend
    argument set to true will blend the shades with existing shades instead of
    overwriting them. This function accepts floating point values for the end
    points. 

    :Parameters:
        `surface` : `Surface`
            Surface to draw on.
        `color` : int, int, int
            RGB fill color.
        `closed` : bool
            True if line segments form a closed polygon, otherwise False.
        `pointlist` : list of (float, float)
            List of X, Y coordinates giving vertices.
        `width` : int
            Line thickness.

    :rtype: `Rect`
    :return: Affected bounding box.
    '''