SFML community forums

General => SFML projects => Topic started by: Nexus on April 18, 2011, 11:34:24 pm

Title: Thor C++ Library – An SFML extension
Post by: Nexus on April 18, 2011, 11:34:24 pm
(http://www.bromeon.ch/thor/thor.png)


[Edit] This post is outdated. Please use now this thread (http://www.sfml-dev.org/forum/viewtopic.php?p=48455#48455) to discuss about the next version of Thor.

Good evening,

I would like to present a project I have been working on the last time. Thor is an open-source C++ library which provides extensions of SFML. There have been a lot of feature requests in the forum that were either too high level or out of scope for integration into SFML. Nevertheless, some of them are very useful in game and multimedia programming. That is why I have implemented some of them, hoping that SFML users can benefit from the functionality.

Thor is completely free to use, like SFML it is licensed under zlib/libpng.


Features

The Thor C++ library comes with the following small modules:

Vectors
- 2D Vector algebra functions: Dot product, compute length and angles, ...
- 3D Vector algebra functions: Dot and cross product, compute length and angles, ...
- PolarVector: 2D vector class that stores polar coordinates

Geometry
- Zone class hierarchy for geometric figures
- Base classes for positionable, rotatable and scalable objects

Particles
- ParticleSystem class based on sf::Image, stores and manages particles (lifetime, transformations, color, ...)
- Customizable Emitter and Affector classes

Events
- SfmlEventSystem class to handle SFML events via callbacks
- EventSystem template for user-defined events

Resources
- ResourceManager class template that allows safe and easy loading, storage and access to resources
- ResourcePtr provides shared access to resources
- Predefined helper classes for SFML resources like sf::Image

Multimedia
- ConcaveShape class: As an extension to sf::Shape, it works with concave shapes
- Arrow class to visualize vectors
- Color blending and simple construction of color gradients
- String conversion functions for a few SFML classes like sf::Vector

Time
- StopWatch class: Wrapper around sf::Clock for pausable clocks
- Timer class: Countdown mechanism
- TriggeringTimer class: Countdown invoking callbacks at expiration

Tools
- SingleDispatcher: Dynamic dispatch to unary functions
- DoubleDispatcher: Dynamic dispatch to binary functions (multimethods)
- Other utility like foreach macros

SmartPtr
- ScopedPtr: Local RAII smart pointer
- MovedPtr: Movable smart pointer implementation
- CopiedPtr: Smart pointer with deep copy semantics

Math
- Generalization of trigonometry functions
- Random number generator based on TR1
- Delaunay triangulation


Download

You can download version 1.0 directly on my homepage (http://www.bromeon.ch/thor). You will also find tutorials and the API documentation there. I use CMake to build the source code, but I also supply precompiled binaries for some configurations. Note that the library bases on the newest Git revisions of SFML 2.

In the next days, I am going to setup an SVN repository so that you are able to follow the development of the Thor C++ library.


Outlook

I try to improve the library continuously, so I appreciate feedback, be it bug reports, feature requests or general discussions. Let me know what you like to be part of Thor, and I can think about it. One of the tasks I am planning to implement in near future is a design that allows easy animations with sf::Sprite, another example is a Z buffer.
Title: Thor C++ Library – An SFML extension
Post by: Laurent on April 18, 2011, 11:55:28 pm
Very nice project :)

I'll try to have a deeper look at it when I have some free time.

It will also make my life much easier:
Quote
User X: "can you please implement xxx in SFML?"
Laurent: "no way... but ask Nexus"

:mrgreen:
Title: Thor C++ Library – An SFML extension
Post by: Groogy on April 19, 2011, 10:46:54 am
Just wondering if you want to extend it with some threading utilities? I'll soon be done with my "extension" or whatever you'd like to call it. It includes synchronization between threads, Thread pool and Job management.

Currently only got Job management left.
Title: Thor C++ Library – An SFML extension
Post by: WitchD0ctor on April 19, 2011, 11:52:00 am
Not gonna lie, that triangulation demo was really sexy.
would be really useful for creating box2d shapes!
Title: Thor C++ Library – An SFML extension
Post by: phoekz on April 19, 2011, 12:18:51 pm
Definitely going to use this in my project, going to love particles and more functional clock/timer. It looks fairly simple even for a beginner. Going to toy around with this tonight :D.
Title: Thor C++ Library – An SFML extension
Post by: Hubert on April 19, 2011, 02:38:17 pm
Thanks you so much.  :o
A lot a usefull things that I'm going to use in my projet.
Title: Thor C++ Library – An SFML extension
Post by: Nexus on April 19, 2011, 05:15:50 pm
I'm glad that you find it useful :)

Quote from: "Groogy"
Just wondering if you want to extend it with some threading utilities?
Probably not, at least not in near future. I'd rather like to concentrate on improving and extending the current modules for now. Also, my own experience with multithreading is pretty limited ;)
Title: Thor C++ Library – An SFML extension
Post by: xazax on April 19, 2011, 08:09:58 pm
I always missed some extended vector functionality :). I hope there is a chance to backport some of those features to core SFML.
Title: Thor C++ Library – An SFML extension
Post by: Nexus on April 19, 2011, 11:38:34 pm
Quote from: "xazax"
I always missed some extended vector functionality :)
A lot of people did (including myself), so Thor seemed to be a good opportunity ;)

By the way, the SVN repository is now online, the URL of the trunk is http://www.bromeon.ch/svn/thor/trunk.
Title: Thor C++ Library – An SFML extension
Post by: xazax on April 25, 2011, 05:59:01 pm
Nice one, thank you very much.
Title: Thor C++ Library – An SFML extension
Post by: Nexus on April 25, 2011, 08:12:09 pm
In the meantime, I have implemented parts of a new event action system. This allows the dynamic mapping from arbitrary identifiers to specific keys, and combinations of them using OR and AND operators.

You can get the code via SVN. Here is an example:
Code: [Select]
#include <Thor/Events.hpp>
#include <SFML/Window.hpp>
#include <iostream>
#include <string>

int main()
{
// Create window, set initial settings
sf::Window window(sf::VideoMode(400, 300), "Thor Action Demo");
window.SetFramerateLimit(20);
window.EnableKeyRepeat(false);

// Create action map: std::string -> thor::Action
using thor::Action;
thor::ActionMap<std::string> map(window.GetInput());

// Run: Press one of the Shift keys and R (realtime input)
map["run"] = (Action(sf::Key::LShift) || Action(sf::Key::RShift)) && Action(sf::Key::R);

// Shoot: Press S or release D (single events)
map["shoot"] = Action(sf::Key::S, Action::PressOnce) || Action(sf::Key::D, Action::ReleaseOnce);

// Leave: Press escape
map["quit"] = Action(sf::Key::Escape, Action::PressOnce);

while (window.IsOpened())
{
// Clear temporarily pushed events
map.ClearEvents();

// Handle events
sf::Event event;
while (window.PollEvent(event))
map.PushEvent(event);

// Check which actions are active
if (map.IsActive("run"))
std::cout << ".";
if (map.IsActive("shoot"))
std::cout << "*";
if (map.IsActive("quit"))
return 0;

window.Display();
}
}

I am going to add support for mouse and joystick. What do you think about it?
Title: Thor C++ Library – An SFML extension
Post by: Laurent on April 25, 2011, 08:48:02 pm
Looks really good so far, I like the API.

But you shouldn't use const char* keys. Comparisons should fail, since it compares the pointer values and not the actual strings. std::string would be better. If it works, I guess it's only because your compiler uses the same memory area for two occurences of the same string literal.
Title: Thor C++ Library – An SFML extension
Post by: Nexus on April 25, 2011, 08:59:14 pm
I first had std::string, and somehow I thought char pointers would be enough (don't ask why :)). But you are of course right, thanks for the hint. I have fixed it.

By the way, mouse and joystick are now supported. I'd like to hear some feed-back concerning the API and functionality!
Title: Thor C++ Library – An SFML extension
Post by: WitchD0ctor on April 26, 2011, 04:10:39 am
wow, those Action Events are looking real tasty.
Title: Thor C++ Library – An SFML extension
Post by: Astrof on April 30, 2011, 02:08:17 am
whoa NICE! I haven't looked into SFML for like...two years or so? But wanted to get back into a mini project or two.  Love the inclusion of the particle engine.  

So I haven't looked into it too much yet (don't shoot me) but was wondering, so the triangulation ties in with box2D? My previous project died because something was wrong with wither box2D or the Spark particle engine that I was using.
Title: Thor C++ Library – An SFML extension
Post by: Grimshaw on April 30, 2011, 02:44:36 pm
Hey, would you mind explaining me this line?

Code: [Select]
map["run"] = (Action(sf::Key::LShift) || Action(sf::Key::RShift)) && Action(sf::Key::R);

map["run"] is getting a boolean value right? from the logic operators? If so, how does it actually record the keys?
Title: Thor C++ Library – An SFML extension
Post by: Nexus on April 30, 2011, 04:11:36 pm
Thanks :)

Quote from: "Astrof"
So I haven't looked into it too much yet (don't shoot me) but was wondering, so the triangulation ties in with box2D?
It's not designed specifically for Box2D, nor does it use the library internally. The Triangulate() functions provide a generic interface to triangulate a set of points, so they can probably be used in combination with Box2D (I don't know the library well however).

Quote from: "DevilWithin"
Code: [Select]
map["run"] = (Action(sf::Key::LShift) || Action(sf::Key::RShift)) && Action(sf::Key::R);map["run"] is getting a boolean value right? from the logic operators? If so, how does it actually record the keys?
No, the operators || and && are overloaded for the thor::Action class, they don't return bool.

thor::Action is able to record key, mouse and joystick events, for both polling (sf::Event) and realtime input (sf::Input). The second parameter of the Action constructor specifies whether the corresponding key/mouse button/joystick button must be pressed or released once to trigger the action, or if it's enough to be held down (like in sf::Input).

The class template thor::ActionMap is continuously fed with SFML events through the method PushEvent(). At the time you check for an event to be active using IsActive(), the pushed events are searched for an occurrence of this event type. Same for realtime input. So, at the beginning of each frame, you need to reset the stored events using ClearEvents().
Title: Thor C++ Library – An SFML extension
Post by: Grimshaw on April 30, 2011, 04:41:43 pm
Very Cool Idea! Great library! Thanks ;)
Title: Thor C++ Library – An SFML extension
Post by: Astrof on April 30, 2011, 08:52:57 pm
I was just wondering about Box2D as I use that mainly for collision detection.  


Also I think I'm just stupid but how do I build this with cmake for VS2010? Specifically setting the SFMLdir

Edit:
Actually I think it's mainly me not knowing how to use cmake.  I'll not flood this thread and instead ask in the help forum.

Edit2: Okay So I get this error:
Code: [Select]

CMake Warning at CMakeLists.txt:67 (find_package):
  Could not find module FindSFML.cmake or a configuration file for package
  SFML.

  Adjust CMAKE_MODULE_PATH to find FindSFML.cmake or set SFML_DIR to the
  directory containing a CMake configuration file for SFML.  The file will
  have one of the following names:

    SFMLConfig.cmake
    sfml-config.cmake



CMake Error at CMakeLists.txt:73 (message):
  SFML directory not found.  Set SFMLDIR to SFML's top-level path (containing
  "include" and "lib" directories).


Configuring incomplete, errors occurred!


I'm trying to compile with VS2010 and SFML2.
Title: Thor C++ Library – An SFML extension
Post by: Nexus on May 01, 2011, 03:38:43 am
The FindSFML.cmake file must be in the CMake modules directory. It should be automatically there when you build SFML with CMake and install it (compile the INSTALL project). Make sure that you use a recent Git revision, there is also one provided on the website.

After installing SFML, try to follow this tutorial (http://www.bromeon.ch/thor/v1.0/tutorial-installation.html) ;)
Title: Thor C++ Library – An SFML extension
Post by: Astrof on May 01, 2011, 03:53:11 am
Hmm okay I'm obviously doing something wrong.  

I'm using SFML 2 from the svn.  I used cmake to build svn and was able to make a sample window and such, so that worked.  I went back and tried to compile the INSTALL project and it failed: gave me this error:

Code: [Select]

Error 1 error MSB3073: The command ""C:\Program Files (x86)\CMake 2.8\bin\cmake.exe" -DBUILD_TYPE=Release -P cmake_install.cmake
if errorlevel 1 goto :VCEnd
:VCEnd" exited with code 1. C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\Microsoft.CppCommon.targets 113


EDIT:
Okay the problem? Admin privileges.  Stupid windows...

Now it's saying something like the SFML libraries can't be found?
Code: [Select]

Could NOT find SFML (missing:  SFML_AUDIO_LIBRARY SFML_GRAPHICS_LIBRARY SFML_WINDOW_LIBRARY SFML_SYSTEM_LIBRARY) (Required is at least version "2")
CMake Error at CMakeLists.txt:73 (message):
  SFML directory not found.  Set SFMLDIR to SFML's top-level path (containing
  "include" and "lib" directories).


Configuring incomplete, errors occurred!
Title: Thor C++ Library – An SFML extension
Post by: Nexus on May 01, 2011, 09:00:40 am
Yes, specify the path in the variable SFMLDIR. This is explained in my tutorial...
Title: Thor C++ Library – An SFML extension
Post by: Astrof on May 01, 2011, 06:13:12 pm
I did that that's why I'm saying it doesn't make sense.  I point it to the dir which has the include folder and the lib folder.  
"C:\SFML\branches\sfml2"
which has bindings, build, cmake, doc, examples, extlibs, include, lib, src, CMakeLists.txt, and license.txt

The tutorial is also maybe a bit off? In the tutorial it has listed a "SFML-Include-Dir" which isn't on the current one (it instead has SFML-Dir and SFMLDIR)

The errors I'm getting are about each libs debug library (but I have compiled for debug libs too).


EDIT:
Okay nevermind I fixed it.  Didn't realize that SFML installed to program files.  I so stupid...

Now I'm getting something about how PollEvent is not a member of RenderWindow?
Title: Thor C++ Library – An SFML extension
Post by: Nexus on May 01, 2011, 07:13:31 pm
The SVN version of SFML is outdated. You must use a recent Git revision in order to compile Thor. I provide a compatible one on my website in the download area (http://www.bromeon.ch/thor/download.html).
Title: Thor C++ Library – An SFML extension
Post by: Astrof on May 01, 2011, 07:21:48 pm
Ah okay hmm is there a way to use github with svn? Or another way that provides a simple click and update vs redownloading every time?

EDIT: okay maybe I should do some research before posting...

Downloading git now.
Title: Thor C++ Library – An SFML extension
Post by: Astrof on May 01, 2011, 08:46:24 pm
Everything works now yay!

I have a small question, does the particle system only work with images or can it work with, say, Shapes or things?
Title: Thor C++ Library – An SFML extension
Post by: Nexus on May 01, 2011, 09:20:29 pm
Good that you managed to install it :)

No, the particle system only works with sf::Image instances. But you can use sf::RenderImage (http://www.sfml-dev.org/documentation/2.0/classsf_1_1RenderImage.htm) to draw any sf::Drawable to an image.
Title: Thor C++ Library – An SFML extension
Post by: Astrof on May 02, 2011, 12:31:17 am
Nice to know.  Ahhhh I'm so excited that I don't know where to begin on my project.  I had this idea shelved for like years.  But hopefully It'll almost work again.
Title: Thor C++ Library – An SFML extension
Post by: Nexus on May 02, 2011, 12:43:38 am
That's interesting, a few weeks ago I dug out an old project of mine. For 1.5 years, I have hardly worked on it. Well, it needed some hours to port everything to SFML 2, but it was worth it... Argh, so many bugs because of the sf::Rect modification :D
Title: Thor C++ Library – An SFML extension
Post by: Nexus on May 22, 2011, 06:58:56 pm
Meanwhile, I have added a way to connect thor::ActionMap with the existing thor::EventSystem. This makes it possible to connect actions to callbacks without bloating ActionMap's interface. Additionally, the classes of the Time module have been adapted so that they work with sf::Uint32 milliseconds (like sf::Clock).

As announced in my initial post, I have also implemented two classes that should help with building animations. The class Animation stores the frames of an animation and can be used by multiple Animator objects, which compute the progress and apply it to sprites. In principle they work like this:
Code: [Select]
// Create animation that has three frames with different subrects
// and durations 0.2, 0.4 and 0.1 seconds
thor::Animation explosion;
explosion.AddFrame(0.2f, sf::IntRect(...));
explosion.AddFrame(0.4f, sf::IntRect(...));
explosion.AddFrame(0.1f, sf::IntRect(...));

// Create object that animates a sf::Sprite, register animation
thor::Animator animator;
animator.AddAnimation("explode", explosion);

// Play a registered animation like this
animator.PlayAnimation("explode");

// In main loop: Update animator and apply changes to a sf::Sprite
animator.Update(passedTime);
animator.Apply(mySprite);

This is only a first draft, tell me what you think about it.
Title: Thor C++ Library – An SFML extension
Post by: CJ_COIMBRA on June 09, 2011, 09:58:45 pm
Time and Event topics will be very helpfull for me!
Is it complete already?
Title: Thor C++ Library – An SFML extension
Post by: Nexus on June 09, 2011, 10:05:42 pm
Quote from: "CJ_COIMBRA"
Is it complete already?
What do you mean? There is already a usable version 1.0, but of course there is always room for improvement ;)

