Debian Codegraph @

src/pygame_sdl2/render.pyx

raw
1 # Copyright 2014 Patrick Dawson <[email protected]>
2 #
3 # This software is provided 'as-is', without any express or implied
4 # warranty. In no event will the authors be held liable for any damages
5 # arising from the use of this software.
6 #
7 # Permission is granted to anyone to use this software for any purpose,
8 # including commercial applications, and to alter it and redistribute it
9 # freely, subject to the following restrictions:
10 #
11 # 1. The origin of this software must not be misrepresented; you must not
12 # claim that you wrote the original software. If you use this software
13 # in a product, an acknowledgment in the product documentation would be
14 # appreciated but is not required.
15 # 2. Altered source versions must be plainly marked as such, and must not be
16 # misrepresented as being the original software.
17 # 3. This notice may not be removed or altered from any source distribution.
18
19 from sdl2 cimport *
20 from sdl2_image cimport *
21 from libc.string cimport memcpy, memset
22 from pygame_sdl2.display cimport *
23 from pygame_sdl2.surface cimport *
24 from pygame_sdl2.rwobject cimport to_rwops
25 from pygame_sdl2.rect cimport to_sdl_rect
26
27 from pygame_sdl2.rect import Rect
28 from pygame_sdl2.error import error
29 from pygame_sdl2.color import Color
30 import json
31 import warnings
32
33 BLENDMODE_NONE = SDL_BLENDMODE_NONE
34 BLENDMODE_BLEND = SDL_BLENDMODE_BLEND
35 BLENDMODE_ADD = SDL_BLENDMODE_ADD
36 BLENDMODE_MOD = SDL_BLENDMODE_MOD
37
38 cdef bint DEBUG_DRAW_BBOX = True
39
40 cdef rinfo_to_dict(SDL_RendererInfo *rinfo):
41 # Ignore texture_formats for now.
42 return {
43 "name" : rinfo.name,
44 "software" : rinfo.flags & SDL_RENDERER_SOFTWARE != 0,
45 "accelerated" : rinfo.flags & SDL_RENDERER_ACCELERATED != 0,
46 "vsync" : rinfo.flags & SDL_RENDERER_PRESENTVSYNC != 0,
47 "rtt" : rinfo.flags & SDL_RENDERER_TARGETTEXTURE != 0,
48 "max_texture_width" : rinfo.max_texture_width,
49 "max_texture_height" : rinfo.max_texture_height,
50 }
51
52 def get_drivers():
53 cdef SDL_RendererInfo rinfo
54 cdef int num_drivers
55 rv = []
56
57 num_drivers = SDL_GetNumRenderDrivers()
58 for n in range(num_drivers):
59 if SDL_GetRenderDriverInfo(n, &rinfo) != 0:
60 raise error()
61
62 rv.append(rinfo_to_dict(&rinfo))
63
64 return rv
65
66
67 cdef class Renderer:
68 cdef SDL_Renderer *renderer
69 cdef dict _info
70
71 def __cinit__(self):
72 self.renderer = NULL
73
74 def __dealloc__(self):
75 if self.renderer:
76 SDL_DestroyRenderer(self.renderer)
77
78 def __init__(self, Window window=None, vsync=False, driver=-1):
79 if window is None:
80 window = main_window
81
82 cdef uint32_t flags = SDL_RENDERER_ACCELERATED
83 if vsync:
84 flags |= SDL_RENDERER_PRESENTVSYNC
85
86 self.renderer = SDL_CreateRenderer(window.window, driver, flags)
87 if self.renderer == NULL:
88 self.renderer = SDL_GetRenderer(window.window)
89 if self.renderer == NULL:
90 raise error()
91
92 cdef SDL_RendererInfo rinfo
93 if SDL_GetRendererInfo(self.renderer, &rinfo) != 0:
94 raise error()
95
96 self._info = rinfo_to_dict(&rinfo)
97
98 if not self.info()["accelerated"]:
99 warnings.warn("Renderer is not accelerated.")
100
101 def load_texture(self, fi):
102 cdef SDL_Texture *tex
103 cdef Texture t = Texture()
104
105 if isinstance(fi, Surface):
106 tex = SDL_CreateTextureFromSurface(self.renderer, (<Surface>fi).surface)
107 else:
108 tex = IMG_LoadTexture_RW(self.renderer, to_rwops(fi), 1)
109
110 if tex == NULL:
111 raise error()
112
113 t.set(self.renderer, tex)
114 return TextureNode(t)
115
116 def load_atlas(self, filename):
117 """ Loads a file in the popular JSON (Hash) format exported by
118 TexturePacker and other software. """
119
120 return TextureAtlas(self, filename)
121
122 def render_present(self):
123 with nogil:
124 SDL_RenderPresent(self.renderer)
125
126 def info(self):
127 return self._info
128
129 cdef set_drawcolor(self, col):
130 if not isinstance(col, Color):
131 col = Color(col)
132 SDL_SetRenderDrawColor(self.renderer, col.r, col.g, col.b, col.a)
133
134 def clear(self, color):
135 self.set_drawcolor(color)
136 SDL_RenderClear(self.renderer)
137
138 def draw_line(self, color not None, x1, y1, x2, y2):
139 self.set_drawcolor(color)
140 if SDL_RenderDrawLine(self.renderer, x1, y1, x2, y2) != 0:
141 raise error()
142
143 def draw_point(self, color not None, x, y):
144 self.set_drawcolor(color)
145 SDL_RenderDrawPoint(self.renderer, x, y)
146
147 def draw_rect(self, color not None, rect):
148 cdef SDL_Rect r
149 to_sdl_rect(rect, &r)
150 self.set_drawcolor(color)
151 SDL_RenderDrawRect(self.renderer, &r)
152
153 def fill_rect(self, color not None, rect):
154 cdef SDL_Rect r
155 to_sdl_rect(rect, &r)
156 self.set_drawcolor(color)
157 SDL_RenderFillRect(self.renderer, &r)
158
159 def set_viewport(self, rect=None):
160 cdef SDL_Rect vprect
161 if rect is None:
162 SDL_RenderSetViewport(self.renderer, NULL)
163 else:
164 to_sdl_rect(rect, &vprect)
165 SDL_RenderSetViewport(self.renderer, &vprect)
166
167 def create_texture(self, size):
168 if SDL_RenderTargetSupported(self.renderer) != SDL_TRUE:
169 raise error()
170
171
172 cdef class Texture:
173 """ Mostly for internal use. Users should only see this for RTT. """
174
175 cdef SDL_Renderer *renderer
176 cdef SDL_Texture *texture
177 cdef public int w, h
178
179 def __cinit__(self):
180 self.texture = NULL
181
182 def __dealloc__(self):
183 if self.texture:
184 SDL_DestroyTexture(self.texture)
185
186 cdef set(self, SDL_Renderer *ren, SDL_Texture *tex):
187 cdef Uint32 format
188 cdef int access, w, h
189
190 self.renderer = ren
191 self.texture = tex
192
193 if SDL_QueryTexture(self.texture, &format, &access, &w, &h) != 0:
194 raise error()
195
196 self.w = w
197 self.h = h
198
199
200 cdef class TextureNode:
201 """ A specified area of a texture. """
202
203 cdef Texture texture
204
205 # The absolute rect within the texture.
206 cdef SDL_Rect source_rect
207
208 # The relative rect within the original tile.
209 cdef SDL_Rect trimmed_rect
210
211 # The dimensions of the original tile.
212 cdef int source_w
213 cdef int source_h
214
215 def __init__(self, tex):
216 if isinstance(tex, Texture):
217 self.texture = tex
218 to_sdl_rect((0,0,tex.w,tex.h), &self.source_rect)
219 to_sdl_rect((0,0,tex.w,tex.h), &self.trimmed_rect)
220 self.source_w = tex.w
221 self.source_h = tex.h
222
223 elif isinstance(tex, TextureNode):
224 self.texture = (<TextureNode>tex).texture
225
226 else:
227 raise ValueError()
228
229 def render(self, dest=None):
230 cdef SDL_Rect dest_rect
231
232 if dest is None:
233 with nogil:
234 SDL_RenderCopy(self.texture.renderer, self.texture.texture, NULL, NULL)
235
236 else:
237 to_sdl_rect(dest, &dest_rect)
238 with nogil:
239 if dest_rect.w == 0 or dest_rect.h == 0:
240 dest_rect.w = self.trimmed_rect.w
241 dest_rect.h = self.trimmed_rect.h
242 SDL_RenderCopy(self.texture.renderer, self.texture.texture, NULL, &dest_rect)
243
244
245 cdef class TextureAtlas:
246 cdef object frames
247
248 def __init__(self, Renderer ren, fi):
249 jdata = json.load(open(fi, "r"))
250 image = jdata["meta"]["image"]
251
252 cdef TextureNode tn = ren.load_texture(image)
253
254 self.frames = {}
255
256 cdef TextureNode itex
257 for itm in jdata["frames"].items():
258 iname, idict = itm
259 itex = TextureNode(tn)
260 f = idict["frame"]
261 to_sdl_rect((f['x'], f['y'], f['w'], f['h']), &itex.source_rect, "frame")
262 f = idict["spriteSourceSize"]
263 to_sdl_rect((f['x'], f['y'], f['w'], f['h']), &itex.trimmed_rect, "spriteSourceSize")
264 if idict["rotated"]:
265 raise error("Rotation not supported yet.")
266 itex.source_w = idict["sourceSize"]["w"]
267 itex.source_h = idict["sourceSize"]["h"]
268
269 self.frames[iname] = itex
270
271 def __getitem__(self, key):
272 return self.frames[key]
273
274 def keys(self):
275 return self.frames.keys()
276
277
278 cdef class Sprite:
279 """ One or more TextureNodes, with possible transforms applied. """
280
281 cdef list nodes
282 cdef SDL_Rect _pos
283 cdef SDL_Rect bounding_box
284
285 cdef double _rotation
286 cdef int _flip
287 cdef SDL_Color _color
288 cdef double _scalex
289 cdef double _scaley
290
291 def __init__(self, nodes):
292 self._color.r = 255
293 self._color.g = 255
294 self._color.b = 255
295 self._color.a = 255
296 self._scalex = 1.0
297 self._scaley = 1.0
298 self._flip = SDL_FLIP_NONE
299
300 memset(&self._pos, 0, sizeof(SDL_Rect))
301 memset(&self.bounding_box, 0, sizeof(SDL_Rect))
302
303 if isinstance(nodes, TextureNode):
304 nodes = [nodes]
305
306 self.nodes = []
307 # TODO: Check that they're all from the same texture.
308 for node in nodes:
309 if not isinstance(node, TextureNode):
310 raise ValueError("Invalid argument: %s" % node)
311 SDL_UnionRect(&self.bounding_box, &(<TextureNode>node).trimmed_rect,
312 &self.bounding_box)
313 self.nodes.append(node)
314
315 cdef void adjust_rect(Sprite self, const SDL_Rect *dest, const SDL_Rect *rin, SDL_Rect *rout) nogil:
316 rout.x = dest.x + <int>(self._scalex * rin.x)
317 rout.y = dest.y + <int>(self._scaley * rin.y)
318 rout.w = <int>(self._scalex * rin.w)
319 rout.h = <int>(self._scaley * rin.h)
320
321 def render(self, dest=None):
322 cdef Texture tex = (<TextureNode>self.nodes[0]).texture
323 cdef SDL_Rect dest_rect
324 cdef SDL_Rect real_dest
325 cdef SDL_Point pivot
326
327 if dest is None:
328 memcpy(&dest_rect, &self._pos, sizeof(SDL_Rect))
329 else:
330 to_sdl_rect(dest, &dest_rect)
331
332 with nogil:
333 SDL_SetTextureColorMod(tex.texture, self._color.r, self._color.g, self._color.b)
334 SDL_SetTextureAlphaMod(tex.texture, self._color.a)
335
336 if DEBUG_DRAW_BBOX:
337 # TODO: Adjust for rotation.
338 self.adjust_rect(&dest_rect, &self.bounding_box, &real_dest)
339
340 SDL_SetRenderDrawColor(tex.renderer, 0x00, 0x00, 0x00, 0x00)
341
342 cdef TextureNode tn
343 for x in self.nodes:
344 tn = <TextureNode> x
345
346 with nogil:
347 pivot.x = <int>(self._scalex * (tn.source_w / 2 - tn.trimmed_rect.x))
348 pivot.y = <int>(self._scaley * (tn.source_h / 2 - tn.trimmed_rect.y))
349
350 self.adjust_rect(&dest_rect, &tn.trimmed_rect, &real_dest)
351
352 SDL_RenderCopyEx(tex.renderer, tex.texture, &tn.source_rect,
353 &real_dest, self._rotation, &pivot,
354 <SDL_RendererFlip>self._flip)
355
356 def collides(self, Sprite other not None):
357 cdef SDL_Rect r1, r2
358
359 self.adjust_rect(&self._pos, &self.bounding_box, &r1)
360 other.adjust_rect(&other._pos, &other.bounding_box, &r2)
361
362 return SDL_HasIntersection(&r1, &r2) == SDL_TRUE
363
364 property pos:
365 def __get__(self):
366 return self._pos.x, self._pos.y
367
368 def __set__(self, val):
369 self._pos.x = val[0]
370 self._pos.y = val[1]
371
372 property color:
373 def __set__(self, val):
374 if not isinstance(val, Color):
375 val = Color(val)
376
377 self._color.r = val.r
378 self._color.g = val.g
379 self._color.b = val.b
380 self._color.a = val.a
381
382 property alpha:
383 def __get__(self):
384 return self._color.a
385
386 def __set__(self, val):
387 self._color.a = val
388
389 property rotation:
390 def __get__(self):
391 return self._rotation
392
393 def __set__(self, val):
394 self._rotation = val
395
396 property scale:
397 def __get__(self):
398 if self._scalex == self._scaley:
399 return self._scalex
400 else:
401 return self._scalex, self._scaley
402
403 def __set__(self, arg):
404 if type(arg) == tuple:
405 x, y = arg
406 else:
407 x = y = arg
408
409 self._scalex = x
410 self._scaley = y
411
412 property hflip:
413 def __get__(self):
414 return self._flip & SDL_FLIP_HORIZONTAL
415
416 def __set__(self, val):
417 if val:
418 self._flip |= SDL_FLIP_HORIZONTAL
419 else:
420 self._flip &= ~SDL_FLIP_HORIZONTAL
421
422 property vflip:
423 def __get__(self):
424 return self._flip & SDL_FLIP_VERTICAL
425
426 def __set__(self, val):
427 if val:
428 self._flip |= SDL_FLIP_VERTICAL
429 else:
430 self._flip &= ~SDL_FLIP_VERTICAL
431
432
433 cdef class Container:
434 """ Multiple sprites, positioned relative to the container. """
435
436 cdef SDL_Rect _rect
437 cdef list sprites
438
439 def __init__(self, rect):
440 """ Parameter may be a position (no clipping) or a rect (clipped). """
441
442 self.sprites = []
443 to_sdl_rect(rect, &self._rect)
444 if len(rect) == 2:
445 self._rect.w = self._rect.h = 0
446
447 def add(self, Sprite sprite not None):
448 self.sprites.append(sprite)
449
450 def render(self, dest=None):
451 # TODO: Something other than this to get the SDL_Renderer.
452 cdef SDL_Renderer *ren = (<TextureNode>(<Sprite>self.sprites[0]).nodes[0]).texture.renderer
453
454 if self._rect.w != 0 and self._rect.h != 0:
455 SDL_RenderSetClipRect(ren, &self._rect)
456
457 for s in self.sprites:
458 s.render((s.pos[0] + self._rect.x, s.pos[1] + self._rect.y))
459
460 # TODO: Save and restore previous clip rect instead?
461 SDL_RenderSetClipRect(ren, NULL)
462
463 property pos:
464 def __get__(self):
465 return self._rect.x, self._rect.y
466
467 def __set__(self, val):
468 self._rect.x = val[0]
469 self._rect.y = val[1]
470
471 property rect:
472 def __get__(self):
473 return Rect(self._rect.x, self._rect.y, self._rect.w, self._rect.h)
474
475 def __set__(self, val):
476 to_sdl_rect(val, &self._rect)
477