Welcome, Guest. Please login or register. Did you miss your activation email?

Show Posts

This section allows you to view all posts made by this member. Note that you can only see posts made in areas you currently have access to.

Topics - mateandmetal

Pages: [1]
SFML wiki / XBox 360 Controller support for SFML games
« on: July 09, 2013, 12:08:44 am »
Hi there!
I´m writing a wrapper around XInput, trying to keep the interface as similar to the SFML API as possible.
If you guys like this code and find it usefull, I will add it to the wiki page  8)

The code compiles and works fine with MinGW
It works with my wired X360 controller, I don´t know if it will work with the wireless controller

Of course you will need the DirectX SDK installed  :'(
Note that this will work only with XBox 360 compatible devices, for another kind of gamepads you still need to use the SFML Joystick API

Ok, here is the code:


#include <SFML/System/Vector2.hpp>

namespace xb {

class Joystick {


        // Typedefs
        typedef unsigned int    t_joyNum;
        typedef unsigned short  t_buttonNum;

        // Enums
        enum {
            Count = 4       // Player 0-3

        enum {
            DPAD_UP       = 0x0001,
            DPAD_DOWN = 0x0002,
            DPAD_LEFT    = 0x0004,
            DPAD_RIGHT  = 0x0008,
            START            = 0x0010,
            BACK              = 0x0020,
            LEFT_THUMB   = 0x0040,
            RIGHT_THUMB = 0x0080,
            LB                   = 0x0100,
            RB                  = 0x0200,
            A                   = 0x1000,
            B                  = 0x2000,
            X                  = 0x4000,
            Y                  = 0x8000,

        // Functions (similar to SFML API)
        static bool isConnected (t_joyNum joyNum);
        static unsigned int getButtonCount (t_joyNum joyNum) { return 14; }
        static bool isButtonPressed (t_joyNum joyNum, t_buttonNum buttonNum);

        // X360 specific functions
        static bool isAnyXBox360ControllerConnected();

        static void getTriggers (t_joyNum joyNum, float &left, float &right);
        static void getSticksPosition (t_joyNum joyNum, sf::Vector2f &left, sf::Vector2f &right);

        static void setVibration (t_joyNum, float leftMotor = 0.0f, float rightMotor = 0.0f);

}; // class

} // ns

#endif // X360_CONTROLLER_HPP

#include "X360Controller.hpp"

#ifdef __MINGW32__
    // Useless MS defines (needed to compile under MinGW)
    #define __in
    #define __out
    #define __reserved

// This define makes your program compile faster by excluding things we are not using

#include <windows.h>
#include <XInput.h>

namespace xb {

// Returns true if the joystick is connected (and is an XBox 360 Controller)
bool Joystick::isConnected (t_joyNum joyNum)

    XINPUT_STATE state;
    ZeroMemory (&state, sizeof (XINPUT_STATE));

    auto result = XInputGetState (joyNum, &state);
    return  (result == ERROR_SUCCESS);


// Convenience function: Returns true if there is at least one X360 controller connected
bool Joystick::isAnyXBox360ControllerConnected()

    return  (isConnected(0) || isConnected(1) || isConnected(2) || isConnected(3));


// Returns true if the device supports audio capabilities (headset)
// Uncomment if you need this function
bool Joystick::voiceSupported (t_joyNum joyNum)

    ZeroMemory (&caps, sizeof (XINPUT_CAPABILITIES));

    auto result = XInputGetCapabilities (joyNum, XINPUT_FLAG_GAMEPAD, &caps);

    if (result != ERROR_SUCCESS)
        return false;

    return  (caps.Flags & XINPUT_CAPS_VOICE_SUPPORTED);


// Returns true if the specified button is pressed
// Note that the triggers are NOT recognized as buttons.. You must use
// the getTriggers function for reading the triggers state
bool Joystick::isButtonPressed (t_joyNum joyNum, t_buttonNum buttonNum)

    XINPUT_STATE state;
    ZeroMemory (&state, sizeof (XINPUT_STATE));