In fact, I suggest to use the SVN version to make use of newer features, improvements and adaptions to SFML. For example, the sf::Clock interface has recently changed, and the Time module of Thor's SVN version has been adapted to it (unlike Thor 1.0, which was released before).
Title: Thor C++ Library – An SFML extension
Post by: Beliar on June 11, 2011, 10:45:11 am
The Library seems nice, it would be much better though if it wouldn't clutter me with warnings just by including headers from it:

Code: [Select]
Thor\Detail\MovedPtr.inl||In function 'bool thor::operator==(const thor::MovedPtr<T, OwnershipPolicy>&, const thor::MovedPtr<T, OwnershipPolicy>&)':|
Thor\Detail\MovedPtr.inl|153|warning: no return statement in function returning non-void|
Thor\Detail\MovedPtr.inl||In function 'bool thor::operator!=(const thor::MovedPtr<T, OwnershipPolicy>&, const thor::MovedPtr<T, OwnershipPolicy>&)':|
Thor\Detail\MovedPtr.inl|161|warning: no return statement in function returning non-void|
Thor\Detail\MovedPtr.inl||In function 'bool thor::operator==(const thor::MovedPtr<T, OwnershipPolicy>&, const thor::MovedPtr<T, OwnershipPolicy>&)':|
Thor\Detail\MovedPtr.inl|153|warning: no return statement in function returning non-void|
Thor\Detail\MovedPtr.inl||In function 'bool thor::operator!=(const thor::MovedPtr<T, OwnershipPolicy>&, const thor::MovedPtr<T, OwnershipPolicy>&)':|
Thor\Detail\MovedPtr.inl|161|warning: no return statement in function returning non-void|
Thor\Detail\SmartPtrImpl.inl||In function 'void thor::detail::ForwardDestroy(T*) [with T = thor::detail::ResourceSlot<sf::Image, thor::Resources::ImageKey>, U = thor::detail::ResourceSlot<sf::Image, thor::Resources::ImageKey>, OwnershipPolicy = thor::NoCopy]':|
Thor\Detail\SmartPtrImpl.inl:148|53|instantiated from 'thor::detail::SmartPtrImpl<T, OwnershipPolicy>::SmartPtrImpl(U*) [with U = thor::detail::ResourceSlot<sf::Image, thor::Resources::ImageKey>, T = thor::detail::ResourceSlot<sf::Image, thor::Resources::ImageKey>, OwnershipPolicy = thor::NoCopy]'|
Thor\Detail\MovedPtr.inl:38|16|instantiated from 'thor::MovedPtr<T, OwnershipPolicy>::MovedPtr(U*) [with U = thor::detail::ResourceSlot<sf::Image, thor::Resources::ImageKey>, T = thor::detail::ResourceSlot<sf::Image, thor::Resources::ImageKey>, OwnershipPolicy = thor::NoCopy]'|
Thor\Detail\ResourceManager.inl:132|102|instantiated from 'thor::ResourcePtr<Resource> thor::ResourceManager<Resource, ResourceKey>::AddResource(thor::ResourceManager<Resource, ResourceKey>::SlotIterator, const ResourceKey&) [with Resource = sf::Image, ResourceKey = thor::Resources::ImageKey, thor::ResourceManager<Resource, ResourceKey>::SlotIterator = std::_Rb_tree_iterator<std::pair<const thor::Resources::ImageKey, thor::detail::ResourceSlot<sf::Image, thor::Resources::ImageKey>*> >]'|
Thor\Detail\ResourceManager.inl:76|30|instantiated from 'thor::ResourcePtr<Resource> thor::ResourceManager<Resource, ResourceKey>::Acquire(const ResourceKey&) [with Resource = sf::Image, ResourceKey = thor::Resources::ImageKey]'|
Thor\Detail\SmartPtrImpl.inl|63|warning: statement has no effect|


(MinGW-GCC 4.5.0)

And, no, I won't disable warnings on my side.

[edit]
Well, I found a solution on my side, but I still dislike warnings in third-party header files.
[/edit]
Title: Thor C++ Library – An SFML extension
Post by: lakunar on June 11, 2011, 10:55:33 am
Realy nice Nexus!

Thanks

But:
1. I think you use a outdatet version of mingw (current gcc version: 4.5) (but who cares :) )

2. I tried the particles demo and it works, but in debug mode i get an error but the app ist not crashing.

Debug: http://projectbase.pr.funpic.de/ThorDebug.JPG (even the sf:text looks  :?)
Release: http://projectbase.pr.funpic.de/ThorRelease.JPG

3. And in both cases the app crashes on exit.
[Edit]
 3. Fixed, Ah it was the ati bug with dynamic linking but the debug error still exists
[/Edit]

@Beliar:
Get them too
But they are fixed easily
Title: Thor C++ Library – An SFML extension
Post by: Nexus on June 11, 2011, 12:24:56 pm
Quote from: "Beliar"
The Library seems nice, it would be much better though if it wouldn't clutter me with warnings just by including headers from it:
Thanks. I try to get rid of the warnings as soon as possible. What flags did you use to compile? I couldn't reproduce all warnings with -Wall -Wextra...

The smart pointer comparison operators are actually forbidden, they just exist to avoid the implicit conversion to safe-bool. g++ behaves strangely in this way, I was already forced to modify the static assertion to depend on the template parameter in order to compile. According to how I know the C++ standard, templates aren't defined before their instantiation, so this should actually work.

Quote from: "lakunar"
I think you use a outdatet version of mingw (current gcc version: 4.5)
Yes, it was up-to-date some time ago ;)
Now I have updated it.

Quote from: "lakunar"
2. I tried the particles demo and it works, but in debug mode i get an error but the app ist not crashing.
Which Thor version and which compiler/OS do you use? Does the SFML OpenGL example work?

I just compiled the debug version of Thor (SVN revision 19) with MingW (g++ 4.5.2) and static linkage, and everything worked fine.
Title: Thor C++ Library – An SFML extension
Post by: lakunar on June 11, 2011, 01:04:50 pm
Thor: 1.0 (not precompiled ) (maybe i should try the svn version)
Sfml: The recommended one (from the Thor website)
OS: Win7 64bit
Compiler: MingW (g++ 4.5.1)  ( :oops: )

SFML Opengl example works with dynamic linkage.
with static linkage i get a bunch of undefined reference errors, and i don't know what to link to

if i try to static linkage thor i get some undefined references to:
Code: [Select]
glOrtho@48
glTranslatef@12
glTranslatef@12
glRotatef@16
glTranslatef@12
glColor4ub@16
glTranslatef@12
glRotatef@16

And right now I link to libopengl32 and libglu32
Title: Thor C++ Library – An SFML extension
Post by: Nexus on June 11, 2011, 01:52:38 pm
Quote from: "lakunar"
Thor: 1.0 (not precompiled ) (maybe i should try the svn version)
Yes, I recommend it. Static linkage with MinGW works in the meantime. In version 1.0 I accidentally had a wrong library dependency order (and didn't know that g++ would care about it, because MSVC++ does not).

About your particle problem: I have tried many configurations with 1.0 and the SVN version, even linking Thor (Debug) with SFML (Release), and in none of them I could reproduce this problem. Try to upgrade to a recent SFML and Thor revision and make sure there are no relicts of older versions that might lead to conflicts. If the error persists, could you try to find out where that OpenGL underflow happens?
Title: Thor C++ Library – An SFML extension
Post by: lakunar on June 11, 2011, 03:42:04 pm
Shame on me  :(

Made the same mistake: wrong library dependency order

Now everything works
Thanks
Title: Thor C++ Library – An SFML extension
Post by: Beliar on June 11, 2011, 05:01:31 pm
Quote from: "Nexus"

[...]
What flags did you use to compile? I couldn't reproduce all warnings with -Wall -Wextra...


I am using CodeBlocks, but as far as I can see, its only -Wall.
Title: Thor C++ Library – An SFML extension
Post by: Nexus on June 11, 2011, 06:23:20 pm
I hope I have removed them all :)
Title: Thor C++ Library – An SFML extension
Post by: Laurent on June 11, 2011, 06:49:29 pm
Quote
g++ behaves strangely in this way, I was already forced to modify the static assertion to depend on the template parameter in order to compile. According to how I know the C++ standard, templates aren't defined before their instantiation, so this should actually work.

gcc performs a syntax check on templates when they are first seen (not instanciated), I think this is called "two-phase template lookup", and it is specified by the standard.
So it already checks/resolves all the code that doesn't depend on a template parameter, before instanciating the template.
Title: Thor C++ Library – An SFML extension
Post by: Nexus on June 11, 2011, 07:24:36 pm
That is true, but g++ performs checks far beyond syntax, which I thought was not allowed. But you are probably right, I have just read Boost.StaticAssert (http://www.boost.org/doc/libs/1_46_1/doc/html/boost_staticassert.html#boost_staticassert.templates) and they mention exactly this problem. Interestingly, the Boost people also use exactly the same workaround ;)

During the development of Thor, I have come across other situations where some compilers apply template rules in a wrong way. MSVC++ isn't strict about missing typename, and g++ probably misinterprets this code (its output is twice "T").
Code: [Select]
#include <iostream>

template <typename T>
void Func(T)
{
    std::cout << "T" << std::endl;
}

template <typename T>
void Use()
{
    Func(T());
}

void Func(int)
{
    std::cout << "int" << std::endl;
}

int main()
{
    Use<double>();
    Use<int>();
}
Title: Thor C++ Library – An SFML extension
Post by: Laurent on June 11, 2011, 07:45:10 pm
Which version of gcc do you use?
Title: Thor C++ Library – An SFML extension
Post by: Nexus on June 11, 2011, 07:47:38 pm
g++ 4.5.2 (with MinGW)
Title: Thor C++ Library – An SFML extension
Post by: lakunar on June 11, 2011, 07:51:02 pm
Quote from: "Nexus"
... its output is twice "T".


Because:
Code: [Select]
#include <iostream>

template <typename T>
void Func(T)
{
    std::cout << "T" << std::endl;
}

template <typename T>
void Use()
{
    Func(T()); //AT THIS POINT
}

void Func(int) //it doesnt know this func so it calls the top one, by putting this before use it should work
{
    std::cout << "int" << std::endl;
}

int main()
{
    Use<double>();
    Use<int>();
}



OT: Is there a reason why i can't use one Zone (thor::Emitter::ZonePtr) for two emitters(thor::TargetEmitter::Ptr)? -> Assertion fail !IsNUll() : include/Thor/Detail/SmartPtrImpl.inl, line 210
Title: Thor C++ Library – An SFML extension
Post by: Nexus on June 11, 2011, 08:13:49 pm
Quote from: "lakunar"
Because [...]
I know, but I think overload resolution should occur at the point of template instantiation (i.e. inside main()). Especially because the function argument T() is clearly dependent on a template parameter.

Quote from: "lakunar"
OT: Is there a reason why i can't use one Zone (thor::Emitter::ZonePtr) for two emitters? -> Assertion fail !IsNUll
ZonePtr is not a shared_ptr, but a MovedPtr (it transfers its ownership). My thought was that every emitter keeps an own zone, independent of other emitters. I found shared ownership less intuitive, what do you think?

You can still copy the zone by using thor::CopiedPtr (I know it could be easier :D):
Code: [Select]
thor::CopiedPtr<thor::Zone, thor::VirtualClone> a(...), b = a;
emitter1->SetEmissionZone( thor::Move(a) );
emitter2->SetEmissionZone( thor::Move(b) );


By the way, that is not offtopic, the template discussion is ;)
Title: Thor C++ Library – An SFML extension
Post by: lakunar on June 11, 2011, 09:06:47 pm
Quote from: "Nexus"
My thought was that every emitter keeps an own zone, independent of other emitters. I thought shared ownership might have been less intuitive, what do you think?


I'm not really into shared & moved pointer.

I am also of the opinion that it is more intuitive if every emitter has it's one zone. But if you want to make an really cool effect than more emitters are in the same zone and it might be easier if you have a shared zone.

Maybe you should implement both, this means that we can choose on constuction and/or later if the emitter has it's own zone or if it uses a shared one.
Then it's possible to constuct for example 3 emitters with a shared zone, and later I can say now i want emitter 1 to have its own zone to modify this and not modifying the other ones.

Edit:
Well, I saw that it isn't that often that two emitters use exact the same Zone, so for me it's fine how it is now.
Title: Thor C++ Library – An SFML extension
Post by: Nexus on June 12, 2011, 01:53:47 pm
Quote from: "lakunar"
Maybe you should implement both, this means that we can choose on constuction and/or later if the emitter has it's own zone or if it uses a shared one.
This would be the shared approach. You can still have multiple independent shared pointers.

There is however the problem how to create one std::tr1::shared_ptr of another one, while copying ownership. Currently, this can be done using Zone::Clone(), but I don't know whether this method will last forever. In contrast, thor::CopiedPtr is smart enough to perform deep copies without Clone().

Quote from: "Nexus"
You can still copy the zone by using thor::CopiedPtr (I know it could be easier :D ):
Okay, it is now easier :)
Code: [Select]
thor::Emitter::ZonePtr a(new thor::Rectangle(...));
thor::Emitter::ZonePtr b = thor::Copy(a);
// a and b are now independent and both non-empty

I also improved the documentation of ZonePtr and emphasized the transferred ownership semantics.
Title: Thor C++ Library – An SFML extension
Post by: lakunar on June 12, 2011, 02:05:53 pm
Shouldn't it be "affector" instead of "emitter"? in
include/Thor/Particles/Emitter.hpp, line 147
Code: [Select]
00147 void AddAffector(Affector::Ptr emitter, const RemovalTrigger& trigger);

---
Shouldn't this work?:
Code: [Select]
thor::ParticleSystem system(image);
...
thor::TargetEmitter::Ptr temitter( new thor::TargetEmitter(200.f, 2.f) );
...
temitter->Emit(system,10.0f); //Error

Error:
Code: [Select]
 'thor::Emitter::Adder' is an inaccessible base of 'thor::ParticleSystem'
Or did i misunderstood there something?

---
Quote
Okay, it is now easier :D

Ah this Copy Funktion looks nice and easy
Title: Thor C++ Library – An SFML extension
Post by: Nexus on June 12, 2011, 02:10:53 pm
Quote from: "lakunar"
Shouldn't it be "affector" instead of "emitter"? in
include/Thor/Particles/Emitter.hpp, line 147
Yes, I just fixed this a few minutes ago 8)

Quote from: "lakunar"
Shouldn't this work?:
Code: [Select]
thor::ParticleSystem system(image);
...
thor::TargetEmitter::Ptr temitter( new thor::TargetEmitter(200.f, 2.f) );
...
temitter->Emit(system,10.0f); //Error
No, you don't need to call Emit() directly. Just add the emitter to the system and update it every frame:
Code: [Select]
thor::ParticleSystem system(image);
thor::TargetEmitter::Ptr temitter( new thor::TargetEmitter(200.f, 2.f) );
system.AddEmitter(temitter);

    // later, in the main loop
    system.Update(frameTimeInSeconds);
    system.Draw(window);

You could also have a look at the Particles tutorial on my homepage.
Title: Thor C++ Library – An SFML extension
Post by: lakunar on June 12, 2011, 02:35:53 pm
Quote
you don't need to call Emit() directly

