neo_doxygen: Remove an outdated comment.
[nit.git] / lib / sdl.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # Copyright 2011-2013 Alexis Laferrière <alexis.laf@xymus.net>
4 #
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
8 #
9 # http://www.apache.org/licenses/LICENSE-2.0
10 #
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
16
17 # SDL display support (used in Linux for windows and inputes only)
18 module sdl is
19 c_compiler_option(exec("sdl-config", "--cflags"))
20 c_linker_option(exec("sdl-config", "--libs"), "-lSDL_image -lSDL_ttf")
21 end
22
23 import mnit_display
24
25 in "C header" `{
26 #include <unistd.h>
27 #include <SDL/SDL.h>
28 #include <SDL/SDL_syswm.h>
29 #include <SDL/SDL_image.h>
30 #include <SDL/SDL_ttf.h>
31 `}
32
33 # Represent a screen surface
34 extern class SDLDisplay `{SDL_Surface *`}
35 super Display
36
37 redef type I: SDLImage
38
39 # Initialize a surface with width and height
40 new (w, h: Int) import enable_mouse_motion_events `{
41 SDL_Init(SDL_INIT_VIDEO);
42
43 if(TTF_Init()==-1) {
44 printf("TTF_Init: %s\n", TTF_GetError());
45 exit(2);
46 }
47
48 SDL_Surface *self = SDL_SetVideoMode(w, h, 24, SDL_HWSURFACE);
49
50 if (!SDLDisplay_enable_mouse_motion_events(self)) {
51 /* ignores mousemotion for performance reasons */
52 SDL_EventState(SDL_MOUSEMOTION, SDL_IGNORE);
53 }
54
55 return self;
56 `}
57
58 # Indicates wether we want the SDL mouse motion event (or only clicks).
59 # Disabled by defaut for performance reason. To activate, redef this method
60 # andd return true
61 fun enable_mouse_motion_events: Bool do return false
62
63 # Destroy the surface
64 fun destroy `{
65 if (SDL_WasInit(SDL_INIT_VIDEO))
66 SDL_Quit();
67
68 if (TTF_WasInit())
69 TTF_Quit();
70 `}
71
72 redef fun finish `{ SDL_Flip(recv); `}
73
74 # Clear the entire window with given RGB color (integer values)
75 fun clear_int(r, g, b: Int) `{
76 SDL_FillRect(recv, NULL, SDL_MapRGB(recv->format,r,g,b));
77 `}
78
79 redef fun width: Int `{ return recv->w; `}
80 redef fun height: Int `{ return recv->h; `}
81
82 # Fill a rectangle with given color
83 fun fill_rect(rect: SDLRectangle, r, g, b: Int) `{
84 SDL_FillRect(recv, rect, SDL_MapRGB(recv->format,r,g,b));
85 `}
86
87 redef fun clear(r, g, b: Float) `{
88 Uint8 ri, gi, bi;
89 ri = (Uint8)r*255;
90 gi = (Uint8)g*255;
91 bi = (Uint8)b*255;
92 SDL_FillRect(recv, NULL, SDL_MapRGB(recv->format,ri,gi,bi));
93 `}
94
95 # SDL events since the last call to this method
96 fun events: Sequence[SDLInputEvent]
97 do
98 var events = new Array[SDLInputEvent]
99 loop
100 var new_event = poll_event
101 if new_event == null then break
102 events.add new_event
103 end
104 return events
105 end
106
107 private fun poll_event: nullable SDLInputEvent import SDLKeyEvent, SDLMouseButtonEvent, SDLMouseMotionEvent, SDLQuitEvent, NativeString.to_s, SDLMouseButtonEvent.as(nullable SDLInputEvent), SDLMouseMotionEvent.as(nullable SDLInputEvent), SDLKeyEvent.as(nullable SDLInputEvent), SDLQuitEvent.as(nullable SDLInputEvent) `{
108 SDL_Event event;
109
110 SDL_PumpEvents();
111
112 if (SDL_PollEvent(&event))
113 {
114 switch (event.type) {
115 case SDL_KEYDOWN:
116 case SDL_KEYUP:
117 #ifdef DEBUG
118 printf("The \"%s\" key was pressed!\n",
119 SDL_GetKeyName(event.key.keysym.sym));
120 #endif
121
122 return SDLKeyEvent_as_nullable_SDLInputEvent(
123 new_SDLKeyEvent(NativeString_to_s(
124 SDL_GetKeyName(event.key.keysym.sym)),
125 event.type==SDL_KEYDOWN));
126
127 case SDL_MOUSEMOTION:
128 #ifdef DEBUG
129 printf("Mouse moved by %d,%d to (%d,%d)\n",
130 event.motion.xrel, event.motion.yrel,
131 event.motion.x, event.motion.y);
132 #endif
133
134 return SDLMouseMotionEvent_as_nullable_SDLInputEvent(
135 new_SDLMouseMotionEvent(event.motion.x, event.motion.y,
136 event.motion.xrel, event.motion.yrel, SDL_GetMouseState(NULL, NULL)&SDL_BUTTON(1)));
137
138 case SDL_MOUSEBUTTONDOWN:
139 case SDL_MOUSEBUTTONUP:
140 #ifdef DEBUG
141 printf("Mouse button \"%d\" pressed at (%d,%d)\n",
142 event.button.button, event.button.x, event.button.y);
143 #endif
144 return SDLMouseButtonEvent_as_nullable_SDLInputEvent(
145 new_SDLMouseButtonEvent(event.button.x, event.button.y,
146 event.button.button, event.type == SDL_MOUSEBUTTONDOWN));
147
148 case SDL_QUIT:
149 #ifdef DEBUG
150 printf("Quit event\n");
151 #endif
152 return SDLQuitEvent_as_nullable_SDLInputEvent(new_SDLQuitEvent());
153 }
154 }
155
156 return null_SDLInputEvent();
157 `}
158
159 # Set the position of the cursor to x,y
160 fun warp_mouse(x,y: Int) `{ SDL_WarpMouse(x, y); `}
161
162 # Show or hide the cursor
163 fun show_cursor(show: Bool) `{ SDL_ShowCursor(show); `}
164 end
165
166 # Basic Drawing figures
167 extern class SDLDrawable `{SDL_Surface*`}
168 super Drawable
169
170 redef type I: SDLImage
171
172 redef fun blit(img, x, y) do native_blit(img, x.to_i, y.to_i)
173 private fun native_blit(img: I, x, y: Int) `{
174 SDL_Rect dst;
175 dst.x = x;
176 dst.y = y;
177 dst.w = 0;
178 dst.h = 0;
179
180 SDL_BlitSurface(img, NULL, recv, &dst);
181 `}
182
183 redef fun blit_centered(img, x, y)
184 do
185 x = x - img.width / 2
186 y = y - img.height / 2
187 blit(img, x, y)
188 end
189 end
190
191 # A drawable Image
192 extern class SDLImage
193 super DrawableImage
194 super SDLDrawable
195
196 # Import image from a file
197 new from_file(path: String) import String.to_cstring `{
198 SDL_Surface *image = IMG_Load(String_to_cstring(path));
199 return image;
200 `}
201
202 # Copy of an existing SDLImage
203 new copy_of(image: SDLImage) `{
204 SDL_Surface *new_image = SDL_CreateRGBSurface(
205 image->flags, image->w, image->h, 24,
206 0, 0, 0, 0);
207
208 SDL_Rect dst;
209 dst.x = 0;
210 dst.y = 0;
211 dst.w = image->w;
212 dst.h = image->h;
213 SDL_BlitSurface(image, NULL, new_image, &dst);
214
215 return new_image;
216 `}
217
218 # Save the image into the specified file
219 fun save_to_file(path: String) import String.to_cstring `{ `}
220
221 # Destroy the image and free the memory
222 redef fun destroy `{ SDL_FreeSurface(recv); `}
223
224 redef fun width: Int `{ return recv->w; `}
225 redef fun height: Int `{ return recv->h; `}
226
227 fun is_ok: Bool do return not address_is_null
228 end
229
230 # A simple rectangle
231 extern class SDLRectangle `{SDL_Rect*`}
232 # Constructor with x,y positions width and height of the rectangle
233 new (x: Int, y: Int, w: Int, h: Int) `{
234 SDL_Rect *rect = malloc(sizeof(SDL_Rect));
235 rect->x = (Sint16)x;
236 rect->y = (Sint16)y;
237 rect->w = (Uint16)w;
238 rect->h = (Uint16)h;
239 return rect;
240 `}
241
242 fun x=(v: Int) `{ recv->x = (Sint16)v; `}
243 fun x: Int `{ return recv->x; `}
244
245 fun y=(v: Int) `{ recv->y = (Sint16)v; `}
246 fun y: Int `{ return recv->y; `}
247
248 fun w=(v: Int) `{ recv->w = (Uint16)v; `}
249 fun w: Int `{ return recv->w; `}
250
251 fun h=(v: Int) `{ recv->h = (Uint16)v; `}
252 fun h: Int `{ return recv->h; `}
253 end
254
255 interface SDLInputEvent
256 super InputEvent
257 end
258
259 # MouseEvent class containing the cursor position
260 class SDLMouseEvent
261 super PointerEvent
262 super SDLInputEvent
263
264 redef var x: Float
265 redef var y: Float
266
267 private init (x, y: Float)
268 do
269 self.x = x
270 self.y = y
271 end
272 end
273
274 # MouseButtonEvent used to get information when a button is pressed/depressed
275 class SDLMouseButtonEvent
276 super SDLMouseEvent
277
278 var button: Int
279
280 redef var pressed: Bool
281 redef fun depressed: Bool do return not pressed
282
283 init (x, y: Float, button: Int, pressed: Bool)
284 do
285 super(x, y)
286
287 self.button = button
288 self.pressed = pressed
289 end
290
291 redef fun to_s
292 do
293 if pressed then
294 return "MouseButtonEvent button {button} down at {x}, {y}"
295 else
296 return "MouseButtonEvent button {button} up at {x}, {y}"
297 end
298 end
299 end
300
301 # MouseMotionEvent to get the cursor position when the mouse is moved
302 class SDLMouseMotionEvent
303 super SDLMouseEvent
304
305 var rel_x: Float
306 var rel_y: Float
307
308 redef var pressed: Bool
309 redef fun depressed: Bool do return not pressed
310
311 init (x, y, rel_x, rel_y: Float, pressed: Bool)
312 do
313 super(x, y)
314
315 self.rel_x = rel_x
316 self.rel_y = rel_y
317 self.pressed = pressed
318 end
319
320 redef fun to_s do return "MouseMotionEvent at {x}, {y}"
321 end
322
323 # SDLKeyEvent for when a key is pressed
324 class SDLKeyEvent
325 super KeyEvent
326 super SDLInputEvent
327
328 var key_name: String
329 var down: Bool
330
331 init (key_name: String, down: Bool)
332 do
333 self.key_name = key_name
334 self.down = down
335 end
336
337 redef fun to_c: nullable Char
338 do
339 if key_name.length == 1 then return key_name.chars.first
340 return null
341 end
342
343 redef fun to_s
344 do
345 if down then
346 return "KeyboardEvent key {key_name} down"
347 else
348 return "KeyboardEvent key {key_name} up"
349 end
350 end
351
352 # Return true if the key is down, false otherwise
353 redef fun is_down do return down
354
355 # Return true if the key is the up arrow
356 redef fun is_arrow_up do return key_name == "up"
357 # Return true if the key is the left arrow
358 redef fun is_arrow_left do return key_name == "left"
359 # Return true if the key is the down arrow
360 redef fun is_arrow_down do return key_name == "down"
361 # Return true if the key is the right arrow
362 redef fun is_arrow_right do return key_name == "right"
363 end
364
365 class SDLQuitEvent
366 super SDLInputEvent
367 super QuitEvent
368 end
369
370 redef class Int
371 fun delay `{ SDL_Delay(recv); `}
372 end
373
374 # Class to load and use TTF_Font
375 extern class SDLFont `{TTF_Font *`}
376 # Load a font with a specified name and size
377 new (name: String, points: Int) import String.to_cstring `{
378 char * cname = String_to_cstring(name);
379
380 TTF_Font *font = TTF_OpenFont(cname, (int)points);
381 if(!font) {
382 printf("TTF_OpenFont: %s\n", TTF_GetError());
383 exit(1);
384 }
385
386 return font;
387 `}
388
389 fun destroy `{ TTF_CloseFont(recv); `}
390
391 # Create a String with the specified color, return an SDLImage
392 fun render(text: String, r, g, b: Int): SDLImage import String.to_cstring `{
393 SDL_Color color;
394 SDL_Surface *text_surface;
395 char *ctext;
396
397 color.r = r;
398 color.g = g;
399 color.b = b;
400
401 ctext = String_to_cstring(text);
402 if(!(text_surface=TTF_RenderText_Blended(recv, ctext, color)))
403 {
404 fprintf(stderr, "SDL TFF error: %s\n", TTF_GetError());
405 exit(1);
406 }
407 else
408 return text_surface;
409 `}
410
411 # TODO reactivate fun below when updating libsdl_ttf to 2.0.10 or above
412 #fun outline: Int # TODO check to make inline/nitside only
413 #fun outline=(v: Int) is extern
414
415 #fun kerning: Bool is extern
416 #fun kerning=(v: Bool) is extern
417
418 # Maximum pixel height of all glyphs of this font.
419 fun height: Int `{
420 return TTF_FontHeight(recv);
421 `}
422
423 fun ascent: Int `{
424 return TTF_FontAscent(recv);
425 `}
426
427 fun descent: Int `{
428 return TTF_FontDescent(recv);
429 `}
430
431 # Get the recommended pixel height of a rendered line of text of the loaded font. This is usually larger than the Font.height.
432 fun line_skip: Int `{
433 return TTF_FontLineSkip(recv);
434 `}
435
436 # Return true is the font used fixed width for each char
437 fun is_fixed_width: Bool `{
438 return TTF_FontFaceIsFixedWidth(recv);
439 `}
440
441 # Return the family name of the font
442 fun family_name: nullable String import String.to_cstring, String.as nullable `{
443 char *fn = TTF_FontFaceFamilyName(recv);
444
445 if (fn == NULL)
446 return null_String();
447 else
448 return String_as_nullable(NativeString_to_s(fn));
449 `}
450
451 # Return the style name of the font
452 fun style_name: nullable String import String.to_cstring, String.as nullable `{
453 char *sn = TTF_FontFaceStyleName(recv);
454
455 if (sn == NULL)
456 return null_String();
457 else
458 return String_as_nullable(NativeString_to_s(sn));
459 `}
460
461 # Return the estimated width of a String if used with the current font
462 fun width_of(text: String): Int import NativeString.to_s `{
463 char *ctext = String_to_cstring(text);
464 int w;
465 if (TTF_SizeText(recv, ctext, &w, NULL))
466 {
467 fprintf(stderr, "SDL TFF error: %s\n", TTF_GetError());
468 exit(1);
469 }
470 else
471 return w;
472 `}
473 end
474
475 # Information on the SDL window
476 # Used in other modules to get window handle
477 extern class SDLSystemWindowManagerInfo `{SDL_SysWMinfo *`}
478
479 new `{
480 SDL_SysWMinfo *val = malloc(sizeof(SDL_SysWMinfo));
481
482 SDL_VERSION(&val->version);
483
484 if(SDL_GetWMInfo(val) <= 0) {
485 printf("Unable to get window handle");
486 return 0;
487 }
488
489 return val;
490 `}
491
492 # Returns the handle of this window on a X11 window system
493 fun x11_window_handle: Pointer `{
494 return (void*)recv->info.x11.window;
495 `}
496 end