Find bogue on Github

How to embed BOGUE in an existing graphics loop?

If you have a game using the SDL2 renderer library, then it’s easy to use BOGUE to add GUI elements to your game, without stopping your graphics loop.

The basic idea is to call the Bogue.one_step function whenever you need to display the GUI. But some caution has to be taken to make sure that:

Here is how to do it (see the full code here: examples/embed. If you dowloaded BOGUE sources from github, you can run this example with dune exec examples/embed/embed.exe.)

We will use an alias for Sdl.Event:

module E = Sdl.Event;;
  1. Do the SDL initialization (window, renderer) yourself.

  2. Define your GUI board with Bogue.create (and define the before_display function if you use it)

  3. Attach the SDL window to the board with Bogue.make_sdl_windows.

  4. Define a GUI state variable:

     let show_gui = ref false in
  5. Start your loop. In principle you will clear the screen at each frame with Sdl.set_render_draw_color and Sdl.render_clear.

  6. Make sure your event handling is done only when !show_gui = false. For instance, here we will stop when Escape is pressed, and show the GUI when TAB is pressed:

    if not !show_gui && Sdl.poll_event (Some e)
    then begin
      match E.(enum (get e typ)) with
      | `Key_up when E.(get e keyboard_keycode) = Sdl.K.tab ->
        show_gui := not !show_gui
      | `Key_down when E.(get e keyboard_keycode) = Sdl.K.escape ->
        raise Sys.Break
      | _ -> ()
      end;
  7. Call the one_step function when needed:

     if !show_gui
     then begin
       Bogue.refresh_custom_windows board;
       try if not (Bogue.one_step ~before_display true (start_fps, fps) board)
       (* one_step returns true if fps was executed *)
         then fps () with
       | Bogue.Exit -> show_gui := false
       | e -> raise e
     end
     else fps ();

    The Bogue.refresh_custom_windows board tells BOGUE that the custom window should be completely rendered even though BOGUE may think there was no change since last frame. The true argument of the one_step function indicates that an animation is running and BOGUE should not interrupt it by waiting for an event. Then, the one_step function will return true if BOGUE itself has an animation running, which means that you should not interrupt the graphics loop.

    Here we close the GUI when the user presses Esc, which raises the Bogue.Exit exception.

    The fps function was created earlier by let start_fps, fps = Time.adaptive_fps 60 but you may use your own FPS handling.

  8. Flip the graphics buffer with Sdl.render_present and loop (jump to Step 5.)

Find bogue on Github