mh
The Problem:
I want to emit particles on an event but just for a certain time.  And i thought that adding and removing(auto) emitters from the system isn't the best way to do this. So I searched for a fire, start func.
Problem with AddEmitter is that it causes a assertion fail if it is called to fast(as long the emitter is emitting) with the same emitter
Title: Thor C++ Library – An SFML extension
Post by: Nexus on June 12, 2011, 02:44:10 pm
Quote from: "lakunar"
I want to emit particles on an event but just for a certain time.  And i thought that adding and removing(auto) emitters from the system isn't the best way to do this.
It was indeed not the best approach until recently. But now, there is an AddEmitter() overload that takes a functor to remove the emitter upon a certain condition (see documentation (http://www.bromeon.ch/thor/v1.1/doc/classthor_1_1_particle_system.html)). There is even a predefined functor for a time-limited emission:
Code: [Select]
thor::ParticleSystem system(...);
thor::Emitter::Ptr emitter(...);
system.AddEmitter(emitter, thor::ParticleSystem::TimeLimit(0.5f));


Quote from: "lakunar"
Problem with AddEmitter is that it causes a assertion fail if it is called to fast(I think) with the same emitter
Yes, the assertion should prevent you from adding an already added emitter by accident.
Title: Thor C++ Library – An SFML extension
Post by: lakunar on June 13, 2011, 04:30:34 pm
Quote from: "Nexus"
Yes, the assertion should prevent you from adding an already added emitter by accident.

Ok.

I have another Problem :?
I don't know if this is a thor or sfml bug.

But the following Code doesn't copy the Image because image2.Copy check if image2 is not 0 (Width,Height) which it is after construction.
Code: [Select]
sf::Image image;
if (!image.LoadFromFile("Media/particles.png"))
  return EXIT_FAILURE;
sf::Image image2;
image2.Copy(image,0,0,sf::IntRect(0,0,32,32));


So this causes a problem with:
Code: [Select]
thor::ParticleSystem system(image,sf::IntRect(0,0,32,32));
which tries to copy the Image in a new constuctet one
Title: Thor C++ Library – An SFML extension
Post by: Nexus on June 13, 2011, 05:08:59 pm
Thanks a lot for the report, partial images should work now. It was indeed my mistake, I hadn't allocated enough space before calling sf::Image::Copy().
Title: Thor C++ Library – An SFML extension
Post by: Kened on June 20, 2011, 07:22:22 pm
First of all, I'm C#.NET-spoiled guy so this is my first time doing something like building libraries. Therefore it's very likely I've made some dumb mistake along the way.
I built and installed sfml2 (the recommended version) without issues and tested some basic stuff.
Then I made makefile (following the tutorial) for the Thor library (the latest from SVN), but when I tried to build it (MinGW 4.4.1) I got this:
Code: [Select]
c:\dev\thor-build>mingw32-make
[  2%] Building CXX object src/CMakeFiles/thor.dir/Random.cpp.obj
C:\dev\svn\thor\src\Random.cpp:96: error: 'Uint64' in namespace 'sf' does not name a type
C:\dev\svn\thor\src\Random.cpp: In member function 'sf::Uint32 thor::<unnamed>::Engine::operator()()':
C:\dev\svn\thor\src\Random.cpp:71: error: 'Uint64' in namespace 'sf' does not name a type
C:\dev\svn\thor\src\Random.cpp:73: error: 'x' was not declared in this scope
C:\dev\svn\thor\src\Random.cpp:73: error: 'a' was not declared in this scope
C:\dev\svn\thor\src\Random.cpp: In member function 'void thor::<unnamed>::Engine::seed(sf::Uint32)':
C:\dev\svn\thor\src\Random.cpp:80: error: 'x' was not declared in this scope
mingw32-make[2]: *** [src/CMakeFiles/thor.dir/Random.cpp.obj] Error 1
mingw32-make[1]: *** [src/CMakeFiles/thor.dir/all] Error 2
mingw32-make: *** [all] Error 2
Title: Thor C++ Library – An SFML extension
Post by: Nexus on June 20, 2011, 09:10:00 pm
It seems like you use an SFML revision which doesn't have sf::Uint64 yet. Update to the newest Git revision of SFML, then it should work.

The SFML version provided on the website is recommended only for Thor 1.0. Maybe I should clarify that.
Title: Thor C++ Library – An SFML extension
Post by: Kened on June 21, 2011, 09:56:09 am
Oh, so that was the stupid mistake I made. Thank you, it works now.
Title: Thor C++ Library – An SFML extension
Post by: Haikarainen on June 21, 2011, 10:41:26 am
GREAT Project! dont know if i posted here before, but i just now checked out your lib in detail, and i have to say i am very impressed! It really is more too it than what meets the eye at first glance.

Really fell in love with your particle system, and geometrical capabilities :D
Title: Thor C++ Library – An SFML extension
Post by: Nexus on June 21, 2011, 07:24:12 pm
Thank you :)

I have already thought about extending the Geometry module (for example to provide a Polygon class and a ContainsPoint() function, which would not be difficult to implement by means of the triangulation functions). But I believe for this kind of functionality, there are much more specific and optimized libraries around, among others Boost.Geometry coming with Boost 1.47. Maybe I am going to use Boost one day, it would simplify a lot...

Anyway, I still have to find a more generic design of the animation system, allowing sprite modifications apart from subrects. And this in turn may require modifications of the Resource module (especially ResourcePtr). At the same time, I have to keep pace with SFML's modifications :)
Title: Thor C++ Library – An SFML extension
Post by: OniLinkPlus on June 21, 2011, 09:22:23 pm
Hey, Nexus, if you're interested, I implemented a concave point detection algorithm in my Terra Game Engine. It goes through all of the points in a shape and creates a list of the points which are concave. Maybe you could use it for triangulation?
Title: Thor C++ Library – An SFML extension
Post by: Nexus on June 21, 2011, 11:54:33 pm
Thanks, but I have already implemented a Delaunay triangulation algorithm, so it should theoretically be possible to use it for the polygons. The question is rather how powerful the Thor.Geometry module should be, at the moment it exists mainly for the particle emitter zones. But as stated, there are more important tasks for the next time ;)
Title: Thor C++ Library – An SFML extension
Post by: gavintlgold on June 27, 2011, 07:20:06 am
Hi there, I've been working on wrapping my head around the proper way to go about handling events with Thor's Action and EventSystem. So far I have a system that works but it seems clunky and it also does not provide the event information to the callbacks. Here's what I have:

Code: [Select]
(in constructor)
m_action_map["on-jump"] = thor::Action(sf::Key::T, thor::Action::PressOnce);
m_event_system.Connect("on-jump", std::tr1::bind(&SomeClass::onJump, &m_someclass));
... (continue for other events) ...

(in event function, per event)
m_action_map.PushEvent(event);

(in update function)
m_action_map.VisitEachFunction(thor::ActionForwarder(m_event_system) );
m_action_map.ClearEvents();


So anyway this code works properly for calling callbacks on events, and even adding in unchanging parameters but if I wanted to place something where the mouse cursor is when the action happens I wouldn't be able to do that since the callbacks don't know about the input or the event. Since my sfml window is in a singleton, I could just do
Code: [Select]
Game::singleton()->GetWindow()->GetInput().GetX()
but that's not a nice way to do it at all. SfmlEventSystem seems like it does this properly but the examples don't show a way to link specific string-based actions like "on-jump" with sfml events. The closest snippet I found was the following:

Code: [Select]
thor::ActionMap<std::string> actionMap(myWindow.GetInput());
thor::SfmlEventSystem sfmlEventSystem(myWindow);
sfmlEventSystem.ForwardEvents( thor::EventForwarder(actionMap) );


But there's not enough context in that snippet for me to understand how to get it to work as I'd like it.

Am I at least doing things somewhat as intended? Is there an easier way to bind custom actions to keypresses? For now I wrote a little macro to get the two lines down to one, but that's obviously not something I'm proud of. Thanks for any advice you can give.
Title: Thor C++ Library – An SFML extension
Post by: Nexus on June 27, 2011, 11:03:33 am
Quote from: "gavintlgold"
So anyway this code works properly for calling callbacks on events, and even adding in unchanging parameters but if I wanted to place something where the mouse cursor is when the action happens I wouldn't be able to do that since the callbacks don't know about the input or the event.
Couldn't you pass a reference to sf::Input to the callback?
Code: [Select]
void OnJump(const sf::Input& realtimeInput);

sf::RenderWindow window = ...;
thor::EventSystem<std::string> system;
system.Connect( "on-jump", std::tr1::bind(&OnJump, std::tr1::cref(window.GetInput())) );


Quote from: "gavintlgold"
I've been working on wrapping my head around the proper way to go about handling events with Thor's Action and EventSystem. So far I have a system that works but it seems clunky
Yes, I am not very happy about the current way of event handling either. In Thor 1.0, there was mainly the callback system thor::SfmlEventSystem to handle events. Later, I introduced thor::ActionMap and thor::Action (which I think are very useful) but these classes are not very well integrated to the rest. Currently, the Events module contains the following components:
Generally, I tend to make ActionSystem more powerful and to get rid of SfmlEventSystem; I don't know if the latter is even used by anybody. We have recently had a similar discussion in the french thread (http://www.sfml-dev.org/forum-fr/viewtopic.php?t=3523&start=30) about this.

However, for thor::ActionMap to completely replace thor::SfmlEventSystem, it needs to be able to pass the events to the callbacks. And here is my problem: Because ActionMap abstracts the events away (you can use sf::Event as a trigger for actions, as well as sf::Input), there needn't necessarily be a event to forward. So we cannot connect a listener like void OnTextEntered(sf::Event event), but we need the sf::Event object to extract event.Text.Unicode. I have to think more about this...

So, I am open to any suggestions as well as reports about the usefulness of the current Events module (especially the SfmlEventSystem class) :)
Title: Thor C++ Library – An SFML extension
Post by: gavintlgold on June 27, 2011, 12:47:23 pm
You're right, a reference to sf::Input should simplify that scenario a bit.

Thanks for the quick response, and I certainly understand the difficulty in getting ActionSystem to pass events properly.

For now though, it's very nice to be able to set up all the callbacks and actions in one place with ActionMap. I think this will make control preferences much easier as well, since I can probably pass some config file's values to the ActionMap (no more fiddling with switch statements!)
Title: Thor C++ Library – An SFML extension
Post by: Nexus on June 29, 2011, 02:44:43 am
Okay, I have spent some work on making thor::ActionMap more powerful and flexible.

You can now pass any SFML events to it (not only key/mouse/joystick press or release), and link actions to callback functions, and extract the sf::Event and sf::Input objects inside the callbacks. The implementation isn't extremely beautiful, but I focus on the ease of use ;)
Code: [Select]
// Callback function for jumps
void OnJump(thor::ActionContext<std::string> context);

int main()
{
sf::Window window(sf::VideoMode(400, 300), "Thor Action Demo");

// Link T key to "jump" action
thor::ActionMap<std::string> map(window.GetInput());
map["jump"] = thor::Action(sf::Key::T, thor::Action::PressOnce);

// Register callback for jumps
thor::ActionMap<std::string>::CallbackSystem system;
system.Connect("jump", &OnJump);

for (;;)
{
// Clear temporarily pushed events
map.ClearEvents();

// Forward all events to the action map
sf::Event event;
while (window.PollEvent(event))
map.PushEvent(event);

// Forward actions to callbacks
map.InvokeCallbacks(system);

window.Display();
}
}

void OnJump(thor::ActionContext<std::string> context)
{
// Get the event that triggered this action
sf::Event event = context.Events[0];
assert(event.Type == sf::Event::KeyPressed && event.Key.Code == sf::Key::T);

// Get the realtime sf::Input
const sf::Input& input = context.RealtimeInput;
assert(input.IsKeyDown(sf::Key::T));

// Get the action identifier "jump"
std::string id = context.ActionId;
assert(id == "jump");
}

And I believe this spells doom for thor::SfmlEventSystem. The class is probably going to be removed during the next days.

I haven't tested the new functionality much yet, I would like to hear your thoughts about the modification of the Events module :)
Title: Thor C++ Library – An SFML extension
Post by: gavintlgold on June 29, 2011, 04:40:35 am
So far it's been a great help (and I imagine it'll get better once I use events that involve special data such as text input and mouse position).

One request I would make is an ActionIdentifier that works for both Presses and Releases (shouldn't it be relatively easy to do with an old-style bitwise filtering system?). That way I can set up a connection that will call on both press and release (for example for setting movement). Then inside the callback I can check if it's a press or release in a switch statement.

For now I can do:
Code: [Select]
Action(sf::Key::A, Action::PressOnce) || Action(sf::Key::A, Action::ReleaseOnce)
 in the Connect statement, which is perhaps good enough, but a little clunky. Ideally I'd be able to do something like
Code: [Select]
Action(sf::Key::A, Action::PressOnce | Action::ReleaseOnce)

Thanks again for the work you've been doing on this--it's proven invaluable for this project.
Title: Thor C++ Library – An SFML extension
Post by: Nexus on June 29, 2011, 11:06:33 am
I'm glad the actions are helpful for your project :)

What would you say about a fourth enumerator?
Code: [Select]
Action(sf::Key::A, Action::Once)
For a bitwise system, I lose type safety because I need an unsigned int. And I don't think mixing the flag Realtime with PressOnce or ReleaseOnce makes sense... Or does it?
Title: Thor C++ Library – An SFML extension
Post by: panithadrum on June 29, 2011, 04:14:19 pm
HI Nexus, your library is amazing. I love your programming style!

May I modify your triangulation code to work with Qt's classes directly?

Edit: Could you explain the difference between thor::Triangulate and thor::TriangulatePolygon?
Title: Thor C++ Library – An SFML extension
Post by: Nexus on June 29, 2011, 05:28:45 pm
Quote from: "panithadrum"
May I modify your triangulation code to work with Qt's classes directly?
Yes, just regard the license :)
 
But I would like to know if the functions aren't generic and extensible enough to be used with Qt, so that I can improve them if necessary. I also recommend to use the public interface, since the implementation might change in the future. What do you exactly want to modify?


Quote from: "panithadrum"
Edit: Could you explain the difference between thor::Triangulate and thor::TriangulatePolygon?
Sure.
(https://legacy.sfmluploads.org/cache/pics/40_[Thor]Triangulate.png) (https://legacy.sfmluploads.org/cache/pics/41_[Thor]TriangulatePolygon.png)
Title: Thor C++ Library – An SFML extension
Post by: gavintlgold on June 29, 2011, 06:19:02 pm
Action::Once sounds like a good solution.

Mixing PressOnce with Realtime could be slightly useful in that it would allow me to initialize a state and then poll it (so PressOnce would call the function once, to set up initial values like the first mouse position in a drag, then Realtime would call every frame to update something, and then perhaps ReleaseOnce would call to clean up or finalize a value).

However, this probably is better done in separate functions anyway, so mixing the two is not a big issue for me.

One thing I'd like to add is that it wasn't immediately obvious to me at least that using a Realtime event would not produce an event in the context.Events vector. So I was polling the event and it was segfaulting. Perhaps mentioning this in the documentation would be helpful to some people who are trying to understand the system.

Thanks!
Title: Thor C++ Library – An SFML extension
Post by: panithadrum on June 29, 2011, 07:49:34 pm
Quote from: "Nexus"
Quote from: "panithadrum"
May I modify your triangulation code to work with Qt's classes directly?
Yes, just regard the license :)

I just read the license terms, thanks :D

 
Quote from: "Nexus"
But I would like to know if the functions aren't generic and extensible enough to be used with Qt, so that I can improve them if necessary. I also recommend to use the public interface, since the implementation might change in the future. What do you exactly want to modify?

I can actually use your code, but not without converting all my QPointF to thor::Vertex and thor::Triangle<thor::Vertex> to QVector<QPointF> back again. Maybe it's not a need at all to make the triangulation work with Qt directly (at least is not critic for sure).


Quote from: "Nexus"
Quote from: "panithadrum"
Edit: Could you explain the difference between thor::Triangulate and thor::TriangulatePolygon?
Sure.
  • thor::Triangulate() computes triangles between all points, i.e. the resulting shape is always convex, as seen in the left picture.
  • thor::TriangulatePolygon() computes only triangles inside a polygon. That is, the resulting shape can be concave, and the order of points is relevant to recognize the polygon outline. The result is visible in the right picture. By the way, this function is used inside thor::ConcaveShape.
