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 - 7krs

Pages: [1]
1
Java / Handling Individual Keys
« on: January 19, 2014, 05:59:02 am »
Edit2: figured it out:

 ...KeyEvent keyev = event.asKeyEvent();
                                        switch (keyev.key)
                                        {
                                                case B: ...

Edit: I found it here http://jsfml.org/javadoc/org/jsfml/window/Keyboard.Key.html, but I still wonder how I can use it in a switch.

I was reading the input section, and I've been reading some of the Javadocs on input handling. I am looking for key-specific input handling as implemented in SFML.

The examples (here: https://github.com/pdinklag/JSFML/wiki/Input) print out the name of an individual key; but how can I construct a switch-case structure to check for individual keys coming from KEY_PRESSED events?

2
Window / [SEMI-SOLVED] I Think I Found A Memory Leak
« on: January 16, 2013, 11:01:13 pm »
A minimal example:

    sf::RenderWindow* ptr = new sf::RenderWindow(sf::VideoMode(800, 600, 32), "title");
    ptr->setActive(false);
    while (true)
    {
        std::thread([=]()
                    {
                        ptr->setActive(true);
                        ptr->setActive(false);
                    }
                    ).join();
    }
 

Memory keeps rising (from ~12MB to over 300MB). Requesting confirmations.

3
Window / Problems Threading A Window
« on: December 19, 2012, 09:20:56 pm »
Hi,

the code works, it's just that the return code is weird:

#include <SFML/Graphics.hpp>
sf::RenderWindow wnd;

void sig()
{
    wnd.setActive(true);
    wnd.clear(sf::Color::Green);
    wnd.display();
    wnd.setActive(false);
}

int main()
{
    wnd.create(sf::VideoMode(800, 600, 32), "Title", sf::Style::Default);
    wnd.setActive(false);
    sf::Thread ap(sig);
    ap.launch();
    ap.wait();
    return 0;
}
 

This is a minimal example, and it returns 234, or 0xEA in hex.

#include <SFML/Graphics.hpp>
sf::RenderWindow wnd;

void sig()
{
    wnd.setActive(true);
    wnd.clear(sf::Color::Green);
    wnd.display();
}

int main()
{
    wnd.create(sf::VideoMode(800, 600, 32), "Title", sf::Style::Default);
    wnd.setActive(false);
    sf::Thread ap(sig);
    ap.launch();
    ap.wait();
    return 0;
}
 

Will cause a segmentation fault and return 139 (0x8B).

What am I doing wrong?

4
Hello,

I am wondering if (possibly how) it would be possible to utilize sf::Event / (sf::Lock || sf::Mutex) to make threads process data at specific intervals. Why? Because it seems to me that sf::RenderWindow::waitEvent() and the mutexes are able to hlt (0xF4) the thread. This means ~0 processor usage - less power, less heat, more for other purposes.

I came up with two possible methods, but none work:

1. I am unable to lock a thread from itself.
#include <SFML/System.hpp>
#include <iostream>

sf::Mutex mutex;
bool runThread = true;
signed int dataToProcess = 0;

void processData()
{
    while (runThread)
    {
        mutex.lock();
        mutex.lock(); // Here I would like the thread to lock itself, and thus wait for any external mutex.unlock to complete one iteration.
        dataToProcess *= 10;
        std::cout << dataToProcess << std::endl;
    }
}

int main()
{
    sf::Thread dataProcessor(processData);
    dataProcessor.launch();
    while (runThread)
    {
        int numberAddition = 0;
        std::cin >> numberAddition;
        if (numberAddition == 0)
        {
            runThread = false;
            dataProcess.wait();
            return dataToProcess;
        }
        dataToProcess += numberAddition;
        mutex.unlock(); // The thread is now iterated through once.
    }
    return 0;
}

 

2. I am unable to wait for specific events in another thread.
    - Thread_1 & Thread_2 are running in parallel.
    - I want to make Thread_2 wait for a boolean to change. No polling.
    - If said boolean is changed, iterate over Thread_2's instructions.
    - When iteration is complete, wait for a change in boolean again.

This can however be solved by simply launching the thread from the location where it is needed, but what if I have local variables in the thread function that need to be re-initialized (extra processing power)? What if the locals need to contain data from previous iterations (A class can solve this tho...)? What if the function contains smaller parts that we can loop through? Using shared booleans in this context would be messy IMHO.

I'll rephrase my question; can we control a thread - that runs continuously - whilst utilizing the anti-power hogging delight of mutexes/locks or waitEvents? (Or is there something superior?)

5
Hello there,

I have two threads, one drawing a sprite to the screen at 30 Hz, the other drawing to a RenderTexture at 1 Hz.

The thread drawing to the RenderTexture has a lot of work to do, so whilst it is drawing, the first thread draws an unfinished sprite to the screen. This can be seen as half of what's being drawn, flickers.

I see that the sprite holds a reference to the renderTexture's texture, and I don't want to sf::Mutex::Lock the entire clear()-display() part of the second thread, that'd take too much time. So therefore I want one sprite that is always complete, and gets updated after finishing drawing to the rendertexture, to avoid the flickering.

How do I do this?

6
Graphics / [Problem]: Disappearing Text upon Resize in a Debug Window
« on: August 19, 2012, 12:42:32 pm »
Hello again, I'm having some trouble with a resource class that contains a debug window with a fully functional scrolling system. It also adjusts itself to new screen (RenderWindow) sizes. Here's my problem and how to reproduce it:

[TO REPRODUCE] : Compile/Build/Run in either Debug or Release mode. Resize the window, again, and again... and sometimes, the text will completely disappear from the debug window. The scroll-bar will still be there tho. LaurentGomila-SFML-2b3d9bd (SFML-2.0 rc) used. Code Blocks 10.05 used. Win7 x86 used.

Normal:


Resized, this happens:


Here's the complete code:

//camelCase all the way!

#include <SFML/Graphics.hpp> //Obvious header
#include <string> //std::string
#include <iostream> //std::cin && std::cout
//#include <vector> //std::vector<type>
#include <cstdio> //std::getchar() (Just to pause an element, it's better than using std::cin >> to pause because you don't need to declare a variable)
#include <deque> //std::deque<type> (Stores sf::Text), I guess I should replace it with pointers to sf::Text)
#include <fstream> //std::ofstream
#include <sstream> //std::stringstream << number << string .str().c_str, used for log + number + .txt

/// A CLASS FOR COMPLETE RESOURCE CONTROL PER WINDOW:
/// resources.hpp
class resources
{
    ///Debugger information and methods:
    sf::RectangleShape debugBar; //The little scroll bar on the right side. Size_x = debugWindow.getSize().x/20?, size_y defined by amount of text. Can be modded to be click-drag-able
    std::deque<sf::Text> debugInfo; //push the front, pop the back.
    sf::RenderTexture debugWindow; //The actual window; size_x = window.getSize().x, size_y = window.getSize().y/3
    void debugUpdate(bool scrolled); //Called after ever << input, as well as scrollDebug
    void debugLog(); //Called if the size of debugInfo becomes too large, takes a chunk and puts it in a log file. File is cleaned on startup. File named after the instance-number of this class e.g.: "log2.txt"
    sf::Font debugFont;
    int debugCharacterSize, scroll;
    int debugThisInstance; //Based off the static debugInstance
    float debugTextsPerWindow, debugTextH, debugWindowY;
    static int debugInstance; //Used for the naming of logs
    bool debugVisible;
    ///Debugger information end.
    int windowSizeX, windowSizeY, windowBitsPerPixel;
    std::string windowTitle;
    sf::View view;
public:
    resources(); //Ctor initialized from the same folder the binaries are in. Currently replacement for dirty, quick initialization
    resources(std::string& rootFolder); //Ctor loads settings from a specific folder, that's how I'd like to handle different windows and their respective settings
    ~resources();
    void resize(); //Also modifies the debugging field
    ///To do with debugging:
    void operator << (std::string debugMessage); //Merely adds a message to the deque
    void operator << (const char * debugMessage);
    void debugScroll(bool upOrDown); //The boolean specifies up or down
    inline void debugDraw(); //Function assumes you have already cleared the window, and that you will display it afterwards. Should always be the last draw();
    void debugToggle();
    ///End of debugging specifications
    sf::Event event;
    sf::RenderWindow window;
};

/// resources.cpp
int resources::debugInstance = 0;

//Private member functions:
void resources::debugUpdate(bool scrolled = false)
{
    if (debugInfo.size() >= 100) //If the size is this large, it'll take a chunk of 20 items and store it, then continue
        debugLog();
    if (!scrolled)
        scroll = 0;
    debugWindow.clear(sf::Color(127,127,127,127));
    for (int i = scroll; i < debugInfo.size(); i++)
    {
        debugInfo[i].setPosition(0.f, (debugWindow.getSize().y - (debugInfo[(i)].getGlobalBounds().height+5)) - debugInfo[i].getGlobalBounds().height*(i-scroll));
        debugWindow.draw(debugInfo[(i)]);
    }
    debugBar.setSize(sf::Vector2f(debugBar.getSize().x, debugWindowY * (debugTextsPerWindow/debugInfo.size())));                                          ///sets a level of percentage, fully represents one screen
    debugBar.setPosition(sf::Vector2f(windowSizeX - debugBar.getGlobalBounds().width, (debugWindow.getSize().y - debugBar.getGlobalBounds().height) - (scroll/debugTextsPerWindow)*(debugBar.getGlobalBounds().height) )); ///Okay, so I can change position based on amount of texts and current scroll position.
    debugWindow.draw(debugBar);
    debugWindow.display();
}

void resources::debugLog() //Operation takes 4.2~0.x ms on a bad school-computer, 5200RPM HDD, 320GB
{
    std::stringstream filename;
    filename << "log" << debugThisInstance << ".txt";
    std::ofstream log(filename.str().c_str(), std::ios::app);
    if (log.is_open())
    {
        for (int i = debugInfo.size()-1; i > (debugInfo.size()-80) && i > 0; i--)
        {
            log << (std::string)debugInfo[i].getString() << '\n';
            debugInfo.pop_back();
        }
    }
    else
        std::cout << std::string("Error saving debug info to log file!\n");
        //If we were to do (*this) << "...", and the file could not be made/opened, we'd end up with a massive, recursive spam!
        //Eventually, the call stack would overflow, the program would terminate.
}

//Public member functions:
resources::resources()
{
    debugInstance++;
    debugThisInstance = debugInstance;
    debugCharacterSize = 10;
    scroll = 0;
    windowSizeX = 400;
    windowSizeY = 300;
    windowBitsPerPixel = 32;
    windowTitle = "Debugger Test!";
    ///DEBUGGER INFORMATION:
    debugFont.loadFromFile("visitor1.ttf"); //Quickly load a font file.
    debugWindow.create(windowSizeX, windowSizeY/3);
    debugWindow.clear(sf::Color(127,127,127,127));
    debugWindow.display();
    debugVisible = true;
    debugBar.setSize(sf::Vector2f(windowSizeX/50, 0));
    debugBar.setFillColor(sf::Color(180,180,180,127));
    debugWindowY = (float) debugWindow.getSize().y;
    *this << " Debugger initialization";
    debugTextH = (float) debugInfo[0].getGlobalBounds().height;
    debugTextsPerWindow = debugWindowY / debugTextH;
    debugUpdate();
    ///END DEBUGGER INFORMATION
    window.create(sf::VideoMode(windowSizeX,windowSizeY,windowBitsPerPixel),windowTitle.c_str(), sf::Style::Default);
}

resources::resources(std::string& rootFolder)
{
}

resources::~resources()
{
}

void resources::resize()
{
    windowSizeX = window.getSize().x;
    windowSizeY = window.getSize().y;
    view = sf::View(sf::FloatRect(0,0,windowSizeX, windowSizeY));
    window.setView(view);
    ///We need to re-initialize some parameters of the debug-texture:
    debugWindow.create(windowSizeX,windowSizeY/3);
    debugBar.setSize(sf::Vector2f(windowSizeX/50, 0));
    debugWindowY = (float) debugWindow.getSize().y;
    debugTextH = (float) debugInfo[0].getGlobalBounds().height;
    debugTextsPerWindow = debugWindowY / debugTextH;
    debugUpdate();
    std::stringstream windowSizes; windowSizes << " Window resized: " << windowSizeX << "x" << windowSizeY;
    *this << windowSizes.str();
}

//Operator << for the debug window
void resources::operator << (std::string debugMessage)
{
    debugInfo.push_front(sf::Text(debugMessage, debugFont, debugCharacterSize));
    debugUpdate();
}

void resources::operator << (const char * debugMessage)
{
    *this << std::string(debugMessage);
}

void resources::debugScroll(bool upOrDown = true)
{
    if (upOrDown && scroll < debugInfo.size()-debugTextsPerWindow && debugInfo.size() > debugTextsPerWindow)
        scroll++;
    else if (scroll > 0 && !upOrDown)
        scroll--;
    debugUpdate(true);
}

inline void resources::debugDraw()
{
    if (debugVisible)
        window.draw(sf::Sprite(debugWindow.getTexture()));
}

void resources::debugToggle()
{
    if (debugVisible)
        *this << " Closing debug window";
    else
        *this << " Opening debug window";
    debugVisible = !debugVisible;
}

/// RESOURCE CLASS.

int main()
{
    resources rsc;
    try
    {
        //A simple loop:
        while (true)
        {
            if (rsc.window.waitEvent(rsc.event))
            {
                switch (rsc.event.type)
                {
                    case sf::Event::Resized:
                        rsc.resize();
                        break;
                    case sf::Event::KeyPressed:
                        switch (rsc.event.key.code)
                        {
                            case sf::Keyboard::Escape:
                                return 0;
                            case sf::Keyboard::Insert:
                                rsc.debugToggle();
                                break;
                            case sf::Keyboard::O:
                                rsc.debugScroll();
                                break;
                            case sf::Keyboard::E:
                                rsc.debugScroll(false);
                                break;
                            case sf::Keyboard::Up:
                                rsc << " Up pressed";
                                break;
                            case sf::Keyboard::Down:
                                rsc << " Down pressed";
                                break;
                            case sf::Keyboard::Left:
                                rsc << " Left pressed";
                                break;
                            case sf::Keyboard::Right:
                                rsc << " Right pressed";
                                break;
                            default: rsc << " unknown button pressed"; break;
                        }
                        break;
                    case sf::Event::Closed:
                        return 0;
                    default: break;
                }
            }
            rsc.window.clear(sf::Color::Black);
            rsc.debugDraw();
            rsc.window.display();
        }
    }
    catch (const char * error)
    {
        std::cout << "Error: " << error << std::endl << "Press enter to exit.";
        std::getchar();
    }
    std::getchar();
    return 0;
}
 

http://fontgal.com/font/10468-visitor
is the font used.

Press 'O' to scroll up (Only works if there's more text than the window)
Press 'E' to scroll down.
Press any arrow key to lodge a respective message.
Insert toggles the debug window.
Press any other key to lodge a standard message.

I've spent several hours tracing it, I searched the web, this forum, no hits. So I am forced to ask it here. My apologies if the question is already answered and I didn't find it.

7
Graphics / Problem Moving Shapes on 'Large' Locations
« on: July 11, 2012, 08:14:36 pm »
        MOVX = 1; MOVY = 0;
        RS[0].move(MOVX, MOVY);
 
RS[0].getPosition().x => 1.49598e+008
RS[0].getPosition().y => 0

I found that, at increasing x distances, the value that MOVX requires, to be consistently higher before moving the object at all. I guess it's the same for the y coordinate.

RS is a pointer to sf::RectangleShape, I use sfml 2.0 RC. I check for movement by drawing a background.

Pages: [1]