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

Pages: [1] 2
SFML wiki / Extract Triangles
« on: November 24, 2023, 06:11:46 pm »
The different (solid) primitive types are useful for individual objects but, sometimes, we need independent triangles, especially if we want to have multiple (separate) shapes in a single vertex array.

Presenting to you, Extract Triangles!

Extract Triangles does exactly that; it extracts individual triangles from the other primitive types.

Basically, it's this:
sf::VertexArray triangleFan(sf::PrimitiveType::TriangleFan);
// set up vertices for triangle fan
sf::VertexArray independentTriangles{ extractTriangles::vertexArrayFrom(triangleFan) };

Simple, huh? 8)

It can also work with just vertices (i.e. std::vector<sf::Vertex>) as well as convert between the two types and - for some reason - can also create vertex buffers from either of those!

For more information as well as the code, visit the SFML wiki and/or the GitHub repository listed below.

Wiki page:

GitHub repository (it's a part of SfmlSnippets):

There is also an example showing it in action included in the repository and also on the wiki page.

Feel free to ask any questions or make any comments.

SFML wiki / Simple Sprite Batcher
« on: November 22, 2023, 12:04:04 am »
Multiple sprites drawn mean multiple draw calls. These draw calls can have a detrimental affect to performance so, if possible, they should be reduced. One way to do this is to draw many of those sprites batched together!

This is a "simple" sprite batcher. That is, it's very easy and simple to use and will bring you performance improvements. However, a more dedicated batcher may be able to bring more improvements albeit at the cost of simplicity.

The batcher is a very small class. You simply create it and pass it the texture. Then, you can pass it the sprites to be batched and draw it as often as required.

Basically, it'll look like this:
sf::Texture texture;
// .. set up the texture for the sprites

std::vector<sf::Sprite> sprites;
// .. set up the sprites

SimpleSpriteBatcher batcher;
batcher.texture = &texture;

while (window.isOpen())
    // .. event handling

    // .. updates where you would modify vector sprites however you want



You can also batch using a vector of pointers to sprites too so you can easily still use this if your sprites are not in a vector or if you need to order them first! There is an example of how to do this on the wiki page.

Here's a video that shows it in action:
Note that the YouTube compression struggles with the video but it still shows the difference between with and without the batcher.

Wiki page:

GitHub repository (it's a part of SfmlSnippets):

Example used to create the clips in the above video is included in the repository and also on the wiki page.

Feel free to ask any questions or make any comments.

SFML development / DPI-Scaling on Windows
« on: November 20, 2023, 10:46:46 pm »
I'm not sure if this is a help request, a feature request or actually providing help to others so it might be better in a different category...

Before we start, you should know that this is not intended to be just complaints. I'd really like to help improve this. First, though, we need to understand what the problems actually are and why they are problems.

One of the main things that has irritated me with using SFML is trying to get it to place nicely with already created windows. Note that my points here will about about Microsoft Windows only.

Creating a window with SFML is simple; it's great!
However, it lacks some features that require the ability to control the window yourself (adding a 'proper' window menu, for example). This can be ignored a lot of the time for most games but falls flat for other (more serious/professional) application types, forcing windows to be created without SFML.

So, instead we can create a window manually (this isn't really much of an issue but it's nicer when SFML does the work for you!). Then, we can pass the window's handle to an SFML window and it can take over control for that window. This is also a nice feature.

However, this starts to create some issues when faced with DPI-scaling. Newer operating systems use scaling and often start with a scale of not 100%. For example, I'm using Windows 11 and the default scale was 150%.

The issue is that things should be scaled by this value so that the user experiences scaled things automatically. If they don't, they are ignoring the user's request; this is an accessibility issue. When you create a window manually, it "cares" about the user's decision and it is scaled. The app itself doesn't see the scale and the accessibility is applied automatically.

If you pass control of a window already created (and scaled properly) to SFML, SFML removes scaling so that its size matches its expected number of pixels. This is understandable for when you are working with exact pixels. This means that window "shrinks" (assuming a larger scale in my examples) to fit SFML's preferences.
Firstly, I'd say that this in itself is a bit of an issue since the reason we create a window without SFML is access to window features that SFML doesn't provide and this removes the ability to do this.

If you've programmed directly in Windows already, you'll understand that you can create (child) windows within other windows (almost everything is a window!). So, creating a window as a child of the actual window as a destination for SFML graphics to be displayed is actually a good idea. This allows you to place SFML graphics in specified rectangles around the window.

Unfortunately, when you pass this child window to SFML, SFML will remove scaling - for everything! That includes its parent window! This means that you cannot create and control one window and give a child window to SFML to play with as it affects the parent window as well.

In addition to this, SFML's removal of the scaling actually affects all windows by the instance so all windows will be "unscaled" by SFML even if not at all related to the window used SFML. This is quite a disturbing situation.

It's worth noting too, that when the window is "unscaled" by SFML, the title bar is also "unscaled" and I've seen the window title disappearing as it's too small!

I should mention that I've looked around for previous info about this and a few things popped up that might interest someone experiencing issues with scaling:
All are many years old.

There doesn't seem to be anything in SFML 3's list of task related to this, unfortunately.

I will also provide a "simple" sample code you can use to see it in action:
#include <SFML/Graphics.hpp>
#include <Windows.h>

LRESULT CALLBACK MainWindowProcedure(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);
LRESULT CALLBACK ChildWindowProcedure(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);
LRESULT CALLBACK Main2WindowProcedure(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);

int main()
        HINSTANCE hInstance{ GetModuleHandle(NULL) };

        // main window
        const wchar_t mainClassName[] = L"Main Window Class";
        WNDCLASS wc = { };
        wc.lpfnWndProc = MainWindowProcedure;
        wc.hInstance = hInstance;
        wc.lpszClassName = mainClassName;

        HWND hWnd = CreateWindowEx(
                0, mainClassName, L"SFML in child window test", WS_OVERLAPPEDWINDOW,
                CW_USEDEFAULT, CW_USEDEFAULT, // position
                1000, 1000, // size
                NULL, NULL, hInstance, NULL
        if (!hWnd)
                return EXIT_FAILURE;

        ShowWindow(hWnd, SW_SHOWNORMAL);

        // reference window (window 2: identical to - but independent from - main window)
        const wchar_t main2ClassName[] = L"Main 2 Window Class";
        WNDCLASS wc2 = { };
        wc2.lpfnWndProc = Main2WindowProcedure;
        wc2.hInstance = hInstance;
        wc2.lpszClassName = main2ClassName;

        HWND hWnd2 = CreateWindowEx(
                0, main2ClassName, L"SFML in child window test 2 (for reference size)", WS_OVERLAPPEDWINDOW,
                CW_USEDEFAULT, CW_USEDEFAULT, // position
                1000, 1000, // size
                NULL, NULL, hInstance, NULL
        if (!hWnd2)
                return EXIT_FAILURE;

        ShowWindow(hWnd2, SW_SHOWNORMAL);

        // child window (child of main window, not window 2)
        const wchar_t childClassName[] = L"Child Window Class";
        WNDCLASS wcChild = { };
        wcChild.lpfnWndProc = ChildWindowProcedure;
        wcChild.hInstance = hInstance;
        wcChild.lpszClassName = childClassName;

        HWND hWndChild = CreateWindowEx(
                0, childClassName, L"Child Window", WS_CHILD | WS_BORDER,
                250, 250, // position
                500, 500, // size
                hWnd, // parent
                NULL, hInstance, NULL
        if (!hWndChild)
                return EXIT_FAILURE;

        ShowWindow(hWndChild, SW_SHOWNORMAL);

        sf::RenderWindow sfmlWindow(hWndChild); // sfml window is created from the child window (of main window)

        sfmlWindow.clear(sf::Color(255u, 160u, 64u)); // fill the SFML window (child) with a solid colour

        MSG msg{};
        while (GetMessage(&msg, NULL, 0, 0) > 0)

LRESULT CALLBACK MainWindowProcedure(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
        switch (msg)
        case WM_DESTROY:
                return 0;
                return DefWindowProc(hWnd, msg, wParam, lParam);

LRESULT CALLBACK ChildWindowProcedure(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
        switch (msg)
        case WM_DESTROY:
                return 0;
                return DefWindowProc(hWnd, msg, wParam, lParam);

LRESULT CALLBACK Main2WindowProcedure(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
        switch (msg)
        case WM_DESTROY:
                return 0;
                return DefWindowProc(hWnd, msg, wParam, lParam);
This is complete and should compile (you will need to link SFML Graphics as normal). Note that if you are using "Multi-byte Character Set" instead of "Unicode Character Set", you'll need to either change it to the Unicode one or replace the "wide" characters with standard ones.

this code also outputs an error (that I must admit that I don't understand):
An internal OpenGL call failed in RenderWindow.cpp(125).
   glGetIntegerv(GLEXT_GL_FRAMEBUFFER_BINDING, reinterpret_cast<GLint*>(&m_defaultFrameBuffer))
Error description:
   The specified operation is not allowed in the current state.

And finally...
As mentioned at the beginning of this post, I will also be giving some help/advice.

As a work-around, you can fix this issue yourself but it's on a "per exe file" basis.

To do this, you can modify the properties of the executable manually (right-click file and click on Properties).
Then, go to Compatibility tab, click on Change high DPI settings, activate Override high DPI scaling behaviour and choose Application or System from the drop-down menu.
Application lets SFML scale the window but the title bar still works.
System disallows SFML from changing the scaling of the windows.

In conclusion, having to "override" settings per file is a bit of a dirty "hack" and it would be cleaner if we could at minimum let SFML know we don't want it to be in charge of scaling.

SFML projects / Cheese Map
« on: August 27, 2023, 08:33:31 pm »

Cheese Map is a drawable layered tile map for SFML, designed to simplify drawing most 2D maps.

It's also fully header-only so no library compilation needed; simply just include it.

You can create multiple grid map (standard grid tile maps) and place them anywhere in space and Cheese Map will draw them all together. You basically give it the view you want it to fill and it draws the map that is needed to fill that view, automatically culling everything out-of-range.

You can also create layers of individual "free" tiles that are tiles that can be placed anywhere in space with no restraint to a grid. These are likely most useful for separate, individual objects that don't conform to a grid and/or need to be layered in front or behind without having to create another entire grid map in front or behind.

Whether it be a grid or layer, each one can have a z-order depth and is automatically sorted when drawn so you easily decide on the order things are drawn. Each one can also have a depth that offsets it in the 3rd dimension; it projects away from the screen towards the back and follows the rule of the perspective (the vanishing point of the map can be customised). Each one can also have its own colour, be activated (drawn) and de-activated (ignored), and given any offset/position that moves the entire grid/layer.

Each tile's texture can also be transformed: flipped/mirrored/rotated using flipx, flipy, and rotate (90 degrees).

Cheese Map makes it easy to move around by using the view: you can move, scale and rotate the view however you like and Cheese Map adapts. You can think of it as if the entire map is static and your view is your camera that you can aim at it however you want to. Cheese Map doesn't draw stuff it doesn't need outside of the camera/view.

To get started quickly, you can have a look at the Simple Example that - with very little code - produces this animation:

(click to show/hide)

There are also a couple of videos available that were created of tests during development:
Early Test Demo:

Initial Tests:

EDIT: fixed Simple Example link

SFML development / Multi-line Text Alignment
« on: August 13, 2023, 06:02:22 pm »
Would you be interested in having a simple multi-line alignment for sf::Text?

You may or may not have already seen this:
where I created something similar to sf::Text that also included a multitude of alignment features.

However, I'm proposing a simple "Left/Center/Right/Justify" choice that would simply affect the entire text globally.
Maybe not even justify if you'd prefer not to have that since it would depend on the type of justification you'd want: "word" justification or "character" justification where "word" only stretches spaces and "character" also separates characters. Of course, you could have both as an option.

The left/center/right option is pretty simple to implement so I'd guess you'd prefer that, if this is a consideration at all, of course.

Let me know and I'll start up a draft...

SFML projects / Qalm
« on: May 22, 2023, 04:54:59 pm »
(click to show/hide)

Hi! :)

A while ago, I began creating a music editor based around an SFML music player that I created. That is, a functioning music 'performer' that plays back music in a similar way to how MIDI does, using only SFML audio module.

That is QALM!

While I all-but-abandoned the main editor due to frustration over the struggle between SFML and user-created windows, a few mini-apps were also created during that time.
It would be fair to say that those mini-apps were not finished but they are, in general, in a working state.

So... I shall provide you with Windows executables (64-bit only) of a couple so you can tinker and hopefully have some fun.

Qalm Instrument Editor

Here, you can create instruments designed to be used with the Qalm Player engine (the core of all of Qalm).
However, you can 'play' the current instrument in real-time using the computer keyboard!
An instrument can be just a single sample (so it allows you to play a sample back at musical pitches) or multiple samples mapped to different pitches (allowing multi-sampled pianos or drumkits!).
Some instruments are provided for testing.

You can also use the created instruments in the other provided app... the Tracker!

Qalm Tracker

This is a functioning Tracker - a music creation tool with a specific style using vertical time. It does function but many expected functions have not been added yet.

You can create your own music using your instruments with tracker-style effects.

Major restrictions include:
- it always loads the same song file (test.qts). You can copy it and move them around but it always loads the same filename each time. If you delete it, it will create one (allowing you to start from scratch).
- it always loads the same instruments. This is a pretty tight restriction, unfortunately. It loads them from a file, though, so replacing those instruments with different instruments but give them the same filename will allow you to use other instruments.

Note that it come pre-loaded with something I composed to test some things.

Here's a video clip of the pre-loaded song playing back:

I hope you have some fun with these.
I had fun making them and I hope to get back to working with them some more in the future.
Remember that everything is using SFML sound buffers and sounds! 8)
When I am more happy with the Player engine, I plan to release the code so you can use it to playback your creations in your programs!

Another Qalm mini-app I have created in a converter that allows you to convert MIDI songs to Qalm songs and then the Qalm Player can play them back with the instruments you created!

The following downloads are for Windows 64-bit only and are Zip folders.
The are each completely self-contained and can be run from wherever and should not need any admin control.


They also contain some basic documentation to help use them.

SFML development / RenderStates const ref in draw()
« on: May 10, 2023, 06:05:30 pm »
Regarding SFML master (v3-WIP).

I noticed that render states in the virtual draw method of a drawable is now a const reference (instead of by value) and I wonder what the reason behind this decision was as I can't find any information or discussion yet other than an old post saying that it wouldn't happen ;)

Old post: https://en.sfml-dev.org/forums/index.php?topic=17102.0

To be clear, I'm not at all saying it's a wrong decision (just because I had to modify lots of code ;D) but wondered why the decision was changed. Maybe now it's better to be (possibly) more optimised over simplicity?

SFML wiki / Get Character At Coord
« on: November 07, 2022, 09:41:14 pm »
SFML's texts are considered a single drawable object so interaction with them is usually based on their boundary boxes.

Get Character At Coord informs you of which character in a text object is at the given co-ordinate.

Get Character At Coord is a free-function that can be added to any code.

It's very easy to use and is pretty small.

Wiki page:

GitHub repository (it's a part of SfmlSnippets):

Example used to create the above screenshots is included in the repository and also on the wiki page.

Feel free to ask any questions or make any comments.

SFML wiki / Rectangular Boundary Collision
« on: July 11, 2017, 08:08:46 pm »
Rectangular Boundary Collision

SFML's sprites and shapes can provide you with their axis-aligned boundary boxes (getGlobalBounds) and you can easily use these rectangles to test if they intersect. Unfortunately, this only allows axis-aligned collision detection.

Rectangular Boundary Collision allows testing collision based on their original rectangular boundary box (getLocalBounds). It tests to see if an object's rectangular boundary collides with another object's rectangular boundary. This method, however, allows transformations to be taken into account - most notably, rotation.

Rectangular Boundary Collision is a single, templated free-function contained within the "collision" namespace:
const bool spritesAreColliding = collision::areColliding(sprite1, sprite2);

You only need the header, which is approximately 100 lines of code...

The collision is performed in three stages:
  • Level 0 - AABB (axis-aligned boundaries boxes):
    tests the axis-aligned boundaries boxes (equivalent to getGlobalBounds) of the objects to see if they intersect.
  • Level 1 - Corner inside opposite object:
    tests to see if any of either object's corner is inside the other object.
  • Level 2 - SAT (Separating Axis Theorem):
    tests using a simplified version (for rectangles) of SAT to catch other cases.
If, at any time, the result is certain, the following stages are not calculated. This allows easier detections to be done without resorting to the more involved calculations.

The collision level represents after which stage to leave the function, regardless of if a result is certain.

(red = collision, green = no collision)

Wiki page:

GitHub repository (it's a part of SfmlSnippets):

Example used to create the above screenshots is included in the repository and also on the wiki page.

If a text is drawn to a window in a separate thread, an OpenGL error is reported when the font is destroyed.
The OpenGL error is caused by SFML's Texture.cpp (when sf::Font is destroyed).

Note that, even if the thread is completely finished and destroyed, the font destruction still causes the error.

The error:

The line to which is referred in Texture.cpp:
glCheck(glDeleteTextures(1, &texture));

A complete and minimal example that causes the error:
#include <SFML/Graphics.hpp>
#include <thread>

void threadFunction(const sf::Text& text)
    sf::RenderWindow window(sf::VideoMode(800, 600), "");

int main()
        sf::Font font;
        sf::Text text("Text", font);
        //text.getLocalBounds(); // uncomment to stop error
            std::thread thread(threadFunction, text);
        } // thread completed and destroyed here
    } // font destroyed here - OpenGL error
    return EXIT_SUCCESS;

Any ideas as to why this happens? Any solutions?
Should the font be so seemingly linked to the window?

The strange thing - as you may have noticed in the code - is that if you call getLocalBounds() on the text object (and subsequently ensureGeometryUpdate), this error no longer occurs. This, could be considered a workaround (or "solution") but I'm still curious as to what causes the problem in the first place.

Note that this exact example was written and tested (and screenshot) using v2.4.1. However, the problems also occur with v2.4.0 and v2.4.2.

SFML projects / Splashentation
« on: June 10, 2017, 12:43:31 am »
This is Splashentation!

Splashentation is a slideshow presentation that is shown in its own window and runs in its own thread.

Useful for opening animations, loading screens and other situations, Splashentation shows multiple SFML drawables per slide and transitions between each slide while allowing real-time control of those drawables.

Controls to progress are also available, allowing specific keys and/or mouse buttons to jump to the next slide, skip entire presentation or quit the presentation. Controls can be stored both globally and per slide.

As you can see in the code for the following example, it is also possible to progress to next slide, skip or quit the presentation programmatically from the main thread.

Each slide can have its own controls (as mentioned in the previous paragraph), duration (including infinity), transition duration, background colour and drawables. The order that drawables are drawn can also be controlled (using a "z depth" value).

Splashentation is released under the zlib licence (the same as SFML) and is available from here:

Simple Example - Loading Splash
Simple Loading Splash example source code

SFML website / Documentation Version Linking
« on: January 16, 2016, 12:57:34 am »
At the moment, the website has the documentation for each different version that are contained within their own folder. As new versions become released, any linking to the documentation automatically becomes linked to what is then and old version.

Would it be possible to include a way to link to specific articles in the documentation while being able to specify a more generic version?

For example,
links to the (currently) latest version of the documentation for sf::RenderWindow.
As soon as 2.3.3 - or, indeed, 2.4 - is released, this link would be out of date.

Since patch updates - and also minor updates - shouldn't be changing the documentation in a "breaking" way, it would be convenient to be able to link to these articles using a form of "wild-card" version.
A suggestion would be able to specify wild card at minor or patch level like so:
which would link to sf::RenderWindow in the latest version of 2.3
which would link to sf::RenderWindow in the latest version of SFML 2.

The website already has the feature to some extent for its documentation's "main page" where, if you leave off the version, it'll choose the latest. Adding the suggested ability above to the articles directly would help increase permanence of documentation links.

I found that, as I was linking to the documentation a lot, I have started to drop using the patch level version from the links thus:
as replacing all links every time a new patch version is released just to make sure you're on the latest version feels like overkill and these are "pretty much" the same. Pretty much, as much as linking to the wrong patch version would be, anyway.

Suggestion summary:
2.3.2 article
latest 2.3 article (currently 2.3.2)
latest 2 article (currently 2.3.2)

SFML projects / Selba Ward
« on: December 13, 2015, 11:21:08 pm »
Welcome to Selba Ward!
.................."check in to check it out"

Selba Ward is a collection of generic, reusable and flexible drawable objects for SFML.

Currently available objects:
Selba Ward can be built as a single library and then the objects can be included as required (as I use it myself) or the individual objects can be copied into your project and built along with it. The drawable objects are completely independant of each other. However, they will also require the very light Common.hpp header, along with any dependants (e.g. Bitmap Text requires Bitmap Font) or extras (e.g. Palette Enums can be useful with Console Screen)

Future Objects
Small and quick objects can usually be added quite quickly when they are added to the to-do list.
Suggestions will be taken into serious consideration, even larger objects.

All objects in Selba Ward require SFML version 2+. The latest version is recommended, although some objects may not have been tested with that version.

As always, feedback (on the currently available objects, their interface, or the underlying code) is highly appreciated.
Suggestions for objects will also be taking into consideration.
Please report any problems with specific versions of SFML to me. This thread can be a good place for that.

Demo Animation
Best viewed in 1080 quality and 60 FPS.

(click to show/hide)

Thank you for reading and I hope you find Selba Ward useful!
Selba Ward is available here on GitHub and is under the zLib licence (same as SFML).

EDIT: Added link for Polygon (from the list) and removed the listing of the old Console Screen as its no longer available.

SFML website / Fake or fine?
« on: August 28, 2015, 10:28:28 pm »
Anybody know what this is
and why it's describing itself as "the official SFML documentation"?

SFML projects / My Practice Beginner Games
« on: August 23, 2015, 08:47:23 pm »
I realised that I have avoided programming those beginner games that everyone does to learn stuff and for general practice so I decided that I'm going to finally attempt them.

This project (of multiple games) doubles as practice for using GitHub too so it will all be available on GitHub. The repositories are the actual files that I am working on so you so you will be able to see my workings, mistakes, and re-factoring (I tend to do that a lot, I think). This also means that you can feel free to raise issues on the repository and the like.

Of course, SFML will be the base library for all games. Who actually wants to write console-only games?  :P
I also will be using a few small libraries of my own - all of which are completely available on GitHub.

I'll be up for discussions on any part of the project - including suggestions - but not really questions about C++ that should be, at the very least, first googled.

Current Work In Progress:

Early video of MTD (v0.0.2):

Video of Puzza (v1.0.0):

(click to show/hide)

The Code
Click here to visit the GitHub repository.

These "games" are work(s) in progress and no guarantees to their working success are given.
I may or may not decide to work on more than one game at a time.
None of this can be considered tutoring. It is not intended to teach. I am learning and this is what I am doing. That is all.

Pages: [1] 2