(https://legacy.sfmluploads.org/cache/pics/40_[Thor]Triangulate.png) (https://legacy.sfmluploads.org/cache/pics/41_[Thor]TriangulatePolygon.png)

Thanks a lot, just what wanted to see!
Title: Thor C++ Library – An SFML extension
Post by: Nexus on June 29, 2011, 08:20:50 pm
Quote from: "gavintlgold"
Action::Once sounds like a good solution.
Okay, I have added thor::Action::Once. The tasks I am going to complete next:
Quote from: "panithadrum"
I can actually use your code, but not without converting all my QPointF to thor::Vertex and thor::Triangle<thor::Vertex> to QVector<QPointF> back again. Maybe it's not a need at all to make the triangulation work with Qt directly (at least is not critic for sure).
Ah yes, it is a little bit unfortunate that you need to convert these types. Inside the algorithm, I need a type like thor::Vertex that I know, I can't work with arbitrary template parameters because I don't know their interface (besides, the whole algorithm would have to be written in the header).

But If I were you, I would really not modify every single place where thor::Vertex is used, this is just too much work. And if I change something in the algorithm, you'd have to do it again ;)

A relatively comfortable solution would be a class derived from thor::Vertex that provides implicit conversions from and to QPoint. Or use something like std::transform(). This shouldn't be a big performance issue.
Title: Thor C++ Library – An SFML extension
Post by: gavintlgold on June 29, 2011, 08:45:09 pm
Quote from: "Nexus"
Probably transform the sf::Event vector to a single event. I think it is easier for the user if the callback is invoked multiple times (once for every sf::Event), so there is no need for a loop in every listener. Mostly, there is only one event per frame anyway.


This sounds good. Having a vector of events seemed a bit clunky to me as well, given that one big reason for using events is to remove loop-like behavior.
Title: Thor C++ Library – An SFML extension
Post by: Nexus on June 29, 2011, 10:36:29 pm
I have finished the three points. The class template thor::ActionContext now looks like this:
Code: [Select]
template <typename ActionIdentifier>
struct ActionContext
{
const sf::Input* RealtimeInput;
const sf::Event* Event;
ActionIdentifier ActionId;
};
Title: Thor C++ Library – An SFML extension
Post by: gavintlgold on June 29, 2011, 10:52:02 pm
Yep, it works nicely for me. The use of pointers is also good as it removes the burden of declaring a const reference and removes the possibility of making an accidental copy.

It's great. One last question: Is there a way to integrate mouse movement? Right now the only thing left in my onEvent function deals with MouseMove events. I may have missed something but I don't see a way to create an action that only involves mouse movement (mousebuttonpressed hooked with realtime would work for when a button is pressed, but not without a press).

I really can't thank you enough for the work you've done so far. This is far easier than trying to set up sigc++ or boost::signals to work with the engine (they work but don't integrate so well with SFML obviously). It also lets me have signals without an implementation that is too complex for what I need, and without having to include yet another library.
Title: Thor C++ Library – An SFML extension
Post by: Nexus on June 29, 2011, 11:11:43 pm
Quote from: "gavintlgold"
One last question: Is there a way to integrate mouse movement? Right now the only thing left in my onEvent function deals with MouseMove events. I may have missed something but I don't see a way to create an action that only involves mouse movement
You can do it like this:
Code: [Select]
void OnMouseMove(thor::ActionContext<std::string> context)
{
sf::Event::MouseMoveEvent movement = context.Event->MouseMove;
std::cout << "Mouse moved:  X = " << movement.X << ", Y = " << movement.Y << std::endl;
}

int main()
{
sf::Window window(...);
thor::ActionMap<std::string> map(window.GetInput());
map["mouse"] = thor::Action(sf::Event::MouseMoved);

thor::ActionMap<std::string>::CallbackSystem system;
system.Connect("mouse", &OnMouseMove);

for (;;)
{
map.ClearEvents();

sf::Event event;
while (window.PollEvent(event))
map.PushEvent(event);

map.InvokeCallbacks(system);

window.Display();
}
}

By the way, I think about providing a function that calls ClearEvents(), PushEvent() and InvokeCallbacks()... But that's not too important at the moment.


Quote from: "gavintlgold"
I really can't thank you enough for the work you've done so far.
You're welcome, thanks a lot for giving feedback and appreciating my work! :)
Title: Thor C++ Library – An SFML extension
Post by: gavintlgold on June 30, 2011, 12:17:38 am
Right... now that it's integrated with SFML that works! Excellent.
Title: Thor C++ Library – An SFML extension
Post by: Haikarainen on July 01, 2011, 06:46:55 am
Thor crashes for me, when trying to draw  a particlesystem.

stacktrace
Code: [Select]
#0 6699D948 sf::RenderTarget::SaveGLStates() (C:\WINDOWS\system32\sfml-graphics-2.dll:??)
#1 70ECCE66 thor::ParticleSystem::PushOpenGLStates() (E:\Work\c++\modernarcade\bin\Release\libthor.dll:??)
#2 70ECD21E thor::ParticleSystem::Draw() (E:\Work\c++\modernarcade\bin\Release\libthor.dll:??)
#3 00000000 0x0040748b in ??() (??:??)
#4 00000000 0x02179e38 in ??() (??:??)
#5 00000000 0x003f72e8 in ??() (??:??)
#6 00000000 0x43e40000 in ??() (??:??)
#7 00000000 0x00000000 in ??() (??:??)


code for the particlesystem
Code: [Select]

this->pImage.LoadFromFile("./data/particles/test.png");
this->pSystem = new thor::ParticleSystem(this->pImage);
this->pEmit = thor::DirectionalEmitter::Create(30.f, 5.f);
this->pSystem->AddEmitter(this->pEmit);

this->pAffect = thor::FadeOutAffector::Create(0.1f);
this->pSystem->AddAffector(this->pAffect);
this->pSystem->SetGlowing(true);

... And in loop:

this->pSystem->Update(this->EngineHandle->GetFrameTime());
//Crashes on this line
this->pSystem->Draw(*this->EngineHandle->GetVideo()->GetWindow());
Title: Thor C++ Library – An SFML extension
Post by: gavintlgold on July 01, 2011, 06:59:45 am
Did you clean the entire project and rebuild? If it helps you, Nexus, particles are working properly for me with somewhat similar code. I know I had a crashing problem earlier where a rebuild solved it.
Title: Thor C++ Library – An SFML extension
Post by: Haikarainen on July 01, 2011, 07:36:45 am
Quote from: "gavintlgold"
Did you clean the entire project and rebuild? If it helps you, Nexus, particles are working properly for me with somewhat similar code. I know I had a crashing problem earlier where a rebuild solved it.


Yep, still no luck. I'm having some other issues with SFML tho, the same project crashes when trying to run the debugtarget. Crashes when you try to clear the renderwindow.

Edit: The same code didnt crash in the debugmode before i reformatted my computer

Edit2: Fixed the other sfml-related issue, apparently i had to link -d libs to the debugtarget. No luck on thor tho

Edit3: Located the line in thor's sourcecode where it segfaults;
Code: [Select]
void ParticleSystem::PushOpenGLStates(sf::RenderWindow& target) const
{
// Switch to manual OpenGL handling, save SFML's state
target.SaveGLStates(); <<----- THIS LINE
target.SetActive();


It's line 250 in ParticleSystem.cpp


Edit4: Last edit: Read http://www.sfml-dev.org/forum/viewtopic.php?p=34122
Title: Thor C++ Library – An SFML extension
Post by: panithadrum on July 03, 2011, 07:52:12 pm
Quote from: "Nexus"
Quote from: "panithadrum"
I can actually use your code, but not without converting all my QPointF to thor::Vertex and thor::Triangle<thor::Vertex> to QVector<QPointF> back again. Maybe it's not a need at all to make the triangulation work with Qt directly (at least is not critic for sure).
Ah yes, it is a little bit unfortunate that you need to convert these types. Inside the algorithm, I need a type like thor::Vertex that I know, I can't work with arbitrary template parameters because I don't know their interface (besides, the whole algorithm would have to be written in the header).

Yeah, you are right. I will convert my structs to thor::Vertex, but just wanted you to know that you can abstract an interface with some sort of macros (I don't know how exactly). Here is an example: http://geometrylibrary.geodan.nl/x01__qt__example_8cpp-example.html.

Code: [Select]
// Adapt a QPointF such that it can be handled by GGL
BOOST_GEOMETRY_REGISTER_POINT_2D_GET_SET(QPointF, double, cs::cartesian, x, y, setX, setY)

With this line the library can access to QPointF!
Title: Thor C++ Library – An SFML extension
Post by: Nexus on July 03, 2011, 09:19:51 pm
Thanks, that's an interesting way to do it. It is typical for Boost to be generic at all costs ;)

Nevertheless, I don't want to do it that way because
Title: Thor C++ Library – An SFML extension
Post by: Groogy on July 03, 2011, 09:41:11 pm
Quote from: "Nexus"
  • The conversion speed shouldn't be the issue: std::copy()/std::transform() is fast compared with the work done by the triangulation.

I can kind of verify that. The models in my engine is "compiled" which actually transforms the vertexes in a more suitable way to be drawn to speed it up. The conversion is really fast and simple. The "compiled" version is never shown outwards and only make sense to the renderer in the engine.

And let's say we have:
It would be a trivial task to convert input and output, also preferable in the long run because of the points Nexus made.
Title: Thor C++ Library – An SFML extension
Post by: gavintlgold on July 04, 2011, 02:04:14 am
I'd like to mention that the particle system is really great for me. I wrote a new affector that just scales the image every step (I'd like to suggest that's included in thor by default actually, as it's sort of the only obvious thing missing from the particles package). Here's an example of it in action with a nice particle texture I made:

(http://i.imgur.com/g4RRgl.jpg) (http://i.imgur.com/g4RRg.png)
Title: Thor C++ Library – An SFML extension
Post by: Haikarainen on July 04, 2011, 03:15:17 am
Quote from: "gavintlgold"
I'd like to mention that the particle system is really great for me. I wrote a new affector that just scales the image every step (I'd like to suggest that's included in thor by default actually, as it's sort of the only obvious thing missing from the particles package). Here's an example of it in action with a nice particle texture I made:

(http://i.imgur.com/g4RRgl.jpg) (http://i.imgur.com/g4RRg.png)


Lol, was just about to post that as a feature request :P
Also, can you iterate thru particles and get their global position, size etc? Need simple collision detection for rain/skillsystem/waterfall/realistic smoke etc. :)
Title: Thor C++ Library – An SFML extension
Post by: gavintlgold on July 04, 2011, 03:22:37 am
Scale affector is really trivial (Nexus, please excuse me for not obeying your naming style):

Header
Code: [Select]
#include <Thor/Particles.hpp>

class ScaleAffector : public thor::Affector
{
  public:
    typedef std::tr1::shared_ptr<ScaleAffector> Ptr;

  public:
    static Ptr Create(sf::Vector2f scaleFactor);

  public:
    explicit ScaleAffector(sf::Vector2f scaleFactor);

    virtual void Affect(thor::Particle& particle, float dt);

    void SetScaleFactor(sf::Vector2f scaleFactor);

    sf::Vector2f GetScaleFactor() const;

  private:
    sf::Vector2f m_scale_factor;
};


Source
Code: [Select]
#include "affectors.hpp"

ScaleAffector::Ptr ScaleAffector::Create(sf::Vector2f scaleFactor)
{
  return Ptr( new ScaleAffector(scaleFactor) );
}

ScaleAffector::ScaleAffector(sf::Vector2f scaleFactor)
: m_scale_factor(scaleFactor)
{
}

void ScaleAffector::Affect(thor::Particle& particle, float dt)
{
  particle.Scale += dt * m_scale_factor;
}

void ScaleAffector::SetScaleFactor(sf::Vector2f scaleFactor)
{
  m_scale_factor = scaleFactor;
}

sf::Vector2f ScaleAffector::GetScaleFactor() const
{
  return m_scale_factor;
}


No, there's no way to iterate through all the particles. I think a better way for you to do what you want would be to make a physics affector that checks the particle's position in Affect and does any physics calculations there. It should be very simple with a format similar to the code above. You can see the properties of a particle that you can modify here (http://www.bromeon.ch/thor/v1.1/doc/classthor_1_1_particle.html)
Title: Thor C++ Library – An SFML extension
Post by: Haikarainen on July 04, 2011, 03:54:50 am
Quote from: "gavintlgold"

No, there's no way to iterate through all the particles. I think a better way for you to do what you want would be to make a physics affector that checks the particle's position in Affect and does any physics calculations there. It should be very simple with a format similar to the code above. You can see the properties of a particle that you can modify here (http://www.bromeon.ch/thor/v1.1/doc/classthor_1_1_particle.html)


The thing is I need collisions for more than the particles properties itself. I think iterating through all the particles would also be a powerful function in this lib.
Title: Thor C++ Library – An SFML extension
Post by: Nexus on July 04, 2011, 10:25:35 am
Quote from: "gavintlgold"
I'd like to mention that the particle system is really great for me. I wrote a new affector that just scales the image every step (I'd like to suggest that's included in thor by default actually, as it's sort of the only obvious thing missing from the particles package).
Hehe, I thought about implementing a ScaleAffector before the first release, but I wasn't sure whether it would be used often, and I didn't want to bloat the interface. But if you find it useful, I will add it :)

Quote from: "Haikarainen"
The thing is I need collisions for more than the particles properties itself. I think iterating through all the particles would also be a powerful function in this lib.
With an affector, you can iterate through the particles, even if this happens implicitly (no for loop). I don't like to give access to the internal container, as it is an implementation detail.

By the way, should I hide the public constructors of the affectors and emitters? This might prevent mistakes because you can only use emitters/affectors within shared_ptr objects, so the Create() factories would be enough...
Title: Thor C++ Library – An SFML extension
Post by: Haikarainen on July 04, 2011, 11:04:15 am
Quote from: "Nexus"
But if you find it useful, I will add it :)

Good news!

Quote from: "Nexus"
With an affector, you can iterate through the particles, even if this happens implicitly (no for loop). I don't like to give access to the internal container, as it is an implementation detail.

Ok, thats understandable, but how would you do that? All i found is ComputeNbParticles ?


Quote from: "Nexus"
By the way, should I hide the public constructors of the affectors and emitters? This might prevent mistakes because you can only use emitters/affectors within shared_ptr objects, so the Create() factories would be enough...

Probably would be a good idea

edit: Oh, Btw; Is there any possibility to configure the glow-option? Like strength, color etc? Or is it just on/off in the lower level too?
Title: Thor C++ Library – An SFML extension
Post by: Nexus on July 04, 2011, 11:14:19 am
Quote from: "Haikarainen"
Ok, thats understandable, but how would you do that? All i found is ComputeNbParticles ?
Derive a class from thor::Affector and override the Affect() method. You can also pass information about other entities (e.g. a collision manager reference) to the constructor of your class. ComputeNbParticles() is just needed for custom emitters.
Code: [Select]
class PhysicsAffector : thor::Affector
{
public:
virtual void Affect(thor::Particle& particle, float /*dt is ignored*/)
{
DoSomething(particle.Position)
}
};


Quote from: "Haikarainen"
edit: Oh, Btw; Is there any possibility to configure the glow-option? Like strength, color etc? Or is it just on/off in the lower level too?
No, it is currently just on/off. Do you have a suggestion how I could make it more configurable? I don't know how to set the strength, because the glow just influences the OpenGL blend mode (ParticleSystem.cpp, line 300).
Title: Thor C++ Library – An SFML extension
Post by: Nexus on July 04, 2011, 12:23:41 pm
thor::ScaleAffector is now ready to use.

I have found out that making the constructors private is a bad idea since it prevents justified use cases like inheriting or aggregating an existing affector/emitter, therefore I won't do it.
Title: Thor C++ Library – An SFML extension
Post by: Haikarainen on July 04, 2011, 01:40:03 pm
Quote from: "Nexus"
Do you have a suggestion how I could make it more configurable? I don't know how to set the strength, because the glow just influences the OpenGL blend mode (ParticleSystem.cpp, line 300).


Hmm googled around on the function and it uses, and it became clear to me that it's the textures that have to be modified. Apparently too much lightness and too little transparency creates a way too bright result.
Title: Thor C++ Library – An SFML extension
Post by: Haikarainen on July 04, 2011, 01:58:42 pm
Quote from: "Nexus"
thor::ScaleAffector is now ready to use.


Sweet ! :D

Btw, I fixed the cmake issue, can configure, generate and compile :) After cleaning up everything, all old sfml and thor-stuff, paths in env-vars etc, and downloading fresh copies, it STILL didn't work.

What I had to do was set the "CMAKE_MODULE_PATH" in cmake manually to "sfml2dir/cmake/Modules", weirdly enough it wasnt able to find the FindSFML file until then, even when I set the SFML_DIR and SFMLDIR path's correctly!

Ohwell it works now, even tho the binaries were placed in the src-dir, i really hope i helped out someone else with the same problem :)
Title: Thor C++ Library – An SFML extension
Post by: Laurent on July 04, 2011, 03:32:33 pm
Quote
What I had to do was set the "CMAKE_MODULE_PATH" in cmake manually to "sfml2dir/cmake/Modules"

If you install SFML properly (I insist on "install", not "compile") the FindSFML.cmake file should be copied to the CMake directory and therefore be automatically available. So I think you just forgot to install it ;)
Title: Thor C++ Library – An SFML extension
Post by: Haikarainen on July 04, 2011, 04:25:44 pm
Quote from: "Laurent"
Quote
What I had to do was set the "CMAKE_MODULE_PATH" in cmake manually to "sfml2dir/cmake/Modules"

If you install SFML properly (I insist on "install", not "compile") the FindSFML.cmake file should be copied to the CMake directory and therefore be automatically available. So I think you just forgot to install it ;)


Oooooooh :D Thanks for filling that in for me, now i should know in the future :) Doing stuff i always use linux for, in windows is confusing. hehe

Edit: Btw, did you mean the sfmldir/cmake dir ?
Title: Thor C++ Library – An SFML extension
Post by: Laurent on July 04, 2011, 07:28:53 pm
Quote
Edit: Btw, did you mean the sfmldir/cmake dir ?

Hum? I was just talking about the FindSFML.cmake file.
Title: Thor C++ Library – An SFML extension
Post by: Nexus on July 05, 2011, 12:25:07 am
Didn't I tell you this in the other thread (http://www.sfml-dev.org/forum/viewtopic.php?t=5211)? Okay, it was probably not that clear :P

Back to topic: I finally need to make the animations more flexible. I have thought about a design like this:
Code: [Select]
class Animation
{
    public:
        virtual ~Animation();
        virtual void Apply(sf::Sprite& sprite, float passedTime) = 0;
};

Concrete animations modifying different properties of a sprite (subrect, color, ...) are represented by separate derived classes. This is very similar to the thor::Affector class hierarchy. The important point is that the user can write his own animations.

The thor::Animator class is going to remain more or less the same, except that it takes shared_ptr<Animation> instead of copies and that there is no more default subrect, but a default animation being applied when no other animation is active. And perhaps I am going to transform it to a template in order to allow arbitrary IDs (not only strings).

Then I also need a way to combine multiple animations: Parallel (modify subrect and color at the same time) and perhaps also sequential (after setting the subrects, change color). I can achieve this by writing a class like this:
Code: [Select]
class CombinedAnimation : public Animation
{
    public:
        // Adds an animation that starts delay seconds after the normal
        // start (so we can parallelize time-shifted versions)
        void AddAnimation(shared_ptr<Animation> anim, float delay = 0.f);

        // Applies all animations
        virtual void Apply(sf::Sprite& sprite, float passedTime);
};

Maybe also a separate class for sequential animations, although this can theoretically be done with the above delay. I don't know whether this delay is a good idea, I will probably not add it from beginning.