    XInputGetState (joyNum, &state);
    return  (state.Gamepad.wButtons & buttonNum);


// This function returns nothing
// It fills the variables left and right with the current state of the triggers (LT and RT)
// The values will always be in the range 0..1
// TODO: TAKE CARE OF THE DEAD ZONE ??????????????????????????????????
void Joystick::getTriggers (t_joyNum joyNum, float &left, float &right)

    XINPUT_STATE state;
    ZeroMemory (&state, sizeof (XINPUT_STATE));

    XInputGetState (joyNum, &state);

    // Normalize and take care of the Dead Zone
    left  = static_cast <float> (state.Gamepad.bLeftTrigger)  / 255;
    right = static_cast <float> (state.Gamepad.bRightTrigger) / 255;


// This function returns nothing
// It fills the vectors left and right with the stick positions,
// wich are in the range -100..100, similar to the SFML function
// getAxisPosition
void Joystick::getSticksPosition (t_joyNum joyNum, sf::Vector2f &left, sf::Vector2f &right)

    XINPUT_STATE state;
    ZeroMemory (&state, sizeof (XINPUT_STATE));

    XInputGetState (joyNum, &state);

    // Check for the "DEAD ZONE"
    // Left Stick
    if ( (state.Gamepad.sThumbLX < XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE &&
              state.Gamepad.sThumbLX > -XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE) &&
             (state.Gamepad.sThumbLY < XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE &&
              state.Gamepad.sThumbLY > -XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE) ) {

        state.Gamepad.sThumbLX = 0;
        state.Gamepad.sThumbLY = 0;


    // Right Stick
    if ( (state.Gamepad.sThumbRX < XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE &&
              state.Gamepad.sThumbRX > -XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE) &&
             (state.Gamepad.sThumbRY < XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE &&
              state.Gamepad.sThumbRY > -XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE) ) {

        state.Gamepad.sThumbRX = 0;
        state.Gamepad.sThumbRY = 0;


    // Convert values to SFML style (-100..100)
    left.x  = static_cast <float> (state.Gamepad.sThumbLX / 327);
    left.y  = static_cast <float> (state.Gamepad.sThumbLY / 327);
    right.x = static_cast <float> (state.Gamepad.sThumbRX / 327);
    right.y = static_cast <float> (state.Gamepad.sThumbRY / 327);


// Set vibration (0.0 to 1.0)
// 0 stops the vibration
void Joystick::setVibration (t_joyNum joyNum, float leftMotor, float rightMotor)

    ZeroMemory (&vib, sizeof (XINPUT_VIBRATION));

    vib.wLeftMotorSpeed  = static_cast <WORD> (leftMotor  * 65535.0f);
    vib.wRightMotorSpeed = static_cast <WORD> (rightMotor * 65535.0f);

    XInputSetState (joyNum, &vib);


} // ns

Test (main.cpp)
#include <iostream>
using std::cout;
using std::endl;

#include <string>
#include <sstream>

#include <SFML/Graphics.hpp>

// CodeBlocks:
// Linker settings, link libraries, add "XInput" without ".lib"
#include "X360Controller.hpp"

template <class T>
std::string numberToString (const T& t) {

    std::stringstream ss;
    ss << t;

    return ss.str();


int main ()

    // If not X360 controllers found, exit
    if (!xb::Joystick::isAnyXBox360ControllerConnected()) {
        cout << "Error: XBox 360 controllers not detected!" << endl;
        return 1;

    // Create the main window
    sf::RenderWindow window (sf::VideoMode (800, 600), "XBox 360 Controller for SFML");

    // Load font
    sf::Font myFont;
    if (!myFont.loadFromFile("steelfish_rg.ttf")) {
        cout << "Error loading font file!" << endl;
        return 1;

    sf::Text buttonText ("Press any button", myFont);
    sf::Text triggerText ("", myFont);
    sf::Text stickText ("", myFont);

    triggerText.setPosition(0.0f, 50.0f);
    stickText.setPosition(0.0f, 150.0f);

    // Start the game loop
    while (window.isOpen()) {

        // Process events
        sf::Event event;

        while (window.pollEvent(event)) {

            // Close window : exit
            if (event.type == sf::Event::Closed)

        // Check for buttons
        if (xb::Joystick::isButtonPressed (0, xb::Joystick::A))
            buttonText.setString ("A");
        if (xb::Joystick::isButtonPressed (0, xb::Joystick::B))
            buttonText.setString ("B");
        if (xb::Joystick::isButtonPressed (0, xb::Joystick::X))
            buttonText.setString ("X");
        if (xb::Joystick::isButtonPressed (0, xb::Joystick::Y))
            buttonText.setString ("Y");
        if (xb::Joystick::isButtonPressed (0, xb::Joystick::LB))
            buttonText.setString ("LB");
        if (xb::Joystick::isButtonPressed (0, xb::Joystick::RB))
            buttonText.setString ("RB");

        // Check for the triggers (LT and RT)
        float lt, rt;
        xb::Joystick::getTriggers(0, lt, rt);
        triggerText.setString("Left trigger: " + numberToString(lt) + "\nRight trigger: " + numberToString(rt));

        // Triggers controls the vibration
        xb::Joystick::setVibration(0, lt, rt);

        // Get sticks positions
        sf::Vector2f ls, rs;
        xb::Joystick::getSticksPosition(0, ls, rs);
        stickText.setString("Left stick: " + numberToString(ls.x) + "," + numberToString(ls.y) +
                            "\nRight stick: " + numberToString(rs.x) + "," + numberToString(rs.y));

        // Clear screen

        // Dibujar

        // Update the window


    // Stop vibration

    return 0;


System / String doesn't display accents under Linux
« on: March 11, 2013, 11:50:55 am »
Hi... I'm trying to display spanish strings with accents under Linux.. with no luck  :(

My GCC version is 4.7.2
Recent SFML 2.0 (compiled by me)
Linux Fedora 18 x64
Codelite IDE

Here is my minimal example:
#include <iostream>
#include <string>
#include <SFML/Graphics.hpp>

using std::cout;
using std::endl;

int main() {

    // Create the main window
    sf::RenderWindow window (sf::VideoMode (800, 600), "String Test");

    // Load font
    sf::Font myFont;
    if (!myFont.loadFromFile("./fuente.ttf")) {
        cout << "error loading font" << endl;
        return -1;

        // Wide string
        const wchar_t *myStringW = L"wide string: áéíóú";
        cout << myStringW << endl;
        sf::Text myTextW (myStringW, myFont, 50);
        myTextW.setPosition(20, 100);

        // ANSI string
        const char *myANSIstring = "ANSI string: áéíóú";
        cout << myANSIstring << endl;
        sf::Text myANSItext (myANSIstring, myFont, 50);
        myANSItext.setPosition(20, 150);

    // Start the game loop
    while (window.isOpen()) {

        // Process events
        sf::Event event;
        while (window.pollEvent(event)) {

            // Close window : exit
            if (event.type == sf::Event::Closed)

        // Clear screen

        // Draw

        // Update the window


    return EXIT_SUCCESS;


The wide string displays correctly using sf::Text. The ANSI string does not display accents.
Should I always use wide strings under Linux?

[attachment deleted by admin]

General / (SOLVED) Can´t load Font files under Linux
« on: February 25, 2013, 10:07:22 pm »
Hi there!
I´m trying to get my game working under Fedora 18 x64
Im using C++ and SFML 2.0 from GitHub (very recent version)

I have created a folder where my font files are stored. Under win7, I load the files as usual:

if (!myFont.loadFromFile ("fonts//asd.ttf"))
// ...

And it works fine.
However, under Linux, this doesn´t work. The game compiles fine, but when I run it, I get this error message:

Failed to load font <filename>  (failed to create the font face)

The font files seems to work fine (I can open them from Dolphin, the KDE file explorer)

I tried changing the file path:
  • ./fonts//name.ttf
  • .//fonts//name.ttf
  • fonts//name.ttf

I can open (read and write) simple text files created by me using std::fstream. It works. Even files inside a folder (like "./config/engine.cfg")

Am I doing something wrong? Do I need to specify the full path to the files under Linux? SFML bug?

EDIT:: Solved

SFML projects / BichingISH! (Final Version 1.0)
« on: January 30, 2013, 11:27:32 pm »
Hello, there!. In this post I submitted my first game. It is quite simple (and bizarre)  ;D


Remember that good old game "Sam & Max: Hit the road" from LucasArts?
I really loved a mini game called Wak-a-rat. That was my inspiration.

The Story

Really? There is a story? ... Well, something like that..

We are two brothers, the owners of a fumigation company. Suddenly, our store is invaded by a new generation of rats, immune to the venom and traps. They come to take revenge for all the rats that we have killed. Having detected the immunity of these rodents, the brothers will have to combat the plague with other tools that are at their fingertips.

Game Mechanics

You will constantly see rats popping from the holes in the table. Rats can have from 1 to 3 lives. They also have a maximum time of "activity", which becomes shorter over the course of the game. If you let them escape with life, they will add some damage to your store (multiplied by the number of lives). The game is finished when you reach the maximum damage.
The game supports two players on the same machine.
You can use mouse, keyboard and/or joysticks.
Network game is not supported. (yet?)

Tools used

Programming: C++, MinGW/gcc compiler version  4.7.2, SFML 2.0 (from GitHub) - static linking under win32
IDE: Code::Blocks versions 10.05, SVN, 12.11 final
3D Graphics and Animation: Blender 2.64, 2.65
2D: GIMP and Photoshop


Engine running

Game Menu

Configuration screen

Single player mode

Two players game mode

Game over screen


Monitor capable of a 1280x720 resolution.
Video card capable of handling 2048x2048 textures.
This game does NOT require the installation of ANY RUNTIME to work.
It is recommended that you download and install the most recent drivers for your video card.


Download Final Version 1.0 from mediafire

As soon as I can install and test SFML2 under Fedora 18  ;)

NOTE: By default the game starts in Spanish, but do not be afraid! You can change language to English in the main menu!
Of course, the game is free.  ;)


Programming, 2D, 3D Graphics and Animations: Pablo Seijo (me)
Sound effects: Several authors (freesound.org)
Music: Kevin MacLeod (incompetech.com)

Big thanks to

Bjarne for creating C++
Laurent for this great library
LucasArts for all that amazing games
and to you, all the SFML community!
 :) ;) ;D

Feature requests / Textured text?
« on: December 18, 2012, 09:36:38 pm »
Can sf::Text use a texture instead of a solid fill color?

  sf::Text myText ("Hello!", myFont, 35);
  myText.setTexture (myTexture);

I know sf::Shape has a setTexture method. Can sf::Text have one?  ::)

SFML wiki / Simple and elegant C++ File Logger
« on: October 14, 2012, 01:13:11 am »
Ok, this is my File Logger class  ;)

Simple C++ File Logger (by mateandmetal)

Yes, it is written in english, no spanish variable names here  ;D

Window / pollEvent -> Segmentation Fault
« on: September 18, 2012, 11:13:42 am »

The fault that my game has becomes randomly. Most of the times it works well, but sometimes it crashes  ???
Here is some code

// main.cpp
// while engine is running...
while (Engine.estaCorriendo()) {

   Engine.manejarEventos(); // handle events
   Engine.actualizar(); // update
   Engine.dibujar(); // draw

} // while

// The engine cpp file..
void Implacable::manejarEventos() {

    // Call handle events function of the last state


// The intro state cpp file
void ige::Intro::manejarEventos () {

    sf::Event evento;

    // engine.getWindow() returns a reference to the sf::RenderWindow
    while (elMotor.obtVentana().pollEvent (evento)) {

        switch (evento.type) {

            // Cerrar ventana: salir
            case sf::Event::Closed:

                elMotor.salir(); // set the engine running to false

            // Any pressed event: Go to the menu state
            case sf::Event::KeyPressed:
            case sf::Event::MouseButtonPressed:
            case sf::Event::JoystickButtonPressed:

                elMotor.cambiarEstado <ige::Menu> ();


        } // sw

    } // while


This is what I get from the debugger

#0 00459524     sf::Window::pollEvent(this=0x41a00010, event=...) (E:\Programacion\SFML2\src\SFML\Window\Window.cpp:183)
#1 0040233D     ige::Intro::manejarEventos(this=0x68d7b0) (E:\Programacion\Ratalypsis\IGE-ESTADOS\Intro.cpp:108)
#2 00401423     Implacable::manejarEventos(this=0x28fbf8) (E:\Programacion\Ratalypsis\IGE-ESTADOS\Implacable.cpp:42)
#3 00402A74     main() (E:\Programacion\Ratalypsis\main.cpp:24)

My debugger points to line 183 of SFML Window code
bool Window::pollEvent(Event& event)
    if (m_impl && m_impl->popEvent(event, false)) ----> SEGFAULT HERE
        return filterEvent(event);
        return false;

This happens sometimes when I press a key or mouse button.

I never had problems with the minimum code of the example tutorials. I´m using MingW32/gcc 4.7.0 (official build), Code::Blocks SVN, Win 7 x64, recent version of SFML2 compiled by me, static linking

I didnt find something similar in the forum/GitHub issues page.

General / The "Bulletproof" Gameloop?
« on: August 27, 2012, 09:56:18 pm »
Hi There!

I´m redesigning my game loop. Yes, I have read these two famous articles:

Fix Your Timestep!
deWiTTERS Game Loop

I wrote a simple main.cpp file to test this methods. This is my deWitters implementation:

    // Timestep (Constant Game Speed independent of Variable FPS)
    sf::Clock miReloj;

    const int TICKS_POR_SEGUNDO = 25;
    const int SALTEO_TICKS = 1000 / TICKS_POR_SEGUNDO;
    const int MAX_SALTEO_FRAMES = 5;

    int loops;
    float interpolacion;

    sf::Int32 proximo_tick = miReloj.getElapsedTime().asMilliseconds();

// This method doesnt look good with VSync On (jerkiness)
window.setVerticalSyncEnabled (false);

     // Start the game loop
     while (window.isOpen()) {

        // Clear screen

        // Update (the events are handled in the actualizar function)
        loops = 0;

        while (miReloj.getElapsedTime().asMilliseconds() > proximo_tick && loops < MAX_SALTEO_FRAMES) {

            actualizar (window); // It doesnt use delta time here

            proximo_tick += SALTEO_TICKS;


        interpolacion = static_cast <float> (miReloj.getElapsedTime().asMilliseconds() + SALTEO_TICKS - proximo_tick) / static_cast <float> (SALTEO_TICKS);

        // Draw
        dibujar (window, interpolacion);

        // Update the window

     return EXIT_SUCCESS;

This are my update/drawing functions using deWitters method:
void actualizar (sf::RenderWindow &rw) {

    // Process events
    sf::Event event;
    while (rw.pollEvent (event)) {
     ... // imagine this code :)
    } // end while

    // Update game objects
    if (!seMueve) return;

    if ((posRenderCirc.x > 700.0f) || (posRenderCirc.x < 20.0f)) {
        velCirculo = -velCirculo;

    posRenderCirc.x += velCirculo; // Just add velocity, no dt here


void dibujar (sf::RenderTarget &rt, const float dt) {

    // Copy original position
    sf::Vector2f posInterpolada (posRenderCirc);

    // If it´s moving, calculate the interpolated position
    if (seMueve) {
        posInterpolada.x += velCirculo * dt; // velCirculo is a float (the object speed)

    circulo.setPosition (posInterpolada); // Draw object at interpolated position
    rt.draw (circulo);

This works fine (with VSync off). But I want to allow the user to select if he/she wants to activate or not the vertical synchronization. Ok, this is my GafferonGames method implementation:

    // Timestep (Fix Your Timestep!)
    sf::Clock miReloj;

    const float dt = 1.0f / 30.0f;

    float tiempoActual = miReloj.getElapsedTime().asSeconds();
    float acumulador = 0.0f;

// VSync friendly
window.setVerticalSyncEnabled (false);

     // Start the game loop
     while (window.isOpen()) {

        // Clear screen

        // Update
        float tiempoNuevo = miReloj.getElapsedTime().asSeconds();
        float tiempoFrame = tiempoNuevo - tiempoActual;

        if (tiempoFrame > 0.25f) {
            tiempoFrame = 0.25f; // Avoid "Spiral of death"

        tiempoActual = tiempoNuevo;
        acumulador += tiempoFrame;

        // Run update in dt sized chunks
        while (acumulador >= dt) {

            actualizar (window, dt);    // using delta time

            acumulador -= dt;


        const float interpolacion = acumulador / dt;

        // Draw with interpolation
        dibujar (window, interpolacion);

        // Update the window

     return EXIT_SUCCESS;

The GafferonGames method update/drawing functions:
void actualizar (sf::RenderWindow &rw, const float tiempoDelta) {

    // Process events
    sf::Event event;
    while (rw.pollEvent (event)) {
     ... // super sexy code here
    } // end while

    // Update game objects
    if (!seMueve) return;

    if ((posRenderCirc.x > 700.0f) || (posRenderCirc.x < 20.0f)) {
        velCirculo = -velCirculo;

    posRenderCirc.x += velCirculo * tiempoDelta;


void dibujar (sf::RenderTarget &rt, const float alphaInterp) {

    sf::Vector2f posInterpolada (posRenderCirc);

    if (seMueve) {
        posInterpolada.x += alphaInterp;

    circulo.setPosition (posInterpolada);
    rt.draw (circulo);


This is working good, with VSync on or off. My game update function is running at fixed 30 FPS and the drawing is running at 60 (VSync on)/3500 fps.

So... is the GafferonGames method THE way to go?
Is there any better/optimized/sexy way to do this?

What method are you guys using?

General / Cooldown time visualization
« on: August 01, 2012, 01:39:58 am »
Hi there!  ;)

In my game, the player can hit the enemy, and then he must wait for a "cooldown" time to hit again. I´m trying to display a graphic (like a clock) to represent the elapsed time.

I have the constant CD time and a sf::Clock to check the elapsed time since de CD begins
const sf::Time cooldownTime = sf::seconds (0.7f);
sf::Clock elapsedCDTime;

I have the graphic shapes
sf::CircleShape circle (30.0f); // The "clock" shape

circle.setFillColor (sf::Color::Transparent);
circle.setOutlineColor (sf::Color::White);
circle.setOutlineThickness (4.0f);

sf::RectangleShape needle (sf::Vector2f (40.0f, 4.0f)); // The clock "needle"
needle.setFillColor (sf::Color::White);
needle.setRotation (90.0f);

Now, I want the "needle" to start rotating from 90 deg. to give a full turn, clockwise. How can I calculate the needle rotation, based on the elapsed time?

Thanks for your time, and sorry for the bad english  :P

General / Get Key Name
« on: July 07, 2012, 02:09:14 am »

I´m writing the configuration system for my game. I need a  function that returns the name of a given key. This is my code:

#include <array>
#include <string>
#include <SFML/Window/Keyboard.hpp>


std::string ige::AdmEntrada::obtNombreTecla (const sf::Keyboard::Key tecla) {

    // Array con los nombres de todas las teclas en castellano
    const static std::array <std::string, sf::Keyboard::Key::KeyCount - 1>  nombreTeclas = {

        "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q",
        "R", "S", "T", "U", "V", "W", "X", "Y", "Z",

        "Cero", "Uno", "Dos", "Tres", "Cuatro", "Cinco", "Seis", "Siete", "Ocho", "Nueve",

        "Ctrl Izq.", "May. Izq.", "Alt Izq.", "Sistema Izq.",
        "Ctrl Der.", "May. Der.", "Alt Der.", "Sistema Der.",

        "Menu", "Abre cor.", "Cierra cor.", "Punto y coma", "Coma", "Punto",
        "Comillas", "Barra", "Barra inv.", "Tilde", "Igual", "Guion",

        "Barra espaciadora", "Enter", "Backspace", "Tab", "Page Up", "Page Down",
        "Fin", "Inicio", "Insertar", "Suprimir",
        "Agregar", "Restar", "Multiplicar", "Dividir",

        "Flecha Izq.", "Flecha Der.", "Flecha Arriba", "Flecha Abajo",
        "0 Numpad", "1 Numpad", "2 Numpad", "3 Numpad", "4 Numpad",
        "5 Numpad", "6 Numpad", "7 Numpad", "8 Numpad", "9 Numpad",

        "F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "F10",
        "F11", "F12", "F13", "F14", "F15", "Pausa"


    return    nombreTeclas [tecla];

I got 1 error and 1 warning:

E:\Programacion\TV Circo\JUEGO\AdmEntrada.cpp|389|warning: missing braces around initializer for 'std::array<std::basic_string<char>, 100u>::value_type [100] {aka std::basic_string<char> [100]}' [-Wmissing-braces]|
E:\Programacion\TV Circo\JUEGO\AdmEntrada.cpp|389|error: too many initializers for 'const std::array<std::basic_string<char>, 100u>'|
||=== Build finished: 1 errors, 1 warnings (0 minutes, 0 seconds) ===|

How can I initialize the std::array correctly? It doesnt support std::initializer_list ctor as far as I know. Adding braces thows only the error (too many initializers)

I´m using MinGW/GCC 4.8.0 (c++0x enabled), SFML 2.0

Feature requests / move window.setKeyRepeatEnabled to sf::Keyboard
« on: April 30, 2012, 12:35:19 am »

I would like to propose something. Moving the setKeyRepeatEnabled from sf::Window to sf::Keyboard, and sf::Window::setJoystickThreshold to sf::Joystick.... Since all belongs to the same module (Window), it may not be so difficult.

I´m writing my input manager class, and i need a renderwindow just to set this two options. Does this two functions really need a renderwindow?  ???

General / Joystick Programming
« on: March 29, 2012, 01:13:32 am »

Started joystick programming today.... I have some doubts..  :-\

1) I have discovered that some buttons of my wired X360 controller are not detected as pressed (the buttons are LT and RT)... sf::Joystick::getButtonCount is returning 10..... Using my generic usb gamepad getButtonCount returns 12 buttons (and they all count as pressed when I press them) ... is this a bug?

2) I´m getting some errors trying to get the joystick moved with the events system. This is my code:

        sf::Event event;
        while (window.pollEvent (event)) {

             // Close window : exit
            if (event.type == sf::Event::Closed)

            // HERE I want to know the joystick number, the axis, and the new position
            if (event.type == sf::Event::JoystickMoved) {

               // error: expected primary expression before ´.´ token
               unsigned int njoy = sf::Event::JoystickMoveEvent.joystickId;

               // trying this way.. error: invalid use of ´struct sf::Event::JoystickMoveEvent´
               unsigned int njoy = event.JoystickMoveEvent.joystickId;

what is the correct way of getting the joy number, the axis moved, and the new position (using the event system) ?

win7 x64, codeblocks, sfml 2 updated

Graphics / (Solved) VertexArray Tilemap not drawing correctly
« on: February 17, 2012, 09:19:40 pm »
Hi There!

Somewhere in the forum, Laurent wrote this example:

Code: [Select]
Here is what a typical tilemap would look like with the new API:

const int size = 32;

// load the texture containing all the tiles
sf::Texture tileset;

// create the map
sf::VertexArray map(sf::Quads, width * height * 4);

for (int x = 0; x < width; ++x)
    for (int y = 0; y < height; ++y)
        int current = (x + y * width) * 4;

        // define the position of the 4 points of the current tile
        map[current + 0].Position = sf::Vector2f((x + 0) * size, (y + 0) * size);
        map[current + 1].Position = sf::Vector2f((x + 0) * size, (y + 1) * size);
        map[current + 2].Position = sf::Vector2f((x + 1) * size, (y + 1) * size);
        map[current + 3].Position = sf::Vector2f((x + 1) * size, (y + 0) * size);

        // define the texture coordinates of the 4 points of the current tile
        int tx = /* X index of the tile in the tileset */;
        int ty = /* Y index of the tile in the tileset */;
        map[current + 0].TexCoords = sf::Vector2i((tx + 0) * size, (ty + 0) * size);
        map[current + 1].TexCoords = sf::Vector2i((tx + 0) * size, (ty + 1) * size);
        map[current + 2].TexCoords = sf::Vector2i((tx + 1) * size, (ty + 1) * size);
        map[current + 3].TexCoords = sf::Vector2i((tx + 1) * size, (ty + 0) * size);

// draw the map
window.Draw(map, &tileset);

I´m trying to use something like this on my own Tilemap class. I´m loading the "desert" example map from the Tiled Map Editor. Here is my drawing function:

Code: [Select]
void Tilemap::DibujarMapa (sf::RenderWindow &ventana) {

    // Creo un array de vertices para dibujar el mapa mas rapido
    sf::VertexArray mapa (sf::Quads, AnchoMapa * AltoMapa * 4);

    int NumCols = TileSheet.GetWidth() / AnchoTile;

    for (int x = 0; x < AnchoMapa; x++) {
        for (int y = 0; y < AltoMapa; y++) {

            int VerticeActual = (x + y * AnchoMapa) * 4;

            // posicion de los cuatro vertices
            mapa[VerticeActual + 0].Position = sf::Vector2f((x + 0) * AnchoTile, (y + 0) * AltoTile);
            mapa[VerticeActual + 1].Position = sf::Vector2f((x + 0) * AnchoTile, (y + 1) * AltoTile);
            mapa[VerticeActual + 2].Position = sf::Vector2f((x + 1) * AnchoTile, (y + 1) * AltoTile);
            mapa[VerticeActual + 3].Position = sf::Vector2f((x + 1) * AnchoTile, (y + 0) * AltoTile);

            int TileActual = ArrayDeTiles [ x + y * AnchoMapa ];

            // posicion de los vertices de la textura
            int tx = (TileActual % NumCols) * AnchoTile;
            int ty = (TileActual / NumCols) * AltoTile;

            mapa[VerticeActual + 0].TexCoords = sf::Vector2f((tx + 0) * AnchoTile, (ty + 0) * AltoTile);
            mapa[VerticeActual + 1].TexCoords = sf::Vector2f((tx + 0) * AnchoTile, (ty + 1) * AltoTile);
            mapa[VerticeActual + 2].TexCoords = sf::Vector2f((tx + 1) * AnchoTile, (ty + 1) * AltoTile);
            mapa[VerticeActual + 3].TexCoords = sf::Vector2f((tx + 1) * AnchoTile, (ty + 0) * AltoTile);

        } // for

    } // otro for

    // Dibujar los vertices con la textura indicada
    ventana.Draw(mapa, &TileSheet);

AnchoMapa = map width in Tiles
AltoMapa = map height in Tiles
AnchoTile = Tile width
AltoTile = tile height
Tilesheet is my sf::Texture (the tileset image)
ArrayDeTiles is a int* array containing the tile data loaded from XML file

I think tx, ty is the texture coordinate for the tile I need to draw.. So I´m using the same calculation for my spritesheet drawing method. I know I´m doing something wrong in this calculation, but I dont get it   :?

here is a screenshot:

What is the correct method for calculating tx, ty?

Using SFML 2.0 21/1, Code::Blocks
(sorry for my bad eng)

Pages: [1]