What do you think? Far too complicated? Not generic enough? All suggestions are welcome!
Title: Thor C++ Library – An SFML extension
Post by: gavintlgold on July 05, 2011, 12:33:58 am
I was thinking about this very recently, and how it might be useful to me. Basically, what would be great to have is a tweener system, that interpolates any float variables. I'm not sure exactly how this could be done, but perhaps if you wrap a small struct around a variable such as a float or Vector2f (sort of like a smart pointer does) and then use that, it might work very well. This would support animations that involve movement, fading, zooming, and really anything you can think of, since it's generic enough to apply to anything.

Where this sort of thing gets very powerful is in interpolation types--adding in support for linear, cubic, 'bouncy' (overshooting), and other stuff. This would be useful for a huge amount of purposes--title screen animations, fading sprites in and out, particle affectors, even cameras (zoomy cameras look nicer--I'm using a homemade one myself but it's a lot of messiness to manage)

There are tweening libraries out there, for example http://code.google.com/p/cpptweener/ . If you think making a tweener is out of the scope of Thor, I'll probably end up using that instead--but having it integrated into particles and things would be very nice indeed.
Title: Thor C++ Library – An SFML extension
Post by: Nexus on July 05, 2011, 01:03:57 am
You won't believe it, I have already had some kind of an interval class in mind, also to produce random numbers. I haven't considered it useful enough yet... But I will certainly take a look at the cpptweener library, thanks for the link.
Title: Thor C++ Library – An SFML extension
Post by: gavintlgold on July 05, 2011, 01:21:35 am
Sounds good. cpptweener's method, which basically involves references to variables, seems somehow unsafe. Also, it uncouples the variable from the tweener, which is nice if you need to tween multiple things with one tweener, but not so good for making quick tweens as it involves at least two variables to juggle. However, it's likely a great source for the math behind nonlinear tweens--it can get a little heady at times, at least for me.

I think having a wrapper with an operator() or somesuch to get the contained type would be a neater way to do it properly. Calling it "Range<contained>" might work nicely. I imagine something like this:

Code: [Select]
template <typename T>
class Range
{
    public:
        const T& operator()() // could also be GetValue() or somesuch
        {
            return mType;
        }

        void Update(float percentage);
        void SetStep(float step);

    private:
        T mType;
        float mStep;
};


I imagine you can derive different types of tweens from that, like LinearRange, CubicRange etc. Alternatively you can have an enum for range types, but I think this way is better.

EDIT: Changed to floats for timestep
Title: Thor C++ Library – An SFML extension
Post by: gsaurus on July 05, 2011, 01:38:24 am
When doing a game I'm interested on updating animations accordingly to the current game frame, which is an integer for me. I tell an animation when it started, then I ask it to update accordingly to the current frame. Animation duration is in frames. This way an animation always run the same way whatever the frame rate is. This isn't generic, neither using a float for time.

I strongly recommend a float interpolation param from 0 to 1. It's simple to convert between game time/frames to animation time, knowing when the animation started and it's duration (whatever that means for the user).

I'm working on a project which intends to provide a generic sprite format for 2D games and that's how I intend to provide animations mainly. I'll post about it when I get the binding for SFML working..
Edit: Actually I stick with the integer duration but provide both time and 0-1 float access.
Title: Thor C++ Library – An SFML extension
Post by: gavintlgold on July 05, 2011, 01:48:07 am
Yes, you're right. The container's progress should be measured in a float between 0 and 1, so that you don't have to deal with time at all. I think having the two methods "Update" and "SetStep" are good though, as that way some people can set the value manually, and others can attach it to existing timers.

It gets rid of having to scale the timestep within the class as well, instead it can be handled by the user like this: Update((float)dt * 0.25f) or whatever.
Title: Thor C++ Library – An SFML extension
Post by: Nexus on July 05, 2011, 01:56:28 pm
I have downloaded cppTweener, but up to now, I haven't been able to create meaningful scenarios. The code is completely undocumented and the examples  depend on other libraries. Apart from that, some code in cppTweeners relies on unspecified behavior and is thus not standard-conforming. For example, the evaluation order of t and --t in the following statement is not defined by the C++ standard.
Code: [Select]
return -c/2 * (((t-2)*(--t)) - 1) + b;
Would you mind explaining me the most important functionality? Is the basic concept a function that takes a float in [0, 1] and returns a scaled version in [a, b], whereby this transformation can be linear, cubic or whatever?

I rather don't plan to provide all these mathematical mappings, but maybe an interface that allows customization by the user. Do you have concrete suggestions for an integration into Animations?

By the way, what do you think about the basic Animation design as described above?
Title: Thor C++ Library – An SFML extension
Post by: gavintlgold on July 05, 2011, 08:48:03 pm
I never really looked at the code for it, and I may have confused it with another library which I took a closer look at. But yes, the idea is that you can set a starting and end position and it will give you an interpolation between 0 and 1. The simplest example is linear, where 0 equals the starting position and 1 equals the ending position, and anything in between is just an even subdivision. More useful are the other types though, which allow you to have movement that starts out fast and slows down as it gets closer to its target. Then you have ease in and ease out, which allow you to start slowly and speed up or start fast and slow down, or start and end slowly.

Basically it's useful when you don't want to snap directly to a target but move there smoothly. It's a bit hard for me to describe properly, but maybe this video makes more sense:

http://www.youtube.com/watch?v=E4Fbk52Mk1w&feature=player_detailpage#t=26s If you look at the time I've linked to, when the desktop is zooming out it speeds up near the middle and slows down right before it reaches its target. It would look bad if it was just a linear scaling effect, but since it uses tweening it looks 'smooth'.

Anyway, that's an example of how you can apply an effect to a sprite, but it's also useful for fading text and moving views, and things like that. That's why I suggested making it more generic to accept any sort of variable.

Again, if you don't think it's something that would fit into Thor, don't worry about it--I'll probably try to make my own version. I most likely release it, too.
Title: Thor C++ Library – An SFML extension
Post by: gsaurus on July 06, 2011, 12:42:59 am
I think it would be enough to provide a generic interface for animations with an update function which takes a float param ranging from 0-1. It's then the implementations that decide how to deal with it to interpolate its information.

You can eventually overload the function to accept an extra argument of some class or function pointer that transforms the argument with a math function. In that case you can supply some strategies by default, like polynomial and trigonometric.
Title: Thor C++ Library – An SFML extension
Post by: Nexus on July 06, 2011, 01:01:44 am
gavintlgold, thanks for the explanation.

gsaurus, I don't know whether a [0,1] float would be easier on user side. Currently, the user just has to pass the frame time, and the animations are automatically updated according to the time passed. The animations themselves work with absolute times. Maybe I could change their (thor::Animation) time handling to normalized floats and leave thor::Animator's absolute. But since an animation has often the same duration, it would be necessary to specify the absolute time duration multiple times (once for each animator).

Concerning the scale function: They would be quite customizable with std::tr1::function. But I am probably going to implement the basic animation system first...
Title: Thor C++ Library – An SFML extension
Post by: gavintlgold on July 06, 2011, 01:15:43 am
Ah, very nice. Using a tr1::function for scaling sounds like a great idea. I suppose it would work very much like an affector does with particles now? That's an excellent way to accomplish the same thing. Maybe there's a way to have animation affectors work directly with particles too (for fading in and out for example)--but that might be too complicated.

If you'd like, I'll make (and donate) a few stock animation affectors (whatever you'll plan on calling them) that will accomplish the math of what cpptweener does, for cubic or bouncy or other interpolations. So for now you can just get the basic system working for a linear animation.
Title: Thor C++ Library – An SFML extension
Post by: Nexus on July 06, 2011, 01:24:58 am
Quote from: "gavintlgold"
Maybe there's a way to have animation affectors work directly with particles too (for fading in and out for example)--but that might be too complicated.
The idea is basically a good one, however I would have to find an abstract way to cover both sf::Sprite and thor::Particle, but their interfaces are completely different. The user code is likely to become more complicated with such an enforced commonality, so I rather risk to duplicate a few things. Maybe I can still reuse code internally.

Quote from: "gavintlgold"
If you'd like, I'll make (and donate) a few stock animation affectors (whatever you'll plan on calling them) that will accomplish the math of what cpptweener does, for cubic or bouncy or other interpolations. So for now you can just get the basic system working for a linear animation.
Thanks a lot for the offer! But don't implement something specific for Thor yet. I still don't know whether and how I will provide this functionality, and I don't want you to rewrite everything ;)
Title: Thor C++ Library – An SFML extension
Post by: gsaurus on July 06, 2011, 02:14:01 am
Well I was moved by gavintlgold suggestion about interpolations. Both update ways would be good.

Is there any advantage on using floats (time in seconds) instead of integers (game frames)? I don't see why one would want to play an animation for one game frame and half.

I didn't look at the source code neither tried the library yet, so pardon me to ask: is the dt passed on the Update of the Animator the time passed since the last game frame?

Are you planning to remove the duration getter from the Animation class? (why?)
Title: Thor C++ Library – An SFML extension
Post by: gavintlgold on July 06, 2011, 02:24:16 am
Quote from: "gsaurus"
I don't see why one would want to play an animation for one game frame and half.


In my game engine, at least, I calculate the time since the last frame and use that for physics calculations and any sort of time-based animation. I like this method because it allows players of the game to have as fast an FPS as their computer allows. It also opens the opportunity for those with slower PCs to play the game properly at 25 FPS if the need arises, since everything is based on the delta.

The game frame system that you're using is an alternative to this, in which all frames are equally spaced. It works as well, but is less flexible as it requires all gamers to be playing at the same FPS. While it doesn't really matter for most 2d games where the graphics and physics aren't likely to get very complex, I figure it allows room for complexity if I use the delta-based system.

So the DT stands for milliseconds per frame--in your engine you could pass it a constant value, but in mine it's not so simple.
Title: Thor C++ Library – An SFML extension
Post by: gsaurus on July 06, 2011, 03:27:27 am
Quote from: "gavintlgold"

The game frame system that you're using is an alternative to this, in which all frames are equally spaced. It works as well, but is less flexible as it requires all gamers to be playing at the same FPS

While game logics are updated at a fixed rate, display is updated whenever possible. So slower machines may experience frameskip (different FPS).

I think this is particularly good for networking games that need to run on all machines the same way and keep state correct from frame to frame. I think that calculations with the elapsed time for game logics would result in small errors, leading to higher synchronization problems.

I think game logics should always play at a fixed rate.
For instance, if one fix game logics to 30fps, the game loop can still be 60fps, updating animations whenever possible (so benefiting from better machines), while game logics are updated every 2 frames.
Though I don't see a reason to update it more often than 60fps, so considering 60fps the time unit, an integer fits well and isn't susceptible to small errors.
Title: Thor C++ Library – An SFML extension
Post by: Nexus on July 06, 2011, 12:00:59 pm
Quote from: "gsaurus"
Is there any advantage on using floats (time in seconds) instead of integers (game frames)?
I think floats are more flexible. With integers, the user is forced to manually compute the correct frame or to keep a fixed framerate.

Quote from: "gsaurus"
I didn't look at the source code neither tried the library yet, so pardon me to ask: is the dt passed on the Update of the Animator the time passed since the last game frame?
Yes.

Quote from: "gsaurus"
Are you planning to remove the duration getter from the Animation class? (why?)
It depends on the choice of the float range. If I use the absolute time like now, I will keep thor::Animation::GetDuration() because thor::Animator needs it. But for a scalable [0,1] (scaled inside thor::Animator), a method to return the animation duration is pointless.
Title: Thor C++ Library – An SFML extension
Post by: gsaurus on July 06, 2011, 12:37:22 pm
What if one want to play an animation in backwards?
Title: Thor C++ Library – An SFML extension
Post by: Nexus on July 06, 2011, 01:09:58 pm
Good point. This behavior can be implemented with a class derived from thor::Animation that wraps another animation and forwards the difference between the total and the passed time. Similar to the above class for parallel animations.

This may seem complicated, but note that thor::Animator just provides an easy interface to play animations. It takes care of details like progress computation, choice of the right animation, recognition of the animation's end, etc. You can also directly access thor::Animation, its method Apply() takes an absolute progress time (unlike thor::Animator::Apply() which takes a time difference).
Title: Thor C++ Library – An SFML extension
Post by: gsaurus on July 06, 2011, 01:26:41 pm
I see.
Quote from: "Nexus"
You can also directly access thor::Animation, its method Apply() takes an absolute progress time (unlike thor::Animator::Apply() which takes a time difference).

Well then I don't need the Animator. But yeah I know what you mean, the interface provided by the Animator should be enough for most situations.
Title: Thor C++ Library – An SFML extension
Post by: Nexus on July 06, 2011, 05:37:27 pm
I finally committed the new Animation class hierarchy. There is now a separate module for animations in Thor.

Up to now, I have still used absolute times in thor::Animation. Maybe this will change to a [0.f, 1.f] progress scale in the future. The thing I don't like with that approach:

Code: [Select]
thor::FrameAnimation::Ptr anim(new thor::FrameAnimation);
anim->AddFrame(1.f, sf::IntRect(...));
anim->AddFrame(4.f, sf::IntRect(...));
// Durations are relative to each other:
// First frame takes 1/5, second 4/5 of the time

thor::Animator animator1, animator2;
animator1.AddAnimation("id", anim, 2.5f);
animator2.AddAnimation("id", anim, 2.5f);

The duration is no more part of the animation, one has to specify it at the animator. So, if multiple animators refer to a single animation, the duration has to be specified every time, although an animation mostly has the same duration for all sf::Sprites it is applied to...

On the other side, a [0,1] scale makes many things simpler and seems like a good approach as already proven by thor::Affector.
Title: Thor C++ Library – An SFML extension
Post by: Nexus on July 10, 2011, 02:38:06 pm
Good news for the people who use the dynamic dispatchers: They have become much more powerful, they support now implicit derived-to-base conversions. If the argument types don't match exactly, the dispatcher tries to find functions taking base class pointers/references. Here is a complete example:
Code: [Select]
// For this code, you needn't compile or link Thor, the dispatchers are a header-only feature
#define THOR_STATIC

#include <Thor/Tools/DoubleDispatcher.hpp>
#include <iostream>

// Example class hierarchy
class Object { public: virtual ~Object() {} };
class Asteroid : public Object {};
class Ship     : public Object {};
class Missile  : public Object {};

// Functions for collision with different argument types
void Collision(Asteroid*, Asteroid*)    { std::cout << "Asteroid-Asteroid\n"; }
void Collision(Asteroid*, Ship*)        { std::cout << "Asteroid-Ship\n";     }
void Collision(Ship*,     Ship*)        { std::cout << "Ship-Ship\n";         }
void Collision(Object*,   Object*)      { std::cout << "Other objects\n";     }

int main()
{
    // Register class hierarchy (required to know derived-base relations at runtime)
    THOR_RTTI_BASE(Object)
        THOR_RTTI_DERIVED(Asteroid)
        THOR_RTTI_DERIVED(Ship)
        THOR_RTTI_DERIVED(Missile);

    // Create dispatcher and register functions
    thor::DoubleDispatcher<Object*> dispatcher(true, true);
    dispatcher.Register<Asteroid, Asteroid>(&Collision);
    dispatcher.Register<Asteroid, Ship>    (&Collision);
    dispatcher.Register<Ship,     Ship>    (&Collision);
    dispatcher.Register<Object,   Object>  (&Collision);

    // Base class pointers (no static type information about derived classes)
    Object* a = new Asteroid;
    Object* s = new Ship;
    Object* m = new Missile;

    // Invoke functions, let dispatcher choose the correct overload
    dispatcher.Call(a, s); // Output: "Asteroid-Ship"
    dispatcher.Call(a, a); // Output: "Asteroid-Asteroid"
    dispatcher.Call(s, s); // Output: "Ship-Ship"
    dispatcher.Call(a, m); // Output: "Other objects"
   
    delete m;
    delete s;
    delete a;
}

I have also updated the Events module according to SFML's new input system. Next, I am probably going to set Animation progresses to [0,1], and maybe to use std::tr1::shared_ptr for resources.
Title: Thor C++ Library – An SFML extension
Post by: Haikarainen on July 11, 2011, 08:23:54 pm
Hey nexus, im currently rewriting an old lost animationsystem,  and i wonder can your timers be used to accurately check how many ms has past since last timer reset?  It's for frames playtime, and im wondering if a playtime at 10ms per frame would get choppy orsomething?
Title: Thor C++ Library – An SFML extension
Post by: Nexus on July 11, 2011, 09:40:41 pm
The classes in the Time module provide the same precision as the underlying sf::Clock, so milliseconds should work.
Title: Thor C++ Library – An SFML extension
Post by: Haikarainen on July 11, 2011, 11:00:52 pm
Quote from: "Nexus"
The classes in the Time module provide the same precision as the underlying sf::Clock, so milliseconds should work.


Yep, they work perfectly :) Thanks alot! the Thor-lib is totally awesome :D
Title: Thor C++ Library – An SFML extension
Post by: Nexus on July 14, 2011, 09:28:17 pm
Okay, I changed the animations to take a [0,1] progress instead of an absolute value. I believe, in the end things get simpler and more flexible (especially when it comes to playing parallel or serial animations). The drawback is that the absolute duration has to be specified at every animator, but since thor::Animator is a copyable class, it can be initialized once and copied for different sf::Sprite instances.

Stuff I am planning to implement next:
It should already be possible to implement the discussed interpolation/tweener feature relatively easy on user side:
Code: [Select]
class MyAnimation : public thor::Animation
{
public:
MyAnimation(thor::Animation::Ptr wrappedAnimation, std::function<float(float)> intervalTransformer)
: mAnimation(wrappedAnimation)
, mTransformer(intervalTransformer)
{
}

virtual void Apply(sf::Sprite& target, float progress) const
{
mAnimation->Apply(target, mTransformer(progress));
}

private:
thor::Animation::Ptr            mAnimation;
std::function<float(float)>     mTransformer;
};

Perhaps I can even take something like this into the public API. It would allow many things, such as reversing an animation, distorting the process, playing an animation multiple times, etc.

In fact, a std::tr1::function<void(sf::Sprite&, float)> might have been an interesting alternative to the whole thor::Animation class hierarchy... But probably the current approach is easier, especially for people not used to high-order functions and binders. In the end, it might require slightly more code because people cannot use super-compact std::tr1::bind() calls ;)
Title: Thor C++ Library – An SFML extension
Post by: gsaurus on July 18, 2011, 01:43:22 pm
Will you change the methods Update to take a Uint in milliseconds soon?
Title: Thor C++ Library – An SFML extension
Post by: Nexus on July 18, 2011, 03:04:27 pm
No, I don't plan to change them, unsigned int milliseconds complicate the handling of delta-times a lot. In fact, they make time handling more complicated in general. For the Time module classes, I nearly must provide sf::Uint32 because floats get unprecise after some time, and because the underlying sf::Clock uses Uint32, too (so there would always be rounding errors at conversions).

We have already discussed that here (http://www.sfml-dev.org/forum/viewtopic.php?p=31998#31998), I'm not really satisfied with this inconsistency. The only thing I can imagine is a thor::Time class, but there are several issues with it, too (see link). For the delta-time parameters, I think the easiest solution is to keep them as float seconds. So, thor::Time would be used by thor::StopWatch, thor::Timer and thor::TriggeringTimer.
Title: Thor C++ Library – An SFML extension
Post by: spiritofforcefield on July 18, 2011, 03:36:09 pm
Wow, I should have visited this forum earlier!
Title: Thor C++ Library – An SFML extension
Post by: gsaurus on July 18, 2011, 07:24:35 pm
Ok, seems a reasonable solution. Plus it's all about visual stuff, for applications that must be very precise there isn't a real problem if one keep logics and visualization separated :P
Title: Thor C++ Library – An SFML extension
Post by: MorleyDev on August 09, 2011, 02:41:54 pm
Out of curiosity, in the tutorials you list unique_ptr as unique ownership and then auto_ptr as moved ownership. But from what I can tell, unique_ptr is also moveable via the use of r-value references (unique_ptr&&) and was intended to replace auto_ptr which is deprecated due to it's usage of hacks to simulate r-value references?
Title: Thor C++ Library – An SFML extension
Post by: Nexus on August 09, 2011, 07:58:15 pm
You are perfectly right, but unique_ptr is not implicitly movable.  You need to invoke std::move() to transfer ownership from a named object – in contrast to auto_ptr. Maybe I should make that clearer, putting it on the same level as scoped_ptr without further notes might indeed be confusing.

By the way, good to know that some people actually read the tutorials :D
Title: Thor C++ Library – An SFML extension
Post by: WitchD0ctor on August 11, 2011, 11:56:03 am
Im just curious but, with the new changes in SFML regarding the new texture class, is it possible yet to texture a shape? That together with your Concave shape class would allow neat dynamic terrain
Title: Thor C++ Library – An SFML extension
Post by: Nexus on August 11, 2011, 02:10:01 pm
I don't think it is possible yet. But as far as I remember, Laurent once planned to implement something similar, I don't know if that is still up-to-date however. Maybe with the new rendering system...
Title: Thor C++ Library – An SFML extension
Post by: Laurent on August 11, 2011, 03:09:40 pm
Quote
Maybe with the new rendering system...

Indeed.
Title: Thor C++ Library – An SFML extension
Post by: Nexus on August 13, 2011, 01:34:09 am
Now that I have had some time again, I could implement a lot of things, especially in the Resources module:
Title: Thor C++ Library – An SFML extension
Post by: Richy19 on September 20, 2011, 06:07:18 pm
I seem to be getting some problems with CMake, Im sure there problems on my end but I dont know what it could be.

this is configuring NMake
Quote
The C compiler identification is MSVC
The CXX compiler identification is MSVC
Check for CL compiler version
Check for CL compiler version - 1600
Check if this is a free VC compiler
Check if this is a free VC compiler - yes
Check for working C compiler: C:/Program Files/Microsoft Visual Studio 10.0/VC/bin/cl.exe
CMake Error: Remove failed on file: C:/Documents and Settings/Richy/My Documents/thor/make/CMakeFiles/CMakeTmp/cmTryCompileExec.exe: System Error: Permission denied
CMake Error: Remove failed on file: C:/Documents and Settings/Richy/My Documents/thor/make/CMakeFiles/CMakeTmp/Debug/cmTryCompileExec.exe: System Error: Permission denied
Check for working C compiler: C:/Program Files/Microsoft Visual Studio 10.0/VC/bin/cl.exe -- broken
CMake Error at C:/Program Files/CMake 2.8/share/cmake-2.8/Modules/CMakeTestCCompiler.cmake:52 (MESSAGE):
  The C compiler "C:/Program Files/Microsoft Visual Studio
  10.0/VC/bin/cl.exe" is not able to compile a simple test program.

  It fails with the following output:

   Change Dir: C:/Documents and Settings/Richy/My Documents/thor/make/CMakeFiles/CMakeTmp

 

  Run Build Command:nmake /NOLOGO "cmTryCompileExec\fast"

     "C:\Program Files\Microsoft Visual Studio 10.0\VC\BIN\nmake.exe" -f
  CMakeFiles\cmTryCompileExec.dir\build.make /nologo -L
  CMakeFiles\cmTryCompileExec.dir\build

     "C:\Program Files\CMake 2.8\bin\cmake.exe" -E cmake_progress_report
  "C:\Documents and Settings\Richy\My
  Documents\thor\make\CMakeFiles\CMakeTmp\CMakeFiles" 1

  Building C object CMakeFiles/cmTryCompileExec.dir/testCCompiler.c.obj

     C:\PROGRA~1\MICROS~2.0\VC\bin\cl.exe
  @C:\DOCUME~1\Richy\LOCALS~1\Temp\nm17F.tmp

  testCCompiler.c

  Linking C executable cmTryCompileExec.exe

     "C:\Program Files\CMake 2.8\bin\cmake.exe" -E vs_link_exe
  C:\PROGRA~1\MICROS~2.0\VC\bin\cl.exe /nologo
  @CMakeFiles\cmTryCompileExec.dir\objects1.rsp
  @C:\DOCUME~1\Richy\LOCALS~1\Temp\nm180.tmp

  LINK : fatal error LNK1104: cannot open file 'cmTryCompileExec.exe'


  LINK Pass 1 failed.  with 2

  NMAKE : fatal error U1077: '"C:\Program Files\CMake 2.8\bin\cmake.exe"' :
  return code '0xffffffff'

  Stop.

  NMAKE : fatal error U1077: '"C:\Program Files\Microsoft Visual Studio
  10.0\VC\BIN\nmake.exe"' : return code '0x2'

  Stop.

 

 

  CMake will not be able to correctly generate this project.
Call Stack (most recent call first):
  CMakeLists.txt:42 (project)


Configuring incomplete, errors occurred!


And this is VS2010 solutions
Quote
Check for working C compiler using: Visual Studio 10
CMake Error: Remove failed on file: C:/Documents and Settings/Richy/My Documents/thor/make/CMakeFiles/CMakeTmp/cmTryCompileExec.exe: System Error: Permission denied
CMake Error: Remove failed on file: C:/Documents and Settings/Richy/My Documents/thor/make/CMakeFiles/CMakeTmp/Debug/cmTryCompileExec.exe: System Error: Permission denied
Check for working C compiler using: Visual Studio 10 -- broken
CMake Error at C:/Program Files/CMake 2.8/share/cmake-2.8/Modules/CMakeTestCCompiler.cmake:52 (MESSAGE):
  The C compiler "C:/Program Files/Microsoft Visual Studio
  10.0/VC/bin/cl.exe" is not able to compile a simple test program.

  It fails with the following output:

   Change Dir: C:/Documents and Settings/Richy/My Documents/thor/make/CMakeFiles/CMakeTmp

 

  Run Build Command:C:\PROGRA~1\MICROS~2.0\Common7\IDE\devenv.com
  CMAKE_TRY_COMPILE.sln /build Debug /project cmTryCompileExec

 

  Microsoft (R) Visual Studio Version 10.0.30319.1.

  Copyright (C) Microsoft Corp.  All rights reserved.

  1>------ Build started: Project: cmTryCompileExec, Configuration: Debug
  Win32 ------

  1> testCCompiler.c

  1>LINK : fatal error LNK1104: cannot open file 'C:\Documents and
  Settings\Richy\My
  Documents\thor\make\CMakeFiles\CMakeTmp\Debug\cmTryCompileExec.exe'

  ========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped
  ==========

 

 

  CMake will not be able to correctly generate this project.
Call Stack (most recent call first):
  CMakeLists.txt:42 (project)


Configuring incomplete, errors occurred!
Title: Thor C++ Library – An SFML extension
Post by: Nexus on September 20, 2011, 08:36:59 pm
"Permission denied" may indicate that you don't have enough rights to delete the file or that it is currently in use. Make sure this is not the case. Try to start the Visual Studio command prompt as administrator.

What did you enter to the VS command prompt? It should be something like this:
Code: [Select]
cmake -G "NMake Makefiles" -D CMAKE_BUILD_TYPE=Release -D THOR_SHARED_LIBS=FALSE -D THOR_STATIC_STD_LIBS=FALSE -D SFMLDIR="C:/Program Files/C++ Libraries/SFML" -D CMAKE_INSTALL_PREFIX="../install" ../../trunk

nmake install

And does it work when you generate a Visual Studio Solution instead of a NMake Makefile?
Title: Thor C++ Library – An SFML extension
Post by: Richy19 on September 20, 2011, 09:04:32 pm
Hi, yea you are right.
Im on XP so i thought i was admin right away but turns out im not.
Running as admin fixed it
Title: Thor C++ Library – An SFML extension
Post by: Nexus on September 30, 2011, 08:05:03 pm
Because it may be very useful for user-defined controls, I implemented string conversion functions for sf::Keyboard::Key and sf::Mouse::Button enumerators. Both directions (from and to string) are provided.

Example:
Code: [Select]
#include <Thor/Events/InputNames.hpp>

int main()
{
    std::string str = thor::ToString(sf::Key::A);
    // str == "A"
}


And I still think about an extension of the animation functionality (with the above-mentioned points, maybe classes for serial/parallel animations). But I only get few feedback concerning the Animation module, I don't even know if there are people that actually use it... So if you have some ideas, express them ;)
Title: Thor C++ Library – An SFML extension
Post by: Haikarainen on September 30, 2011, 11:05:15 pm
Quote from: "Nexus"
Because it may be very useful for user-defined controls, I implemented string conversion functions for sf::Keyboard::Key and sf::Mouse::Button enumerators. Both directions (from and to string) are provided.


Huh, thats pretty nice. How do you do it? Hardcoded strings or are they configurable using the api (as in not changing the api)?

Something tells me that thor will sometime be grown into something close to a game engine ;)
Title: Thor C++ Library – An SFML extension
Post by: Nexus on September 30, 2011, 11:23:44 pm
Quote from: "Haikarainen"
Huh, thats pretty nice. How do you do it? Hardcoded strings or are they configurable using the api (as in not changing the api)?
Since C++ offers no possibility to get all constants of an enum, each enumerator is hardcoded. I tried to reduce boilerplate code to a minimum and have a static assertion in case Laurent suddenly adds new keys ;)

If you mean whether a string associated with an enumerator can be configured by the user, this is not the case yet. But it sounds like a good idea. However there is the possibility that a key is mapped to different strings during runtime, if one is not careful enough...


Quote from: "Haikarainen"
Something tells me that thor will sometime be grown into something close to a game engine ;)
Depends on what you understand by game engine. I see it like some sort of rigid framework that offers functionality for almost every part of a game and where the single parts often depend on each other. With Thor, I try to keep them more or less independent, and to cover mainly frequently-used functionality. Thus, one can only use the modules that are needed, without aligning the whole application towards the library design.

However, the Resource module tends to increase coupling. For example, the Particles and Animation module depend on it since they use ResourcePtr. Maybe I switch to the standard shared_ptr... This just as a sidenote. I'm always open for design discussions, just post what you think! :)
Title: Thor C++ Library – An SFML extension
Post by: Haikarainen on October 01, 2011, 01:08:52 am
Quote from: "Nexus"
Since C++ offers no possibility to get all constants of an enum, each enumerator is hardcoded. I tried to reduce boilerplate code to a minimum and have a static assertion in case Laurent suddenly adds new keys ;)


Allright, I myself is currently on work on a keymanager for my game. It includes classes; nn::KeyManager, nn::Key, nn::Action and nn::Binding.

nn::KeyManager hold all keys, actions and binding.

nn::Key holds a sf::KeyCode~, a name and a displayname, and functions to get if the key was pressed, released, the current state etc.

nn::Action holds a displayname and a commandname.

nn::Binding holds a pointer to a nn::Key and a nn::Action.

The (command)name in both action and key is the "identifier", what to type in console to bind them togheter(for example "bind leftctrl jump"), commandname also has to be a valid command for the engine (a la quake).
And the DisplayName for both is what to show to the user(especially under the keybinding options in menu).

Just thought I'd share in case you wanna bind your key-management with your custom eventhandling thingy  ;)

Quote from: "Nexus"
Depends on what you understand by game engine. I see it like some sort of rigid framework that offers functionality for almost every part of a game and where the single parts often depend on each other. With Thor, I try to keep them more or less independent, and to cover mainly frequently-used functionality. Thus, one can only use the modules that are needed, without aligning the whole application towards the library design.

However, the Resource module tends to increase coupling. For example, the Particles and Animation module depend on it since they use ResourcePtr. Maybe I switch to the standard shared_ptr... This just as a sidenote. I'm always open for design discussions, just post what you think! :)


Class independence is a great thing for such a library, And I totally agree on keeping it as a framework rather than an engine, lets just call it a really flexible game api-extension to SFML :P

Regarding the Particles, im not sure how things work anymore since I dont use them after my SFML2-post-texture-port (never got the time to look up the changes heh), but it sure would be nice if you didnt bind the particles to your resourcemanagement, since Im looking forward to implement particles in my game again, and I allready have my own resourcemanager wich have to load files from my custom packaging format etc. Remember that you could just bind a sf::Image(when it was current) to a particlemanager, isnt that the case anymore(but for sf::Texture) ?
Title: Thor C++ Library – An SFML extension
Post by: Nexus on October 01, 2011, 11:52:06 am
Quote from: "Haikarainen"
Just thought I'd share in case you wanna bind your key-management with your custom eventhandling thingy  ;)
Thank you. I have already received requests to serialize thor::Action (which supports arbitrary events, realtime inputs and their logical combinations), but I will probably not do this in near future, because it involves parsers and/or serialize frameworks, it would be quite specific and I don't know how many people would even find it useful. The new functions in InputNames.hpp provide a possibility to perform such a task on user side.

Quote from: "Haikarainen"
Remember that you could just bind a sf::Image(when it was current) to a particlemanager, isnt that the case anymore(but for sf::Texture) ?
Yes, see here (http://www.bromeon.ch/thor/v1.1/doc/classthor_1_1_particle_system.html). There is still the possibility to copy whole sf::Image objects or parts of them. Additionally, there is a constructor from a shared sf::Texture object (using thor::ResourcePtr, here I could use shared_ptr). I don't know whether the constructors taking sf::Image will last forever, they're more a interim solution for the SFML API change. And one can have the same functionality with the sf::Texture constructors only, by creating a texture and calling sf::Texture::LoadFromImage() first. What do you think will be a common/simple way of specifying the particle texture?

The dependency on the Resources module is not too big however, since you can put anything into a ResourcePtr (like shared_ptr), so resources needn't be loaded by my manager. What bothers me more is the fact that I sometimes use shared_ptr (to carry the abstract Emitter, Affector, Animation classes) and sometimes ResourcePtr (for SFML resource classes), although both could be used interchangeably at the moment. In fact, ResourcePtr is only a thin wrapper around shared_ptr. I can still add new features to ResourcePtr one day, that's the main reason why I haven't used shared_ptr everywhere ;)
Title: Thor C++ Library – An SFML extension
Post by: Silvah on October 01, 2011, 06:17:12 pm
Just a little question: do you really want to copy the map and the key in src/InputNames.cpp, line 40?
Code: [Select]
 typename M::mapped_type GetMapped(M map, typename M::key_type key)
  //                                ^      ^^^^^^^^^^^^^^^^^^^^

Also, could you consider increasing the precision of pi in Math/Trigonometry.hpp to make the computations depending on it slightly more, well, precise?
Title: Thor C++ Library – An SFML extension
Post by: Nexus on October 02, 2011, 03:54:22 am
Quote from: "Silvah"
Just a little question: do you really want to copy the map and the key in src/InputNames.cpp, line 40?
No, of course not. Thanks a lot for the hint!

There are also other optimizations possible, I could even use std::vector instead of std::map in one direction. But I'm not sure if the enumerator values will remain subsequent, in SFML 1.6 they were not.

Quote from: "Silvah"
Also, could you consider increasing the precision of pi in Math/Trigonometry.hpp to make the computations depending on it slightly more, well, precise?
I can increase the literal lengths in thor::TrigonometricTraits<T>::Pi(), but I don't know whether the float version (which is equal to thor::Pi) is affected by it...
Title: Thor C++ Library – An SFML extension
Post by: Silvah on October 02, 2011, 12:09:50 pm
Quote from: "Nexus"
I can increase the literal lengths in thor::TrigonometricTraits<T>::Pi(), but I don't know whether the float version (which is equal to thor::Pi) is affected by it...
So just increase the lengths and let the compiler worry about the most precise representation. It may not affect float version, but certainly will affect double and long double versions.
Title: Thor C++ Library – An SFML extension
Post by: Nexus on October 02, 2011, 01:43:47 pm
Okay, the Pi precision has been extended and the InputNames performance has been improved.

Other tasks:
Ideas and suggestions concerning one or more of those points are welcome!
Title: Thor C++ Library – An SFML extension
Post by: gsaurus on October 02, 2011, 04:18:32 pm
I still didn't get why the association of strings to keys feature. Can you give an example where it's important?
Title: Thor C++ Library – An SFML extension
Post by: Nexus on October 02, 2011, 04:34:11 pm
You mean the way back? It is useful to serialize data. For example, a user can store key controls in a text document, and parse them when reading the file.

He could also convert the enumerators to integers and vice versa, but this has some disadvantages: The text document is full of magic numbers, making manual read/write access complicated. And if Laurent changes the enumerator values one day, the integer mapping will be broken. On the other side, these are also reasons against SetInputName() functions -- I cannot guarantee a bijective mapping anymore, if the user specifies his own strings.

Or do you think converting strings to keys/mouse buttons is rather unnecessary?
Title: Thor C++ Library – An SFML extension
Post by: gsaurus on October 02, 2011, 06:59:58 pm
I think it's unnecessary as it's just for serialization purposes.
I think that SFML keys should change anyway, the enum keys could refer to ASCII values for example.
Title: Thor C++ Library – An SFML extension
Post by: Nexus on October 02, 2011, 07:12:02 pm
Quote from: "gsaurus"
I think it's unnecessary as it's just for serialization purposes.
The functionality can also be used to display key names on screen (again for dynamic controls), serialization is just one example. But wouldn't serialization alone be reason enough? It seems unnecessary that everybody who isn't satisfied with the integer conversion needs to reinvent the wheel.

Quote from: "gsaurus"
I think that SFML keys should change anyway, the enum keys could refer to ASCII values for example.
They did in SFML 1.6, but probably not many people made use of it. And other than alphanumeric keys would still have more or less arbitrary values, so you don't get a human-readable description for them. Apart from that, a consecutive implementation also allows simpler and faster treatment (e.g. one can iterate through the enumerators).
Title: Thor C++ Library – An SFML extension
Post by: N1ghtly on October 02, 2011, 08:03:41 pm
This library is bawz :D
Keep it up, Nexus!
Title: Thor C++ Library – An SFML extension
Post by: Ceylo on December 14, 2011, 11:36:36 am
I was wondering whether Thor had some support for a clock class that would be able to correctly handle the OS standby mode. From what I saw, it hasn't.

I mean, currently sf::Clock just computes the difference between the current time and the start time. If your computer goes to standby mode, your app logic and drawing is paused, but the clock goes on. When waking up, there'll be a huge "frame time". I'd like to know if it's possible to handle this correctly, maybe with a class that get the OS ticks rather than real elapsed time.

Thanks,
Ceylo
Title: Thor C++ Library – An SFML extension
Post by: Nexus on December 14, 2011, 11:42:31 am
I have already thought about some kind of "manual" clock. That is, two classes like thor::StopWatch and thor::Timer, but instead of basing on sf::Clock, they have an Update(float dt) function and accumulate a member variable. The advantage is better interaction with game logics, for example one doesn't have to stop/restart timers every time a game is paused. It can be updated along with all other game elements that need frametime updates. If no game logic is computed, time stands still -- also in standby mode.

But I would like to unify both approaches somehow, I'm not sure whether it would confuse users if I provided two versions of each class. Some ideas?
Title: Thor C++ Library – An SFML extension
Post by: Laurent on December 14, 2011, 12:02:06 pm
Quote
I have already thought about some kind of "manual" clock. That is, two classes like thor::StopWatch and thor::Timer, but instead of basing on sf::Clock, they have an Update(float dt) function and accumulate a member variable.

Does this really need a class? Obviously, it won't require Start/Stop/Reset methods, so basically a simple variable can do the job.
Code: [Select]
float accumulatedTime = 0;

while (running)
{
    if (!paused)
        accumulatedTime += elapsedTime;
}

And it doesn't solve the problem, it's just shifted to the calculation of elapsedTime.

Quote
I'd like to know if it's possible to handle this correctly, maybe with a class that get the OS ticks rather than real elapsed time.

I think that using a timing function that calculates the CPU time rather than the real time would be enough. According to the OgreTimer implementation that I saw this morning, std::clock() behaves likes this.
Title: Thor C++ Library – An SFML extension
Post by: Nexus on December 16, 2011, 10:21:31 pm
Quote from: "Laurent"
Does this really need a class?
Not necessarily, but with its encapsulation it provides protection against accidental modifications, and it allows convenient methods to set/get different time units. Plus, code gets more expressive with meaningful method names.

Quote from: "Laurent"
And it doesn't solve the problem, it's just shifted to the calculation of elapsedTime.
This is true. Does sf::RenderWindow::GetFrameTime() use sf::Clock internally? In this case, how can one get the "real" frame time (e.g. without the time the window is moved/resized, or the computer is in standby mode)?

Quote from: "Laurent"
According to the OgreTimer implementation that I saw this morning, std::clock() behaves likes this.
The problem with the standard clocks is that they're unprecise (or at least, the standard doesn't require high resolution). Maybe, Boost.DateTime is an alternative. But I don't like its complexity...
Title: Thor C++ Library – An SFML extension
Post by: Laurent on December 16, 2011, 11:39:21 pm
Quote
Does sf::RenderWindow::GetFrameTime() use sf::Clock internally?

Yes.

Quote
In this case, how can one get the "real" frame time (e.g. without the time the window is moved/resized, or the computer is in standby mode)?

You can't. I don't think that you can magically skip these things, you have to detect and handle them one by one.
Title: Thor C++ Library – An SFML extension
Post by: Nexus on December 17, 2011, 12:01:18 am
Okay. For a workaround, one can also cheat and set an upper limit for the frame time. This could also be handled automatically by a class.

Maybe one class is enough, something like thor::ManualClock with a basic sf::Clock-like interface. The ultimative flexibility could be achived by making thor::StopWatch and thor::Timer templates and by letting them choose the underlying clock. But this becomes too complicated very fast.
Title: Thor C++ Library – An SFML extension
Post by: Ceylo on December 17, 2011, 11:15:03 am
Quote from: "Nexus"
The problem with the standard clocks is that they're unprecise (or at least, the standard doesn't require high resolution).

Could you tell more about this? Why do you say it's not precise?
Title: Thor C++ Library – An SFML extension
Post by: Nexus on December 17, 2011, 03:48:25 pm
The precision of std::clock() depends on CLOCKS_PER_SEC, which is usually about 1000, so one can't measure less than one millisecond. It may be good for many use cases, but standard clocks don't offer high-resolution measuring like sf::Clock does.

I have also come across Boost.Chrono (http://www.boost.org/doc/libs/1_47_0/doc/html/chrono.html), it looks more suitable for time measuring than Boost.DateTime. And, it is part of the C++11 standard (http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2661.htm), in the header <chrono> :)
Title: Thor C++ Library – An SFML extension
Post by: Haikarainen on December 17, 2011, 08:15:37 pm
I found a problem.

Was setting up my development environment on my new laptop, downloaded latest SFML2, CMake, SVN and Thor1.1, and after setting up SFML successfully and creating cbp-files to build thor, I get compiler errors.

You're trying to include
Code: [Select]
#include <SFML/Graphics/Transformable.hpp>
#include <SFML/Graphics/ConvexShape.hpp>


probably others as well, these files aren't present on the lastest git of SFML.

Is this known? Should I D/L 1.0 instead?


Thanks
Title: Thor C++ Library – An SFML extension
Post by: Laurent on December 17, 2011, 08:45:16 pm
You need the 'drawables' branch of SFML 2, not the master one.
Title: Thor C++ Library – An SFML extension
Post by: Ceylo on December 18, 2011, 03:01:40 pm
Quote from: "Nexus"
The precision of std::clock() depends on CLOCKS_PER_SEC, which is usually about 1000, so one can't measure less than one millisecond. It may be good for many use cases, but standard clocks don't offer high-resolution measuring like sf::Clock does.

Well.. we'd need to check the value for the other OSs but starting from Mac OS X 10.5 CLOCKS_PER_SEC is defined as 1000000. Thus you can measure up to one microsecond.

Quote from: "Nexus"
I have also come across Boost.Chrono (http://www.boost.org/doc/libs/1_47_0/doc/html/chrono.html), it looks more suitable for time measuring than Boost.DateTime. And, it is part of the C++11 standard (http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2661.htm), in the header <chrono> :)

Boost.Chrono.. humm.. I'll have a look at it. Thanks :)
Title: Thor C++ Library – An SFML extension
Post by: flackez on December 19, 2011, 09:36:00 am
Hello :)

I try to compile thor from svn (r71) with latest sfml from git on archlinux x64 and got this error...

Code: [Select]
Found SFML: /usr/local/include
-- SFML and OpenGL found.
-- Configuring done
-- Generating done
-- Build files have been written to: /local/buildpkg/sfml-thor/src/trunk
[  3%] Building CXX object src/CMakeFiles/thor.dir/Arrow.cpp.o
In file included from /local/buildpkg/sfml-thor/src/trunk/src/Arrow.cpp:26:0:
/local/buildpkg/sfml-thor/src/trunk/include/Thor/Multimedia/Arrow.hpp:35:43: fatal error: SFML/Graphics/Transformable.hpp: No such file or directory
compilation terminated.
make[2]: *** [src/CMakeFiles/thor.dir/Arrow.cpp.o] Error 1
make[1]: *** [src/CMakeFiles/thor.dir/all] Error 2
make: *** [all] Error 2
==> ERROR: A failure occurred in build().
    Aborting...


it seem like no file Transformable.hpp anymore in latest sfml build.  :D

edit: how i miss that above post lol :shock:
Title: Thor C++ Library – An SFML extension
Post by: Laurent on December 19, 2011, 09:39:47 am
The answer is three posts above... ;)
Title: Thor C++ Library – An SFML extension
Post by: excrulon on January 01, 2012, 08:40:31 am
I can't get cmake working with this. I read previous posts in the first few pages of this thread but it didn't help. Also read the tutorial on your site. I've installed SFML, and it's in c:\program files\sfml and my FindSFML.cmake is in C:\Program Files\SFML\cmake\Modules. CMake has two similar variables to set -- SFMLDIR and SFML_DIR. SFML_DIR keeps getting reset to have the value of SFML_DIR-NOTFOUND but SFMLDIR doesn't. I just checked out the latest version of thor from trunk. I get this error no matter what I do:

CMake Warning at CMakeLists.txt:86 (find_package):
  Could not find module FindSFML.cmake or a configuration file for package
  SFML.

  Adjust CMAKE_MODULE_PATH to find FindSFML.cmake or set SFML_DIR to the
  directory containing a CMake configuration file for SFML.  The file will
  have one of the following names:

    SFMLConfig.cmake
    sfml-config.cmake



CMake Error at CMakeLists.txt:92 (message):
  SFML directory not found.  Set SFMLDIR to SFML's top-level path (containing
  "include" and "lib" directories).
Title: Thor C++ Library – An SFML extension
Post by: Laurent on January 01, 2012, 10:21:44 am
You must either copy FindSFML.cmake to <CMake install>/share/cmake-2.8/Modules, or set CMAKE_MODULE_PATH to "C:\Program Files\SFML\cmake\Modules".
Title: Thor C++ Library – An SFML extension
Post by: Nexus on January 08, 2012, 12:02:52 am
On the future of Thor

As Laurent announced to change SFML's naming convention, I have to decide how to continue with Thor. Since Thor and SFML have a similar API (some SFML classes are inherited by Thor or have the same member functions) and the former is officially an extension of the latter, it is standing to reason that I need to adapt the new convention.

I want to exploit this opportunity to improve the general API in Thor and to break some other interfaces. Ideas I have had so far:
Please tell me what you think about those points. I'm also open to other suggestions regarding the API. What do you find unintuitive? Are there things you consider unnecessary/useless? Don't hesitate to post your opinions, unfortunately I recently receive only few feedback from the people using Thor. I'm happy about all inputs, even if you yourself don't use my library.

Concerning the addition of new features, I will wait until a stable code base is established. If you have ideas, please still mention them, this allows me to plan more exactly and to make future integration easier.

Perhaps I am going to release a version 1.1 with the current API, if there are people wishing it.
Title: Thor C++ Library – An SFML extension
Post by: N1ghtly on January 09, 2012, 06:24:16 pm
Does the the latest Thor version work with the latest Git snapshot yet?
Title: Thor C++ Library – An SFML extension
Post by: Nexus on January 09, 2012, 09:15:00 pm
Quote from: "N1ghtly"
Does the the latest Thor version work with the latest Git snapshot yet?
Yes.
Title: Thor C++ Library – An SFML extension
Post by: Orwel on January 10, 2012, 08:25:58 pm
Finnaly, i will stop to postpone to update THOR  :D
Title: Thor C++ Library – An SFML extension
Post by: BlueMagic on January 25, 2012, 03:49:39 pm
Just a small question: How good is the development version of the particle system? Is it still under heavy, constant changes?

BTW, I started using the particle system but I can't seem to find a way to emit particles with an angle offset. I thought SetEmissionAngle() would be the answer, but it doesn't do what I'm saying. Is there any way to do it?
Title: Thor C++ Library – An SFML extension
Post by: Nexus on January 28, 2012, 12:11:34 pm
Quote from: "BlueMagic"
Just a small question: How good is the development version of the particle system? Is it still under heavy, constant changes?
When the SFML API is broken as a result of the new naming convention, I will exploit the opportunity to modify some things. This concerns especially the smart pointer ownership, I am probably not going to use thor::ResourcePtr in the future. Details are explained in my recent post (http://www.sfml-dev.org/forum/viewtopic.php?p=44136#44136). I have also thought about making thor::Emitter more abstract (at the moment, many properties are already predefined, decreasing flexibility for own derivates).

What do you think about this, are you annoyed of ResourcePtr? Should I use shared_ptr instead, or something completely different to hold the textures?

And are there other suggestions about the Particles API? Now is a good moment to announce them ;)


Quote from: "BlueMagic"
BTW, I started using the particle system but I can't seem to find a way to emit particles with an angle offset. I thought SetEmissionAngle() would be the answer, but it doesn't do what I'm saying. Is there any way to do it?
The emission angle determines how "spread" particles are emitted, i.e. if they're just thrown towards a line (0°), in a half circle (180°), etc.

To influence the direction, use thor::DirectionalEmitter::SetVelocity(). This function expects a vector, you can construct one with a specific angle using thor::PolarVector2f, for example:
Code: [Select]
thor::PolarVector2f direction(10.f, 90.f);
// length 10, angle 90°
// i.e. the same as cartesian sf::Vector2f(0.f, 10.f)

thor::DirectionalEmitter::Ptr emitter = ...
emitter->SetVelocity(direction);

And finally, there's also the option to create a custom emitter class by deriving from thor::Emitter.
Title: Thor C++ Library – An SFML extension
Post by: BlueMagic on January 28, 2012, 04:39:38 pm
Quote from: "Nexus"
Quote from: "BlueMagic"
Just a small question: How good is the development version of the particle system? Is it still under heavy, constant changes?
When the SFML API is broken as a result of the new naming convention, I will exploit the opportunity to modify some things. This concerns especially the smart pointer ownership, I am probably not going to use thor::ResourcePtr in the future. Details are explained in my recent post (http://www.sfml-dev.org/forum/viewtopic.php?p=44136#44136). I have also thought about making thor::Emitter more abstract (at the moment, many properties are already predefined, decreasing flexibility for own derivates).

What do you think about this, are you annoyed of ResourcePtr? Should I use shared_ptr instead, or something completely different to hold the textures?
And are there other suggestions about the Particles API? Now is a good moment to announce them ;)
 


As for ResourcePtr, I barely got to use it when trying out the Particle System and all I can say is that it did the trick well. The concept of shared_ptr is also very functional so I guess that would work well too. They're all good since they are improvements from simple pointers anyway. I think it makes sense that you work with ResourcePtr since it's part of your framework. As for suggestions for the API, I've got none (except that I've been meaning to ask how optimal is the way that the particles are rendered, especially when compared to something like vertexarray which I believe would work quite well if I'm not mistaken).

Quote from: "Nexus"

Quote from: "BlueMagic"
BTW, I started using the particle system but I can't seem to find a way to emit particles with an angle offset. I thought SetEmissionAngle() would be the answer, but it doesn't do what I'm saying. Is there any way to do it?
The emission angle determines how "spread" particles are emitted, i.e. if they're just thrown towards a line (0°), in a half circle (180°), etc.

To influence the direction, use thor::DirectionalEmitter::SetVelocity(). This function expects a vector, you can construct one with a specific angle using thor::PolarVector2f, for example:
Code: [Select]
thor::PolarVector2f direction(10.f, 90.f);
// length 10, angle 90°
// i.e. the same as cartesian sf::Vector2f(0.f, 10.f)

thor::DirectionalEmitter::Ptr emitter = ...
emitter->SetVelocity(direction);

And finally, there's also the option to create a custom emitter class by deriving from thor::Emitter.


I think I may have expressed myself badly. I meant that I wanted the texture to appear with an angle offset, as in rotated X degrees (rotation relative to the center of the texture or so), in a way that I can set a random angle so not all the textures appear exactly alike at first. Kind of like the torque modifier but when they are created. I believe the API doesn't give me that option.
Title: Thor C++ Library – An SFML extension
Post by: Nexus on January 28, 2012, 05:26:28 pm
thor::ResourcePtr is currently just a thin wrapper around std::tr1::shared_ptr, so I could directly use the latter (I kept ResourcePtr to allow more functionality, but I currently don't exploit it). And I have already planned to check how well a sf::VertexArray version would perform compared to the direct OpenGL approach, but I guess some options like SetGlowing() won't be available anymore.

The initial rotation of particles is the same as the emission zone's rotation, so you can modifiy it with
Code: [Select]
emitter->GetEmissionZone().SetRotation(rotation);
However, this does also rotate the shape of the zone (which is not relevant for points or circles, but for other shapes). Maybe I should also allow a rotation relative to the zone, same for position and maybe also scale.

The design dates back to a time before sf::Transform and sf::Transformable, I believe reflecting over it in consideration of the new SFML API might make things simpler and more intuitive.
Title: Thor C++ Library – An SFML extension
Post by: BlueMagic on February 06, 2012, 08:07:31 pm
Isn't rotating the shape of the zone kinda slow?
Title: Thor C++ Library – An SFML extension
Post by: Nexus on February 06, 2012, 08:26:11 pm
No, the rotation is just a transform, the actual zone points are not changed.

But the zone orientation and the particle's texture rotation are two different things, I should separate them anyway. Hopefully, I can embed sf::Transform/sf::Transformable in a nice way...
Title: Thor C++ Library – An SFML extension
Post by: dydya-stepa on February 26, 2012, 12:51:04 pm
is it possible to catch events like Shift+P or Alt+F4 with thor event system?
If yes, can you provide a sample how that would look like.
Title: Thor C++ Library – An SFML extension
Post by: Ockonal on February 26, 2012, 02:22:40 pm
Quote from: "dydya-stepa"
is it possible to catch events like Shift+P or Alt+F4 with thor event system?
If yes, can you provide a sample how that would look like.

Shift + P? Why not. But not Alt+F4, this is system binding.
Title: Thor C++ Library – An SFML extension
Post by: Nexus on February 26, 2012, 02:54:10 pm
Shift + P:
Code: [Select]
thor::Action shift = thor::Action(sf::Keyboard::LShift) || thor::Action(sf::Keyboard::RShift);
thor::Action p = thor::Action(sf::Keyboard::P, thor::Action::PressOnce);

thor::ActionMap<std::string> map;
map["shift+p"] = shift && p;

With Alt + F4, you can also try that, but I think SFML also fires a Closed event. So you should rather catch this one.
Title: Thor C++ Library – An SFML extension
Post by: StormWingDelta on March 05, 2012, 12:16:59 am
I thought it would be easier to download the current version than it is.  Why didn't you just zip file the things needed for it? Just wondering since all I see are text files and it is going to take forever to do this one at a time or did I click the wrong link to get to the current version.?
Title: Thor C++ Library – An SFML extension
Post by: dydya-stepa on March 05, 2012, 09:18:54 am
cool, what about double mouse click ?
Title: Thor C++ Library – An SFML extension
Post by: Nexus on March 06, 2012, 06:27:23 pm
Quote from: "StormWingDelta"
I thought it would be easier to download the current version than it is.  Why didn't you just zip file the things needed for it?
The current version is a SVN revision. I would have to zip it everytime I make a commit. But I'm planning to release a new version soon, one that's still compatible with the current SFML API.

But you're probably making it more complicated than necessary, have you tried an SVN client (such as TortoiseSVN on Windows, or also direct commandline svn)?


Quote from: "dydya-stepa"
cool, what about double mouse click ?
You can have a callback that measures time since the mouse was clicked last time. If this time is shorter than a specific threshold, recognize it as double click.
Code: [Select]
struct Callback
{
    void operator() (thor::ActionContext<std::string> c)
    {
        if (*c.Event == sf::Event::MouseButtonPressed)
            return;

        if (clock.Restart() < sf::Seconds(0.5))
            DoubleClick(c);
    }

    sf::Clock clock;
}
Title: Thor C++ Library – An SFML extension
Post by: Hubert on March 06, 2012, 07:12:56 pm
Hello Nexus,

First of all, thank you for that very useful library.

I have a question that I hope you will be able to answer.
It is possible to not throw an exception during the load of a resource if its extention is not supported ?
Let me give you an example. I have a resource loader which try to load all ressources contained in specific folders without any regard concerning the extension.
With the way supplied by the SFML to load an Texture for instance, the non-loadable ressource is just ignore and we get a NULL pointer.
I would like to have the same behavior because currently my application is closed as soon as a non-loadable is found.

(I guess I can specify to load only file whose the extension is contained in an enum for instance, but it would be more interesting if it can be possible with Thor directly).

Another request.
Is that possible you give an minimal code to implement custom ressource to be integrated by Thor ressource manager ?

Finally, I would like to have your opinion about the singleton in the management of resources. Currently I use this pattern that I don't love so much, but I would like to know if you've got another approach.

Thank you for your attention and excuse my english. I don't speak as well as I would like.
Title: Thor C++ Library – An SFML extension
Post by: Nexus on March 06, 2012, 09:06:36 pm
Quote from: "Hubert"
It is possible to not throw an exception during the load of a resource if its extention is not supported ?
Yes, take a look at ResourceManager::SetLoadingFailureStrategy() (http://www.bromeon.ch/libraries/thor/v1.1/doc/classthor_1_1_resource_manager.html).


Quote from: "Hubert"
Another request.
Is that possible you give an minimal code to implement custom ressource to be integrated by Thor ressource manager ?
Sure.
Code: [Select]
// --------------------------------------------------------------------------------------------------------------
// Given: An API for a custom resource, e.g. 3D Mesh

// Custom resource class
class Mesh {};

// Factory function returning a pointer to the resource
Mesh* CreateMesh(std::string filename)
{
return new Mesh(...);
}
Code: [Select]
// --------------------------------------------------------------------------------------------------------------
// Your part: Write a resource key
#include <Thor/Resources.hpp>

// Resource key class, stores information for loading
class FileLoader
{
typedef thor::MovedPtr<Mesh, thor::NoCopy> Ptr;
std::string filename;

public:
FileLoader(std::string filename)
: filename(filename)
{
}

// Function that actually loads the resource
Ptr Load() const
{
return Ptr( CreateMesh(filename) );
}

// Less-than operator as global function to compare two keys
// Here, it just compares the filenames
friend bool operator< (const FileLoader& lhs, const FileLoader& rhs)
{
return lhs.filename < rhs.filename;
}
};

Code: [Select]
// --------------------------------------------------------------------------------------------------------------
// Use it
int main()
{
// Create the resource manager
thor::ResourceManager<Mesh, FileLoader> mgr;

// Acquire resources (note that a and c acquire same resource, since keys are equal)
thor::ResourcePtr<Mesh> a = mgr.Acquire( FileLoader("first.mesh") );
thor::ResourcePtr<Mesh> b = mgr.Acquire( FileLoader("second.mesh") );
thor::ResourcePtr<Mesh> c = mgr.Acquire( FileLoader("first.mesh") );

// That's why the smart pointers a and c refer to only 1 resource, in total 2 resources have been loaded
assert(a == c);

}

Note that I don't really like thor::ResourcePtr, and even less I like thor::MovedPtr. I realized that the current smart pointers in Thor are far too complicated, yet not flexible enough. This is going to be simplified a lot in the near future, see also some posts earlier where I explained all the changes I've planned.


Quote from: "Hubert"
Finally, I would like to have your opinion about the singleton in the management of resources. Currently I use this pattern that I don't love so much, but I would like to know if you've got another approach.
Generally, I'm not a big fan of global variables and singletons, I've already written something about it here (http://www.sfml-dev.org/forum/viewtopic.php?p=34227#34227). If possible, you should prefer keeping thor::ResourceManager in a dedicated class and passing around thor::ResourcePtr instances.
Title: Thor C++ Library – An SFML extension
Post by: Hubert on March 06, 2012, 09:26:34 pm
Hi,

Thank you for your answer !

Shame on me ! I've seen the enum thor::Resources::LoadingFailureStrategy
when I read the tutorial concerning the ressource management.

Actually, I think that I don't see your point about the Singleton. I've the same opinion about this "trick" overused but I don't see how you would implement your solution.
Title: Thor C++ Library – An SFML extension
Post by: Nexus on March 07, 2012, 09:09:33 pm
Quote from: "Hubert"
I've the same opinion about this "trick" overused but I don't see how you would implement your solution.
Well, resources needn't be everywhere. It's enough to have them in the places where the SFML frontend classes (like sf::Sprite, sf::Text, sf::Sound) are used. And normally, these places aren't spread over your whole project, rather in a few classes, which have access to the resources.

In one project, I use two big classes for rendering and playing audio. I pass the ResourceManager to them by reference in their constructor, so they can later acquire texture/sound resources on demand. For this, the access to the resources doesn't have to be global. That's just one example, there are many possibilities.

And I have only tried out very few, that's why I'm still happy about feedback concerning usability.
Title: Thor C++ Library – An SFML extension
Post by: Nexus on March 12, 2012, 05:49:50 pm
As Laurent pushed the new naming convention, I can now begin to adapt Thor.

I plan to release Thor 1.1 compatible to CamelCase functions for people still using the old convention. So if there's anything important for this version, tell me now :)

New features and bigger API changes won't be implemented in 1.1, they're planned for the next version (probably Thor 2.0, as it will break backwards-compatibility in several places). Again, don't hesitate to express ideas, especially concerning the improvement of existing features (new ones can still be added later). Thank you!
Title: Thor C++ Library – An SFML extension
Post by: eXpl0it3r on March 12, 2012, 07:58:17 pm
Quote from: "Nexus"
As Laurent pushed the new naming convention, I can now begin to adapt Thor.

Go for it! :-P
I checked the SVN repository if you've updated Thor already, before I saw this post, just because I know how fast you were at other times. ^^

Quote from: "Nexus"
I plan to release Thor 1.1 compatible to CamelCase functions for people still using the old convention.

Hmmm I don't know if this makes much sense... I mean people using SFML 2.0 now have to change to lowerCase functions anyway, why not just adapt Thor too?

Quote from: "Nexus"
New features and bigger API changes won't be implemented in 1.1, they're planned for the next version.

Is there more info about when it will be comming? And dare you give me the 'soon' answer! :P

Quote from: "Nexus"
What do you think about this, are you annoyed of ResourcePtr? Should I use shared_ptr instead, or something completely different to hold the textures?

Yes I'm kinda annoyed by the ResourcePtr too and I think just using std::shared_ptr should work (or std::tr1::shared_ptr).
Title: Thor C++ Library – An SFML extension
Post by: Nexus on March 13, 2012, 06:01:31 pm
Quote from: "eXpl0it3r"
Hmmm I don't know if this makes much sense... I mean people using SFML 2.0 now have to change to lowerCase functions anyway
That's true, but I thought there might still be a few people who are content with the current convention or have huge projects depending on it which don't pay out to be adapted. Additionally, I'm not sure how much longer the SVN repository will exist, so a finished version might be ok. Having only Thor 1.0 as a release is not so good, as many things have been improved since then.

I reflect about switching to GitHub, however I have quite few experience with Git and mainly use GUI clients. Also, some features of GitHub don't please me (like the issue tracker where one cannot delete tickets, or no edits are marked).


Quote from: "eXpl0it3r"
Is there more info about when it will be comming? And dare you give me the 'soon' answer! :P
If I've found a hoster for version control and installed everything, I can directly begin to commit (or push) changes. The refactoring itself shouldn't take much time (hopefully I can perform it this or next week), it's rather the other changes (split of some features, some API modifications). However they can be gradually adapted.


Quote from: "eXpl0it3r"
Yes I'm kinda annoyed by the ResourcePtr too and I think just using std::shared_ptr should work (or std::tr1::shared_ptr).
Thanks! Finally a user statement :)
Title: Thor C++ Library – An SFML extension
Post by: BlueMagic on March 13, 2012, 07:57:45 pm
If I were to suggest features, they would be (in order of importance to me):

-Z Buffer: Only trouble I see in SFML. As someone who is trying to develop a top down game, I find that the method I'm using to sort depth (which is basically to order the list of entities by y position) is quite slow for a decent number of objects. I'm guessing this would be much faster.

-Initial rotation of the particles: There's that workaround you mentioned about rotating the emission zone, but it would be good to have an initial rotation so we can achieve better 'randomness'.

-I guess simplifying the ptr situation to using just std::shared_ptr would be nice too.

Let me know if you are planning to implement any of this because it would help me immensely!
Title: Thor C++ Library – An SFML extension
Post by: Nexus on March 14, 2012, 11:49:28 am
I have already planned all the three points :)

Concerning the initial particle rotation, I'm not sure how to provide it in the API. Originally, I thought one could unify everything to use transforms (sf::Transform). However, it has some disadvantages: The user cannot extract rotation/scale, and applying a generic transform for a time interval dt is complicated and slow.

So probably, there will just be a DirectionalEmitter::setParticleRotation() method.
Title: Thor C++ Library – An SFML extension
Post by: BlueMagic on March 14, 2012, 03:09:22 pm
Amazing news then!
I'll make sure to follow the development closely. Thanks and let us know if we can help you with feedback or whatever.
Title: Thor C++ Library – An SFML extension
Post by: GamingGod on March 17, 2012, 01:42:58 pm
Greetings.

I'm trying to compile using VS 2010 compiler and CMake, but this bug occurs :
Code: [Select]
CMake Error at CMakeLists.txt:92 (message):
  SFML directory not found.  Set SFMLDIR to SFML's top-level path (containing
  "include" and "lib" directories).


My SFMLDIR in CMake is valid, but when I'm trying to setup valid path for SFML_DIR (then I press generate) it keeps changing to SFML_DIR-NOTFOUND and I can't generate with CMake. Any ideas?

PS. If someone has latest Thor compiled with VS 2010, please upload it somewhere. Thanks in advance.
Title: Thor C++ Library – An SFML extension
Post by: Nexus on March 17, 2012, 02:54:21 pm
Quote from: "GamingGod"
SFML_DIR
You should just change SFMLDIR (without the underscore). It seems like XY_DIR is the usual CMake convention, maybe Laurent should add an underscore to the variable to reduce confusion...

Quote from: "GamingGod"
PS. If someone has latest Thor compiled with VS 2010, please upload it somewhere. Thanks in advance.
Just a few hours ago I released version 1.1, you can find the binaries on my homepage :)
Title: Thor C++ Library – An SFML extension
Post by: Laurent on March 17, 2012, 03:07:51 pm
Where does this SFML_DIR come from?
Title: Thor C++ Library – An SFML extension
Post by: Nexus on March 17, 2012, 03:21:12 pm
Quote from: "Laurent"
Where does this SFML_DIR come from?
Now that I looked again at the advanced variable list, I saw SFML_DIR is not there. But it's not the first time I hear of this variable, probably because CMake error messages contain it, like here (http://www.sfml-dev.org/forum/viewtopic.php?t=4309).
Title: Thor C++ Library – An SFML extension
Post by: Laurent on March 17, 2012, 03:33:11 pm
That's right, I remember now.

If SFML_DIR was defined, CMake would expect it to contain the path to a SFMLConfig.cmake configuration file. Configuration files are another way of handling external libraries; SFML doesn't use it.

So what I should do instead is to rename my own variable to a totally different name, like SFML_ROOT.
Title: Thor C++ Library – An SFML extension
Post by: GamingGod on March 17, 2012, 03:56:52 pm
Thank you good Sirs.

PS. Where I can find the 1.1 binaries? I can see only 1.0.
Title: Thor C++ Library – An SFML extension
Post by: Nexus on March 17, 2012, 04:22:33 pm
Quote from: "Laurent"
So what I should do instead is to rename my own variable to a totally different name, like SFML_ROOT.
Good idea. I think Boost also uses BOOST_ROOT.


[Edit] Please use now this thread (http://www.sfml-dev.org/forum/viewtopic.php?p=48455#48455) to discuss about the next version of Thor.