diff --git a/examples/X11/X11.cpp b/examples/X11/X11.cpp index 877111756..4a6608687 100644 --- a/examples/X11/X11.cpp +++ b/examples/X11/X11.cpp @@ -4,14 +4,14 @@ //////////////////////////////////////////////////////////// #include +#include #define GLAD_GL_IMPLEMENTATION #include -#include #include -#include #include #include +#include //////////////////////////////////////////////////////////// /// Initialize OpenGL states into the specified view @@ -171,31 +171,49 @@ int main() XSetWindowAttributes attributes; attributes.background_pixel = BlackPixel(display, screen); attributes.event_mask = KeyPressMask; - Window window = XCreateWindow(display, RootWindow(display, screen), - 0, 0, 650, 330, 0, + Window window = XCreateWindow(display, + RootWindow(display, screen), + 0, + 0, + 650, + 330, + 0, DefaultDepth(display, screen), InputOutput, DefaultVisual(display, screen), - CWBackPixel | CWEventMask, &attributes); + CWBackPixel | CWEventMask, + &attributes); if (!window) return EXIT_FAILURE; // Set the window's name - XStoreName(display, window , "SFML Window"); + XStoreName(display, window, "SFML Window"); // Let's create the windows which will serve as containers for our SFML views - Window view1 = XCreateWindow(display, window, - 10, 10, 310, 310, 0, + Window view1 = XCreateWindow(display, + window, + 10, + 10, + 310, + 310, + 0, DefaultDepth(display, screen), InputOutput, DefaultVisual(display, screen), - 0, nullptr); - Window view2 = XCreateWindow(display, window, - 330, 10, 310, 310, 0, + 0, + nullptr); + Window view2 = XCreateWindow(display, + window, + 330, + 10, + 310, + 310, + 0, DefaultDepth(display, screen), InputOutput, DefaultVisual(display, screen), - 0, nullptr); + 0, + nullptr); // Show our windows XMapWindow(display, window); diff --git a/examples/android/app/src/main/jni/main.cpp b/examples/android/app/src/main/jni/main.cpp index 0e008dc38..c9ff10488 100644 --- a/examples/android/app/src/main/jni/main.cpp +++ b/examples/android/app/src/main/jni/main.cpp @@ -1,8 +1,8 @@ +#include +#include +#include #include #include -#include -#include -#include // Do we want to showcase direct JNI/NDK interaction? // Undefine this to get real cross-platform code. @@ -11,8 +11,8 @@ #if defined(USE_JNI) // These headers are only needed for direct NDK/JDK interaction -#include #include +#include // Since we want to get the native activity from SFML, we'll have to use an // extra header here: @@ -22,36 +22,36 @@ int vibrate(sf::Time duration) { // First we'll need the native activity handle - ANativeActivity *activity = sf::getNativeActivity(); + ANativeActivity* activity = sf::getNativeActivity(); // Retrieve the JVM and JNI environment - JavaVM* vm = activity->vm; + JavaVM* vm = activity->vm; JNIEnv* env = activity->env; // First, attach this thread to the main thread JavaVMAttachArgs attachargs; attachargs.version = JNI_VERSION_1_6; - attachargs.name = "NativeThread"; - attachargs.group = nullptr; - jint res = vm->AttachCurrentThread(&env, &attachargs); + attachargs.name = "NativeThread"; + attachargs.group = nullptr; + jint res = vm->AttachCurrentThread(&env, &attachargs); if (res == JNI_ERR) return EXIT_FAILURE; // Retrieve class information - jclass natact = env->FindClass("android/app/NativeActivity"); + jclass natact = env->FindClass("android/app/NativeActivity"); jclass context = env->FindClass("android/content/Context"); // Get the value of a constant - jfieldID fid = env->GetStaticFieldID(context, "VIBRATOR_SERVICE", "Ljava/lang/String;"); - jobject svcstr = env->GetStaticObjectField(context, fid); + jfieldID fid = env->GetStaticFieldID(context, "VIBRATOR_SERVICE", "Ljava/lang/String;"); + jobject svcstr = env->GetStaticObjectField(context, fid); // Get the method 'getSystemService' and call it - jmethodID getss = env->GetMethodID(natact, "getSystemService", "(Ljava/lang/String;)Ljava/lang/Object;"); - jobject vib_obj = env->CallObjectMethod(activity->clazz, getss, svcstr); + jmethodID getss = env->GetMethodID(natact, "getSystemService", "(Ljava/lang/String;)Ljava/lang/Object;"); + jobject vib_obj = env->CallObjectMethod(activity->clazz, getss, svcstr); // Get the object's class and retrieve the member name - jclass vib_cls = env->GetObjectClass(vib_obj); + jclass vib_cls = env->GetObjectClass(vib_obj); jmethodID vibrate = env->GetMethodID(vib_cls, "vibrate", "(J)V"); // Determine the timeframe @@ -75,7 +75,7 @@ int vibrate(sf::Time duration) // This is the actual Android example. You don't have to write any platform // specific code, unless you want to use things not directly exposed. // ('vibrate()' in this example; undefine 'USE_JNI' above to disable it) -int main(int argc, char *argv[]) +int main(int argc, char* argv[]) { sf::VideoMode screen(sf::VideoMode::getDesktopMode()); @@ -83,7 +83,7 @@ int main(int argc, char *argv[]) window.setFramerateLimit(30); sf::Texture texture; - if(!texture.loadFromFile("image.png")) + if (!texture.loadFromFile("image.png")) return EXIT_FAILURE; sf::Sprite image(texture); @@ -159,7 +159,8 @@ int main(int argc, char *argv[]) window.draw(text); window.display(); } - else { + else + { sf::sleep(sf::milliseconds(100)); } } diff --git a/examples/cocoa/CocoaAppDelegate.h b/examples/cocoa/CocoaAppDelegate.h index f1d1ce67f..3e22b3580 100644 --- a/examples/cocoa/CocoaAppDelegate.h +++ b/examples/cocoa/CocoaAppDelegate.h @@ -23,9 +23,10 @@ // //////////////////////////////////////////////////////////// -#import #import +#import + /* * NB: We need pointers for C++ objects fields in Obj-C interface ! * The recommended way is to use PIMPL idiom. @@ -36,7 +37,7 @@ struct SFMLmainWindow; -@interface CocoaAppDelegate : NSObject +@interface CocoaAppDelegate : NSObject { @private NSWindow* m_window; @@ -48,17 +49,17 @@ struct SFMLmainWindow; BOOL m_initialized; } -@property (retain) IBOutlet NSWindow* window; +@property (retain) IBOutlet NSWindow* window; -@property (assign) IBOutlet NSView* sfmlView; +@property (assign) IBOutlet NSView* sfmlView; -@property (assign) IBOutlet NSTextField* textField; +@property (assign) IBOutlet NSTextField* textField; --(IBAction)colorChanged:(NSPopUpButton*)sender; --(IBAction)rotationChanged:(NSSlider*)sender; --(IBAction)visibleChanged:(NSButton*)sender; --(IBAction)textChanged:(NSTextField*)sender; --(IBAction)updateText:(NSButton*)sender; +- (IBAction)colorChanged:(NSPopUpButton*)sender; +- (IBAction)rotationChanged:(NSSlider*)sender; +- (IBAction)visibleChanged:(NSButton*)sender; +- (IBAction)textChanged:(NSTextField*)sender; +- (IBAction)updateText:(NSButton*)sender; @end @@ -68,6 +69,6 @@ struct SFMLmainWindow; */ @interface SilentWindow : NSWindow --(void)keyDown:(NSEvent*)theEvent; +- (void)keyDown:(NSEvent*)theEvent; @end diff --git a/examples/cocoa/CocoaAppDelegate.mm b/examples/cocoa/CocoaAppDelegate.mm index 56b329e9a..4b4431e60 100644 --- a/examples/cocoa/CocoaAppDelegate.mm +++ b/examples/cocoa/CocoaAppDelegate.mm @@ -24,27 +24,26 @@ //////////////////////////////////////////////////////////// #import "CocoaAppDelegate.h" + #import "NSString+stdstring.h" // These define are used for converting the color of the NSPopUpButton -#define BLUE @"Blue" -#define GREEN @"Green" -#define RED @"Red" +#define BLUE @"Blue" +#define GREEN @"Green" +#define RED @"Red" #if defined(__APPLE__) - #if defined(__clang__) - #pragma clang diagnostic ignored "-Wdeprecated-declarations" - #elif defined(__GNUC__) - #pragma GCC diagnostic ignored "-Wdeprecated-declarations" - #endif +#if defined(__clang__) +#pragma clang diagnostic ignored "-Wdeprecated-declarations" +#elif defined(__GNUC__) +#pragma GCC diagnostic ignored "-Wdeprecated-declarations" +#endif #endif // Our PIMPL struct SFMLmainWindow { - SFMLmainWindow(sf::WindowHandle win) : - renderWindow(win), - background(sf::Color::Blue) + SFMLmainWindow(sf::WindowHandle win) : renderWindow(win), background(sf::Color::Blue) { std::string resPath = [[[NSBundle mainBundle] resourcePath] tostdstring]; if (!logo.loadFromFile(resPath + "/logo.png")) @@ -54,7 +53,7 @@ struct SFMLmainWindow sprite.setTexture(logo, true); sf::FloatRect rect = sprite.getLocalBounds(); - sf::Vector2f size(rect.width, rect.height); + sf::Vector2f size(rect.width, rect.height); sprite.setOrigin(size / 2.f); sprite.scale({0.3f, 0.3f}); @@ -69,24 +68,24 @@ struct SFMLmainWindow text.setFont(font); } - sf::RenderWindow renderWindow; - sf::Font font; - sf::Text text; - sf::Texture logo; - sf::Sprite sprite; - sf::Color background; + sf::RenderWindow renderWindow; + sf::Font font; + sf::Text text; + sf::Texture logo; + sf::Sprite sprite; + sf::Color background; }; // Private stuff @interface CocoaAppDelegate () -@property (assign) SFMLmainWindow* mainWindow; -@property (retain) NSTimer* renderTimer; -@property (assign) BOOL visible; +@property (assign) SFMLmainWindow* mainWindow; +@property (retain) NSTimer* renderTimer; +@property (assign) BOOL visible; -@property (assign) BOOL initialized; +@property (assign) BOOL initialized; --(void)renderMainWindow:(NSTimer*)aTimer; +- (void)renderMainWindow:(NSTimer*)aTimer; @end @@ -94,15 +93,15 @@ struct SFMLmainWindow // Finally, the implementation @implementation CocoaAppDelegate -@synthesize window = m_window; -@synthesize sfmlView = m_sfmlView; -@synthesize textField = m_textField; +@synthesize window = m_window; +@synthesize sfmlView = m_sfmlView; +@synthesize textField = m_textField; -@synthesize mainWindow = m_mainWindow; -@synthesize renderTimer = m_renderTimer; -@synthesize visible = m_visible; +@synthesize mainWindow = m_mainWindow; +@synthesize renderTimer = m_renderTimer; +@synthesize visible = m_visible; -@synthesize initialized = m_initialized; +@synthesize initialized = m_initialized; - (id)init { @@ -113,7 +112,7 @@ struct SFMLmainWindow return self; } --(void)applicationDidFinishLaunching:(NSNotification*)aNotification +- (void)applicationDidFinishLaunching:(NSNotification*)aNotification { (void)aNotification; @@ -125,15 +124,14 @@ struct SFMLmainWindow self.visible = YES; // Launch the timer to periodically display our stuff into the Cocoa view. - self.renderTimer = [NSTimer timerWithTimeInterval:1.0/60.0 - target:self - selector:@selector(renderMainWindow:) - userInfo:nil - repeats:YES]; - [[NSRunLoop mainRunLoop] addTimer:self.renderTimer - forMode:NSDefaultRunLoopMode]; - [[NSRunLoop mainRunLoop] addTimer:self.renderTimer - forMode:NSEventTrackingRunLoopMode]; + self.renderTimer = [NSTimer + timerWithTimeInterval:1.0 / 60.0 + target:self + selector:@selector(renderMainWindow:) + userInfo:nil + repeats:YES]; + [[NSRunLoop mainRunLoop] addTimer:self.renderTimer forMode:NSDefaultRunLoopMode]; + [[NSRunLoop mainRunLoop] addTimer:self.renderTimer forMode:NSEventTrackingRunLoopMode]; /* * This is really some ugly code but in order to have the timer fired * periodically we need to add it to the two above runloop mode. @@ -147,23 +145,23 @@ struct SFMLmainWindow } } --(void)dealloc +- (void)dealloc { [self.renderTimer invalidate]; self.mainWindow->renderWindow.close(); - self.window = nil; - self.sfmlView = nil; - self.textField = nil; + self.window = nil; + self.sfmlView = nil; + self.textField = nil; delete static_cast(self.mainWindow); - self.mainWindow = 0; - self.renderTimer = nil; + self.mainWindow = 0; + self.renderTimer = nil; [super dealloc]; } --(void)renderMainWindow:(NSTimer*)aTimer +- (void)renderMainWindow:(NSTimer*)aTimer { (void)aTimer; @@ -187,7 +185,7 @@ struct SFMLmainWindow self.mainWindow->renderWindow.display(); } --(IBAction)colorChanged:(NSPopUpButton*)sender +- (IBAction)colorChanged:(NSPopUpButton*)sender { if (self.initialized) { @@ -202,7 +200,7 @@ struct SFMLmainWindow } } --(IBAction)rotationChanged:(NSSlider*)sender +- (IBAction)rotationChanged:(NSSlider*)sender { if (self.initialized) { @@ -211,13 +209,13 @@ struct SFMLmainWindow } } --(IBAction)visibleChanged:(NSButton*)sender +- (IBAction)visibleChanged:(NSButton*)sender { if (self.initialized) self.visible = [sender state] == NSOnState; } --(IBAction)textChanged:(NSTextField*)sender +- (IBAction)textChanged:(NSTextField*)sender { if (self.initialized) self.mainWindow->text.setString([[sender stringValue] tostdwstring]); @@ -235,7 +233,7 @@ struct SFMLmainWindow @implementation SilentWindow --(void)keyDown:(NSEvent*)theEvent +- (void)keyDown:(NSEvent*)theEvent { (void)theEvent; // Do nothing except preventing this alert. diff --git a/examples/cocoa/NSString+stdstring.h b/examples/cocoa/NSString+stdstring.h index d73771ff4..8dab5a1ba 100644 --- a/examples/cocoa/NSString+stdstring.h +++ b/examples/cocoa/NSString+stdstring.h @@ -23,17 +23,17 @@ // //////////////////////////////////////////////////////////// -#import #import +#import @interface NSString (NSString_stdstring) -+(id)stringWithstdstring:(const std::string&)string; ++ (id)stringWithstdstring:(const std::string&)string; -+(id)stringWithstdwstring:(const std::wstring&)string; ++ (id)stringWithstdwstring:(const std::wstring&)string; --(std::string)tostdstring; +- (std::string)tostdstring; --(std::wstring)tostdwstring; +- (std::wstring)tostdwstring; @end diff --git a/examples/cocoa/NSString+stdstring.mm b/examples/cocoa/NSString+stdstring.mm index c4581d9e8..393d82c10 100644 --- a/examples/cocoa/NSString+stdstring.mm +++ b/examples/cocoa/NSString+stdstring.mm @@ -23,38 +23,38 @@ // //////////////////////////////////////////////////////////// -#import "NSString+stdstring.h" #include +#import "NSString+stdstring.h" + @implementation NSString (NSString_stdstring) -+(id)stringWithstdstring:(const std::string&)string ++ (id)stringWithstdstring:(const std::string&)string { std::string utf8; utf8.reserve(string.size() + 1); sf::Utf8::fromAnsi(string.begin(), string.end(), std::back_inserter(utf8)); - NSString* str = [NSString stringWithCString:utf8.c_str() - encoding:NSUTF8StringEncoding]; + NSString* str = [NSString stringWithCString:utf8.c_str() encoding:NSUTF8StringEncoding]; return str; } -+(id)stringWithstdwstring:(const std::wstring&)string ++ (id)stringWithstdwstring:(const std::wstring&)string { const void* data = static_cast(string.data()); - unsigned size = static_cast(string.size() * sizeof(wchar_t)); + unsigned size = static_cast(string.size() * sizeof(wchar_t)); NSString* str = [[[NSString alloc] initWithBytes:data length:size encoding:NSUTF32LittleEndianStringEncoding] autorelease]; return str; } --(std::string)tostdstring +- (std::string)tostdstring { // Not sure about the encoding to use. Using [self UTF8String] doesn't // work for characters like é or à. - const char *cstr = [self cStringUsingEncoding:NSISOLatin1StringEncoding]; + const char* cstr = [self cStringUsingEncoding:NSISOLatin1StringEncoding]; if (cstr != nullptr) return std::string(cstr); @@ -62,7 +62,7 @@ return ""; } --(std::wstring)tostdwstring +- (std::wstring)tostdwstring { // According to Wikipedia, Mac OS X is Little Endian on x86 and x86-64 // https://en.wikipedia.org/wiki/Endianness diff --git a/examples/ftp/Ftp.cpp b/examples/ftp/Ftp.cpp index 977ea7cc4..e317dae15 100644 --- a/examples/ftp/Ftp.cpp +++ b/examples/ftp/Ftp.cpp @@ -3,6 +3,7 @@ // Headers //////////////////////////////////////////////////////////// #include + #include #include #include @@ -12,7 +13,7 @@ /// Print a FTP response into a standard output stream /// //////////////////////////////////////////////////////////// -std::ostream& operator <<(std::ostream& stream, const sf::Ftp::Response& response) +std::ostream& operator<<(std::ostream& stream, const sf::Ftp::Response& response) { return stream << response.getStatus() << response.getMessage(); } @@ -31,12 +32,11 @@ int main() do { std::cout << "Enter the FTP server address: "; - std::cin >> address; - } - while (!address.has_value()); + std::cin >> address; + } while (!address.has_value()); // Connect to the server - sf::Ftp server; + sf::Ftp server; sf::Ftp::Response connectResponse = server.connect(address.value()); std::cout << connectResponse << std::endl; if (!connectResponse.isOk()) @@ -45,9 +45,9 @@ int main() // Ask for user name and password std::string user, password; std::cout << "User name: "; - std::cin >> user; + std::cin >> user; std::cout << "Password: "; - std::cin >> password; + std::cin >> password; // Login to the server sf::Ftp::Response loginResponse = server.login(user, password); @@ -75,7 +75,7 @@ int main() << std::endl; std::cout << "Your choice: "; - std::cin >> choice; + std::cin >> choice; std::cout << std::endl; switch (choice) @@ -93,8 +93,7 @@ int main() { // Print the current server directory sf::Ftp::DirectoryResponse response = server.getWorkingDirectory(); - std::cout << response << '\n' - << "Current directory is " << response.getDirectory() << std::endl; + std::cout << response << '\n' << "Current directory is " << response.getDirectory() << std::endl; break; } @@ -114,7 +113,7 @@ int main() // Change the current directory std::string directory; std::cout << "Choose a directory: "; - std::cin >> directory; + std::cin >> directory; std::cout << server.changeDirectory(directory) << std::endl; break; } @@ -124,7 +123,7 @@ int main() // Create a new directory std::string directory; std::cout << "Name of the directory to create: "; - std::cin >> directory; + std::cin >> directory; std::cout << server.createDirectory(directory) << std::endl; break; } @@ -134,7 +133,7 @@ int main() // Remove an existing directory std::string directory; std::cout << "Name of the directory to remove: "; - std::cin >> directory; + std::cin >> directory; std::cout << server.deleteDirectory(directory) << std::endl; break; } @@ -144,9 +143,9 @@ int main() // Rename a file std::string source, destination; std::cout << "Name of the file to rename: "; - std::cin >> source; + std::cin >> source; std::cout << "New name: "; - std::cin >> destination; + std::cin >> destination; std::cout << server.renameFile(source, destination) << std::endl; break; } @@ -156,7 +155,7 @@ int main() // Remove an existing directory std::string filename; std::cout << "Name of the file to remove: "; - std::cin >> filename; + std::cin >> filename; std::cout << server.deleteFile(filename) << std::endl; break; } @@ -166,9 +165,9 @@ int main() // Download a file from server std::string filename, directory; std::cout << "Filename of the file to download (relative to current directory): "; - std::cin >> filename; + std::cin >> filename; std::cout << "Directory to download the file to: "; - std::cin >> directory; + std::cin >> directory; std::cout << server.download(filename, directory) << std::endl; break; } @@ -178,9 +177,9 @@ int main() // Upload a file to server std::string filename, directory; std::cout << "Path of the file to upload (absolute or relative to working directory): "; - std::cin >> filename; + std::cin >> filename; std::cout << "Directory to upload the file to (relative to current directory): "; - std::cin >> directory; + std::cin >> directory; std::cout << server.upload(filename, directory) << std::endl; break; } @@ -195,8 +194,7 @@ int main() } while (choice != 0); // Disconnect from the server - std::cout << "Disconnecting from server...\n" - << server.disconnect() << '\n'; + std::cout << "Disconnecting from server...\n" << server.disconnect() << '\n'; // Wait until the user presses 'enter' key std::cout << "Press enter to exit..." << std::endl; diff --git a/examples/island/Island.cpp b/examples/island/Island.cpp index 9a0f95ecc..3888fdff9 100644 --- a/examples/island/Island.cpp +++ b/examples/island/Island.cpp @@ -2,13 +2,16 @@ //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// +#include + #define STB_PERLIN_IMPLEMENTATION #include -#include - #include #include +#include +#include +#include #include #include #include @@ -16,62 +19,58 @@ #include #include -#include -#include -#include - namespace { - // Width and height of the application window - const unsigned int windowWidth = 800; - const unsigned int windowHeight = 600; +// Width and height of the application window +const unsigned int windowWidth = 800; +const unsigned int windowHeight = 600; - // Resolution of the generated terrain - const unsigned int resolutionX = 800; - const unsigned int resolutionY = 600; +// Resolution of the generated terrain +const unsigned int resolutionX = 800; +const unsigned int resolutionY = 600; - // Thread pool parameters - const unsigned int threadCount = 4; - const unsigned int blockCount = 32; +// Thread pool parameters +const unsigned int threadCount = 4; +const unsigned int blockCount = 32; - struct WorkItem - { - sf::Vertex* targetBuffer; - unsigned int index; - }; +struct WorkItem +{ + sf::Vertex* targetBuffer; + unsigned int index; +}; - std::deque workQueue; - std::vector threads; - int pendingWorkCount = 0; - bool workPending = true; - bool bufferUploadPending = false; - std::recursive_mutex workQueueMutex; +std::deque workQueue; +std::vector threads; +int pendingWorkCount = 0; +bool workPending = true; +bool bufferUploadPending = false; +std::recursive_mutex workQueueMutex; - struct Setting - { - const char* name; - float* value; - }; +struct Setting +{ + const char* name; + float* value; +}; - // Terrain noise parameters - const int perlinOctaves = 3; +// Terrain noise parameters +const int perlinOctaves = 3; - float perlinFrequency = 7.0f; - float perlinFrequencyBase = 4.0f; +float perlinFrequency = 7.0f; +float perlinFrequencyBase = 4.0f; - // Terrain generation parameters - float heightBase = 0.0f; - float edgeFactor = 0.9f; - float edgeDropoffExponent = 1.5f; +// Terrain generation parameters +float heightBase = 0.0f; +float edgeFactor = 0.9f; +float edgeDropoffExponent = 1.5f; - float snowcapHeight = 0.6f; +float snowcapHeight = 0.6f; - // Terrain lighting parameters - float heightFactor = windowHeight / 2.0f; - float heightFlatten = 3.0f; - float lightFactor = 0.7f; -} +// Terrain lighting parameters +float heightFactor = windowHeight / 2.0f; +float heightFlatten = 3.0f; +float lightFactor = 0.7f; +} // namespace // Forward declarations of the functions we define further down @@ -88,8 +87,7 @@ void generateTerrain(sf::Vertex* vertexBuffer); int main() { // Create the window of the application - sf::RenderWindow window(sf::VideoMode({windowWidth, windowHeight}), "SFML Island", - sf::Style::Titlebar | sf::Style::Close); + sf::RenderWindow window(sf::VideoMode({windowWidth, windowHeight}), "SFML Island", sf::Style::Titlebar | sf::Style::Close); window.setVerticalSyncEnabled(true); sf::Font font; @@ -97,9 +95,9 @@ int main() return EXIT_FAILURE; // Create all of our graphics resources - sf::Text hudText; - sf::Text statusText; - sf::Shader terrainShader; + sf::Text hudText; + sf::Text statusText; + sf::Shader terrainShader; sf::RenderStates terrainStates(&terrainShader); sf::VertexBuffer terrain(sf::Triangles, sf::VertexBuffer::Static); @@ -159,26 +157,25 @@ int main() } // Center the status text - statusText.setPosition({(windowWidth - statusText.getLocalBounds().width) / 2.f, (windowHeight - statusText.getLocalBounds().height) / 2.f}); + statusText.setPosition({(windowWidth - statusText.getLocalBounds().width) / 2.f, + (windowHeight - statusText.getLocalBounds().height) / 2.f}); // Set up an array of pointers to our settings for arrow navigation - constexpr std::array settings = - {{ - {"perlinFrequency", &perlinFrequency}, - {"perlinFrequencyBase", &perlinFrequencyBase}, - {"heightBase", &heightBase}, - {"edgeFactor", &edgeFactor}, - {"edgeDropoffExponent", &edgeDropoffExponent}, - {"snowcapHeight", &snowcapHeight}, - {"heightFactor", &heightFactor}, - {"heightFlatten", &heightFlatten}, - {"lightFactor", &lightFactor} - }}; + constexpr std::array settings = { + {{"perlinFrequency", &perlinFrequency}, + {"perlinFrequencyBase", &perlinFrequencyBase}, + {"heightBase", &heightBase}, + {"edgeFactor", &edgeFactor}, + {"edgeDropoffExponent", &edgeDropoffExponent}, + {"snowcapHeight", &snowcapHeight}, + {"heightFactor", &heightFactor}, + {"heightFlatten", &heightFlatten}, + {"lightFactor", &lightFactor}}}; std::size_t currentSetting = 0; std::ostringstream osstr; - sf::Clock clock; + sf::Clock clock; while (window.isOpen()) { @@ -187,7 +184,7 @@ int main() { // Window closed or escape key pressed: exit if ((event.type == sf::Event::Closed) || - ((event.type == sf::Event::KeyPressed) && (event.key.code == sf::Keyboard::Escape))) + ((event.type == sf::Event::KeyPressed) && (event.key.code == sf::Keyboard::Escape))) { window.close(); break; @@ -198,12 +195,23 @@ int main() { switch (event.key.code) { - case sf::Keyboard::Enter: generateTerrain(terrainStagingBuffer.data()); break; - case sf::Keyboard::Down: currentSetting = (currentSetting + 1) % settings.size(); break; - case sf::Keyboard::Up: currentSetting = (currentSetting + settings.size() - 1) % settings.size(); break; - case sf::Keyboard::Left: *(settings[currentSetting].value) -= 0.1f; break; - case sf::Keyboard::Right: *(settings[currentSetting].value) += 0.1f; break; - default: break; + case sf::Keyboard::Enter: + generateTerrain(terrainStagingBuffer.data()); + break; + case sf::Keyboard::Down: + currentSetting = (currentSetting + 1) % settings.size(); + break; + case sf::Keyboard::Up: + currentSetting = (currentSetting + settings.size() - 1) % settings.size(); + break; + case sf::Keyboard::Left: + *(settings[currentSetting].value) -= 0.1f; + break; + case sf::Keyboard::Right: + *(settings[currentSetting].value) += 0.1f; + break; + default: + break; } } } @@ -245,7 +253,8 @@ int main() << "Use the arrow keys to change the values.\nUse the return key to regenerate the terrain.\n\n"; for (std::size_t i = 0; i < settings.size(); ++i) - osstr << ((i == currentSetting) ? ">> " : " ") << settings[i].name << ": " << *(settings[i].value) << '\n'; + osstr << ((i == currentSetting) ? ">> " : " ") << settings[i].name << ": " + << *(settings[i].value) << '\n'; hudText.setString(osstr.str()); @@ -285,18 +294,20 @@ float getElevation(float x, float y) for (int i = 0; i < perlinOctaves; ++i) { - elevation += stb_perlin_noise3( - x * perlinFrequency * static_cast(std::pow(perlinFrequencyBase, i)), - y * perlinFrequency * static_cast(std::pow(perlinFrequencyBase, i)), - 0, 0, 0, 0 - ) * static_cast(std::pow(perlinFrequencyBase, -i)); + elevation += stb_perlin_noise3(x * perlinFrequency * static_cast(std::pow(perlinFrequencyBase, i)), + y * perlinFrequency * static_cast(std::pow(perlinFrequencyBase, i)), + 0, + 0, + 0, + 0) * + static_cast(std::pow(perlinFrequencyBase, -i)); } elevation = (elevation + 1.f) / 2.f; float distance = 2.0f * std::sqrt(x * x + y * y); - elevation = (elevation + heightBase) * (1.0f - edgeFactor * std::pow(distance, edgeDropoffExponent)); - elevation = std::min(std::max(elevation, 0.0f), 1.0f); + elevation = (elevation + heightBase) * (1.0f - edgeFactor * std::pow(distance, edgeDropoffExponent)); + elevation = std::min(std::max(elevation, 0.0f), 1.0f); return elevation; } @@ -316,11 +327,7 @@ float getMoisture(float x, float y) x = x / resolutionX - 0.5f; y = y / resolutionY - 0.5f; - float moisture = stb_perlin_noise3( - x * 4.f + 0.5f, - y * 4.f + 0.5f, - 0, 0, 0, 0 - ); + float moisture = stb_perlin_noise3(x * 4.f + 0.5f, y * 4.f + 0.5f, 0, 0, 0, 0); return (moisture + 1.f) / 2.f; } @@ -337,21 +344,22 @@ float getMoisture(unsigned int x, unsigned int y) //////////////////////////////////////////////////////////// sf::Color colorFromFloats(float r, float g, float b) { - return sf::Color(static_cast(r), - static_cast(g), - static_cast(b)); + return sf::Color(static_cast(r), static_cast(g), static_cast(b)); } sf::Color getLowlandsTerrainColor(float moisture) { - sf::Color color = - moisture < 0.27f ? colorFromFloats(240, 240, 180) : - moisture < 0.3f ? colorFromFloats(240 - (240 * (moisture - 0.27f) / 0.03f), 240 - (40 * (moisture - 0.27f) / 0.03f), 180 - (180 * (moisture - 0.27f) / 0.03f)) : - moisture < 0.4f ? colorFromFloats(0, 200, 0) : - moisture < 0.48f ? colorFromFloats(0, 200 - (40 * (moisture - 0.4f) / 0.08f), 0) : - moisture < 0.6f ? colorFromFloats(0, 160, 0) : - moisture < 0.7f ? colorFromFloats((34 * (moisture - 0.6f) / 0.1f), 160 - (60 * (moisture - 0.6f) / 0.1f), (34 * (moisture - 0.6f) / 0.1f)) : - colorFromFloats(34, 100, 34); + sf::Color color = moisture < 0.27f ? colorFromFloats(240, 240, 180) + : moisture < 0.3f ? colorFromFloats(240 - (240 * (moisture - 0.27f) / 0.03f), + 240 - (40 * (moisture - 0.27f) / 0.03f), + 180 - (180 * (moisture - 0.27f) / 0.03f)) + : moisture < 0.4f ? colorFromFloats(0, 200, 0) + : moisture < 0.48f ? colorFromFloats(0, 200 - (40 * (moisture - 0.4f) / 0.08f), 0) + : moisture < 0.6f ? colorFromFloats(0, 160, 0) + : moisture < 0.7f ? colorFromFloats((34 * (moisture - 0.6f) / 0.1f), + 160 - (60 * (moisture - 0.6f) / 0.1f), + (34 * (moisture - 0.6f) / 0.1f)) + : colorFromFloats(34, 100, 34); return color; } @@ -366,9 +374,10 @@ sf::Color getHighlandsTerrainColor(float elevation, float moisture) { sf::Color lowlandsColor = getLowlandsTerrainColor(moisture); - sf::Color color = - moisture < 0.6f ? sf::Color(112, 128, 144) : - colorFromFloats(112 + (110 * (moisture - 0.6f) / 0.4f), 128 + (56 * (moisture - 0.6f) / 0.4f), 144 - (9 * (moisture - 0.6f) / 0.4f)); + sf::Color color = moisture < 0.6f ? sf::Color(112, 128, 144) + : colorFromFloats(112 + (110 * (moisture - 0.6f) / 0.4f), + 128 + (56 * (moisture - 0.6f) / 0.4f), + 144 - (9 * (moisture - 0.6f) / 0.4f)); float factor = std::min((elevation - 0.4f) / 0.1f, 1.f); @@ -408,16 +417,21 @@ sf::Color getSnowcapTerrainColor(float elevation, float moisture) //////////////////////////////////////////////////////////// sf::Color getTerrainColor(float elevation, float moisture) { - sf::Color color = - elevation < 0.11f ? sf::Color(0, 0, static_cast(elevation / 0.11f * 74.f + 181.0f)) : - elevation < 0.14f ? sf::Color(static_cast(std::pow((elevation - 0.11f) / 0.03f, 0.3f) * 48.f), static_cast(std::pow((elevation - 0.11f) / 0.03f, 0.3f) * 48.f), 255) : - elevation < 0.16f ? sf::Color(static_cast((elevation - 0.14f) * 128.f / 0.02f + 48.f), static_cast((elevation - 0.14f) * 128.f / 0.02f + 48.f), static_cast(127.0f + (0.16f - elevation) * 128.f / 0.02f)) : - elevation < 0.17f ? sf::Color(240, 230, 140) : - elevation < 0.4f ? getLowlandsTerrainColor(moisture) : - elevation < snowcapHeight ? getHighlandsTerrainColor(elevation, moisture) : - getSnowcapTerrainColor(elevation, moisture); + sf::Color color = elevation < 0.11f ? sf::Color(0, 0, static_cast(elevation / 0.11f * 74.f + 181.0f)) + : elevation < 0.14f + ? sf::Color(static_cast(std::pow((elevation - 0.11f) / 0.03f, 0.3f) * 48.f), + static_cast(std::pow((elevation - 0.11f) / 0.03f, 0.3f) * 48.f), + 255) + : elevation < 0.16f + ? sf::Color(static_cast((elevation - 0.14f) * 128.f / 0.02f + 48.f), + static_cast((elevation - 0.14f) * 128.f / 0.02f + 48.f), + static_cast(127.0f + (0.16f - elevation) * 128.f / 0.02f)) + : elevation < 0.17f ? sf::Color(240, 230, 140) + : elevation < 0.4f ? getLowlandsTerrainColor(moisture) + : elevation < snowcapHeight ? getHighlandsTerrainColor(elevation, moisture) + : getSnowcapTerrainColor(elevation, moisture); - return color; + return color; } @@ -432,11 +446,9 @@ sf::Vector2f computeNormal(float left, float right, float bottom, float top) sf::Vector3f deltaX(1, 0, (std::pow(right, heightFlatten) - std::pow(left, heightFlatten)) * heightFactor); sf::Vector3f deltaY(0, 1, (std::pow(top, heightFlatten) - std::pow(bottom, heightFlatten)) * heightFactor); - sf::Vector3f crossProduct( - deltaX.y * deltaY.z - deltaX.z * deltaY.y, - deltaX.z * deltaY.x - deltaX.x * deltaY.z, - deltaX.x * deltaY.y - deltaX.y * deltaY.x - ); + sf::Vector3f crossProduct(deltaX.y * deltaY.z - deltaX.z * deltaY.y, + deltaX.z * deltaY.x - deltaX.x * deltaY.z, + deltaX.x * deltaY.y - deltaX.y * deltaY.x); // Scale cross product to make z component 1.0f so we can drop it crossProduct /= crossProduct.z; @@ -455,12 +467,12 @@ sf::Vector2f computeNormal(float left, float right, float bottom, float top) void processWorkItem(std::vector& vertices, const WorkItem& workItem) { unsigned int rowBlockSize = (resolutionY / blockCount) + 1; - unsigned int rowStart = rowBlockSize * workItem.index; + unsigned int rowStart = rowBlockSize * workItem.index; if (rowStart >= resolutionY) return; - unsigned int rowEnd = std::min(rowStart + rowBlockSize, resolutionY); + unsigned int rowEnd = std::min(rowStart + rowBlockSize, resolutionY); unsigned int rowCount = rowEnd - rowStart; const float scalingFactorX = static_cast(windowWidth) / static_cast(resolutionX); @@ -483,9 +495,13 @@ void processWorkItem(std::vector& vertices, const WorkItem& workItem } else { - vertices[arrayIndexBase + 0].position = sf::Vector2f(static_cast(x) * scalingFactorX, static_cast(y) * scalingFactorY); - vertices[arrayIndexBase + 0].color = getTerrainColor(getElevation(x, y), getMoisture(x, y)); - vertices[arrayIndexBase + 0].texCoords = computeNormal(getElevation(x - 1, y), getElevation(x + 1, y), getElevation(x, y + 1), getElevation(x, y - 1)); + vertices[arrayIndexBase + 0].position = sf::Vector2f(static_cast(x) * scalingFactorX, + static_cast(y) * scalingFactorY); + vertices[arrayIndexBase + 0].color = getTerrainColor(getElevation(x, y), getMoisture(x, y)); + vertices[arrayIndexBase + 0].texCoords = computeNormal(getElevation(x - 1, y), + getElevation(x + 1, y), + getElevation(x, y + 1), + getElevation(x, y - 1)); } // Bottom left corner (first triangle) @@ -495,15 +511,23 @@ void processWorkItem(std::vector& vertices, const WorkItem& workItem } else { - vertices[arrayIndexBase + 1].position = sf::Vector2f(static_cast(x) * scalingFactorX, static_cast(y + 1) * scalingFactorY); - vertices[arrayIndexBase + 1].color = getTerrainColor(getElevation(x, y + 1), getMoisture(x, y + 1)); - vertices[arrayIndexBase + 1].texCoords = computeNormal(getElevation(x - 1, y + 1), getElevation(x + 1, y + 1), getElevation(x, y + 2), getElevation(x, y)); + vertices[arrayIndexBase + 1].position = sf::Vector2f(static_cast(x) * scalingFactorX, + static_cast(y + 1) * scalingFactorY); + vertices[arrayIndexBase + 1].color = getTerrainColor(getElevation(x, y + 1), getMoisture(x, y + 1)); + vertices[arrayIndexBase + 1].texCoords = computeNormal(getElevation(x - 1, y + 1), + getElevation(x + 1, y + 1), + getElevation(x, y + 2), + getElevation(x, y)); } // Bottom right corner (first triangle) - vertices[arrayIndexBase + 2].position = sf::Vector2f(static_cast(x + 1) * scalingFactorX, static_cast(y + 1) * scalingFactorY); + vertices[arrayIndexBase + 2].position = sf::Vector2f(static_cast(x + 1) * scalingFactorX, + static_cast(y + 1) * scalingFactorY); vertices[arrayIndexBase + 2].color = getTerrainColor(getElevation(x + 1, y + 1), getMoisture(x + 1, y + 1)); - vertices[arrayIndexBase + 2].texCoords = computeNormal(getElevation(x, y + 1), getElevation(x + 2, y + 1), getElevation(x + 1, y + 2), getElevation(x + 1, y)); + vertices[arrayIndexBase + 2].texCoords = computeNormal(getElevation(x, y + 1), + getElevation(x + 2, y + 1), + getElevation(x + 1, y + 2), + getElevation(x + 1, y)); // Top left corner (second triangle) vertices[arrayIndexBase + 3] = vertices[arrayIndexBase + 0]; @@ -518,15 +542,21 @@ void processWorkItem(std::vector& vertices, const WorkItem& workItem } else { - vertices[arrayIndexBase + 5].position = sf::Vector2f(static_cast(x + 1) * scalingFactorX, static_cast(y) * scalingFactorY); - vertices[arrayIndexBase + 5].color = getTerrainColor(getElevation(x + 1, y), getMoisture(x + 1, y)); - vertices[arrayIndexBase + 5].texCoords = computeNormal(getElevation(x, y), getElevation(x + 2, y), getElevation(x + 1, y + 1), getElevation(x + 1, y - 1)); + vertices[arrayIndexBase + 5].position = sf::Vector2f(static_cast(x + 1) * scalingFactorX, + static_cast(y) * scalingFactorY); + vertices[arrayIndexBase + 5].color = getTerrainColor(getElevation(x + 1, y), getMoisture(x + 1, y)); + vertices[arrayIndexBase + 5].texCoords = computeNormal(getElevation(x, y), + getElevation(x + 2, y), + getElevation(x + 1, y + 1), + getElevation(x + 1, y - 1)); } } } // Copy the resulting geometry from our thread-local buffer into the target buffer - std::memcpy(workItem.targetBuffer + (resolutionX * rowStart * 6), vertices.data(), sizeof(sf::Vertex) * resolutionX * rowCount * 6); + std::memcpy(workItem.targetBuffer + (resolutionX * rowStart * 6), + vertices.data(), + sizeof(sf::Vertex) * resolutionX * rowCount * 6); } diff --git a/examples/joystick/Joystick.cpp b/examples/joystick/Joystick.cpp index 154c7a8f5..6d313f08d 100644 --- a/examples/joystick/Joystick.cpp +++ b/examples/joystick/Joystick.cpp @@ -3,6 +3,7 @@ // Headers //////////////////////////////////////////////////////////// #include + #include #include #include @@ -12,72 +13,73 @@ namespace { - struct JoystickObject +struct JoystickObject +{ + sf::Text label; + sf::Text value; +}; + +using Texts = std::unordered_map; +Texts texts; +std::ostringstream sstr; +float threshold = 0.1f; + +// Axes labels in as C strings +constexpr std::array axislabels = {"X", "Y", "Z", "R", "U", "V", "PovX", "PovY"}; + +// Helper to set text entries to a specified value +template +void set(const char* label, const T& value) +{ + sstr.str(""); + sstr << value; + texts[label].value.setString(sstr.str()); +} + +// Update joystick identification +void updateIdentification(unsigned int index) +{ + sstr.str(""); + sstr << "Joystick " << index << ":"; + texts["ID"].label.setString(sstr.str()); + texts["ID"].value.setString(sf::Joystick::getIdentification(index).name); +} + +// Update joystick axes +void updateAxes(unsigned int index) +{ + for (unsigned int j = 0; j < sf::Joystick::AxisCount; ++j) { - sf::Text label; - sf::Text value; - }; - - using Texts = std::unordered_map; - Texts texts; - std::ostringstream sstr; - float threshold = 0.1f; - - // Axes labels in as C strings - constexpr std::array axislabels = {"X", "Y", "Z", "R", "U", "V", "PovX", "PovY"}; - - // Helper to set text entries to a specified value - template - void set(const char* label, const T& value) - { - sstr.str(""); - sstr << value; - texts[label].value.setString(sstr.str()); - } - - // Update joystick identification - void updateIdentification(unsigned int index) - { - sstr.str(""); - sstr << "Joystick " << index << ":"; - texts["ID"].label.setString(sstr.str()); - texts["ID"].value.setString(sf::Joystick::getIdentification(index).name); - } - - // Update joystick axes - void updateAxes(unsigned int index) - { - for (unsigned int j = 0; j < sf::Joystick::AxisCount; ++j) - { - if (sf::Joystick::hasAxis(index, static_cast(j))) - set(axislabels[j], sf::Joystick::getAxisPosition(index, static_cast(j))); - } - } - - // Update joystick buttons - void updateButtons(unsigned int index) - { - for (unsigned int j = 0; j < sf::Joystick::getButtonCount(index); ++j) - { - sstr.str(""); - sstr << "Button " << j; - - set(sstr.str().c_str(), sf::Joystick::isButtonPressed(index, j)); - } - } - - // Helper to update displayed joystick values - void updateValues(unsigned int index) - { - if (sf::Joystick::isConnected(index)) { - // Update the label-value sf::Text objects based on the current joystick state - updateIdentification(index); - updateAxes(index); - updateButtons(index); - } + if (sf::Joystick::hasAxis(index, static_cast(j))) + set(axislabels[j], sf::Joystick::getAxisPosition(index, static_cast(j))); } } +// Update joystick buttons +void updateButtons(unsigned int index) +{ + for (unsigned int j = 0; j < sf::Joystick::getButtonCount(index); ++j) + { + sstr.str(""); + sstr << "Button " << j; + + set(sstr.str().c_str(), sf::Joystick::isButtonPressed(index, j)); + } +} + +// Helper to update displayed joystick values +void updateValues(unsigned int index) +{ + if (sf::Joystick::isConnected(index)) + { + // Update the label-value sf::Text objects based on the current joystick state + updateIdentification(index); + updateAxes(index); + updateButtons(index); + } +} +} // namespace + //////////////////////////////////////////////////////////// /// Entry point of application @@ -135,10 +137,12 @@ int main() sstr << "Button " << i; JoystickObject& object = texts[sstr.str()]; - object.label.setPosition({5.f, 5.f + (static_cast(sf::Joystick::AxisCount + i + 4) * font.getLineSpacing(14))}); + object.label.setPosition( + {5.f, 5.f + (static_cast(sf::Joystick::AxisCount + i + 4) * font.getLineSpacing(14))}); object.label.setString(sstr.str() + ":"); - object.value.setPosition({80.f, 5.f + (static_cast(sf::Joystick::AxisCount + i + 4) * font.getLineSpacing(14))}); + object.value.setPosition( + {80.f, 5.f + (static_cast(sf::Joystick::AxisCount + i + 4) * font.getLineSpacing(14))}); object.value.setString("N/A"); } @@ -170,15 +174,13 @@ int main() { // Window closed or escape key pressed: exit if ((event.type == sf::Event::Closed) || - ((event.type == sf::Event::KeyPressed) && (event.key.code == sf::Keyboard::Escape))) + ((event.type == sf::Event::KeyPressed) && (event.key.code == sf::Keyboard::Escape))) { window.close(); break; } - else if ((event.type == sf::Event::JoystickButtonPressed) || - (event.type == sf::Event::JoystickButtonReleased) || - (event.type == sf::Event::JoystickMoved) || - (event.type == sf::Event::JoystickConnected)) + else if ((event.type == sf::Event::JoystickButtonPressed) || (event.type == sf::Event::JoystickButtonReleased) || + (event.type == sf::Event::JoystickMoved) || (event.type == sf::Event::JoystickConnected)) { // Update displayed joystick values updateValues(event.joystickConnect.joystickId); diff --git a/examples/opengl/OpenGL.cpp b/examples/opengl/OpenGL.cpp index 886aa4a80..fb60382fe 100644 --- a/examples/opengl/OpenGL.cpp +++ b/examples/opengl/OpenGL.cpp @@ -3,9 +3,10 @@ // Headers //////////////////////////////////////////////////////////// #include + #include -#include #include +#include #define GLAD_GL_IMPLEMENTATION #include @@ -42,7 +43,7 @@ int main() { // Request a 24-bits depth buffer when creating the window sf::ContextSettings contextSettings; - contextSettings.depthBits = 24; + contextSettings.depthBits = 24; contextSettings.sRgbCapable = sRgb; // Create the main window @@ -79,7 +80,7 @@ int main() // Attempt to generate a mipmap for our cube texture // We don't check the return value here since // mipmapping is purely optional in this example - (void) texture.generateMipmap(); + (void)texture.generateMipmap(); // Make the window the active window for OpenGL calls if (!window.setActive(true)) @@ -295,11 +296,11 @@ int main() // We get the position of the mouse cursor (or touch), so that we can move the box accordingly sf::Vector2i pos; - #ifdef SFML_SYSTEM_IOS +#ifdef SFML_SYSTEM_IOS pos = sf::Touch::getPosition(0); - #else +#else pos = sf::Mouse::getPosition(window); - #endif +#endif float x = static_cast(pos.x) * 200.f / static_cast(window.getSize().x) - 100.f; float y = -static_cast(pos.y) * 200.f / static_cast(window.getSize().y) + 100.f; diff --git a/examples/shader/Effect.hpp b/examples/shader/Effect.hpp index 9571604f9..1f4c284a4 100644 --- a/examples/shader/Effect.hpp +++ b/examples/shader/Effect.hpp @@ -5,6 +5,7 @@ // Headers //////////////////////////////////////////////////////////// #include + #include #include @@ -15,7 +16,6 @@ class Effect : public sf::Drawable { public: - ~Effect() override { } @@ -57,10 +57,7 @@ public: } protected: - - Effect(const std::string& name) : - m_name(name), - m_isLoaded(false) + Effect(const std::string& name) : m_name(name), m_isLoaded(false) { } @@ -71,16 +68,14 @@ protected: } private: - // Virtual functions to be implemented in derived effects - virtual bool onLoad() = 0; - virtual void onUpdate(float time, float x, float y) = 0; + virtual bool onLoad() = 0; + virtual void onUpdate(float time, float x, float y) = 0; virtual void onDraw(sf::RenderTarget& target, const sf::RenderStates& states) const = 0; private: - std::string m_name; - bool m_isLoaded; + bool m_isLoaded; static const sf::Font* s_font; }; diff --git a/examples/shader/Shader.cpp b/examples/shader/Shader.cpp index 7391b215b..d73060426 100644 --- a/examples/shader/Shader.cpp +++ b/examples/shader/Shader.cpp @@ -2,16 +2,17 @@ //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// -#include "Effect.hpp" #include #include +#include "Effect.hpp" + namespace { - std::random_device rd; - std::mt19937 rng(rd()); -} +std::random_device rd; +std::mt19937 rng(rd()); +} // namespace const sf::Font* Effect::s_font = nullptr; @@ -21,9 +22,7 @@ const sf::Font* Effect::s_font = nullptr; class Pixelate : public Effect { public: - - Pixelate() : - Effect("Pixelate") + Pixelate() : Effect("Pixelate") { } @@ -55,10 +54,9 @@ public: } private: - sf::Texture m_texture; - sf::Sprite m_sprite; - sf::Shader m_shader; + sf::Sprite m_sprite; + sf::Shader m_shader; }; @@ -68,33 +66,32 @@ private: class WaveBlur : public Effect { public: - - WaveBlur() : - Effect("Wave + Blur") + WaveBlur() : Effect("Wave + Blur") { } bool onLoad() override { // Create the text - m_text.setString("Praesent suscipit augue in velit pulvinar hendrerit varius purus aliquam.\n" - "Mauris mi odio, bibendum quis fringilla a, laoreet vel orci. Proin vitae vulputate tortor.\n" - "Praesent cursus ultrices justo, ut feugiat ante vehicula quis.\n" - "Donec fringilla scelerisque mauris et viverra.\n" - "Maecenas adipiscing ornare scelerisque. Nullam at libero elit.\n" - "Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.\n" - "Nullam leo urna, tincidunt id semper eget, ultricies sed mi.\n" - "Morbi mauris massa, commodo id dignissim vel, lobortis et elit.\n" - "Fusce vel libero sed neque scelerisque venenatis.\n" - "Integer mattis tincidunt quam vitae iaculis.\n" - "Vivamus fringilla sem non velit venenatis fermentum.\n" - "Vivamus varius tincidunt nisi id vehicula.\n" - "Integer ullamcorper, enim vitae euismod rutrum, massa nisl semper ipsum,\n" - "vestibulum sodales sem ante in massa.\n" - "Vestibulum in augue non felis convallis viverra.\n" - "Mauris ultricies dolor sed massa convallis sed aliquet augue fringilla.\n" - "Duis erat eros, porta in accumsan in, blandit quis sem.\n" - "In hac habitasse platea dictumst. Etiam fringilla est id odio dapibus sit amet semper dui laoreet.\n"); + m_text.setString( + "Praesent suscipit augue in velit pulvinar hendrerit varius purus aliquam.\n" + "Mauris mi odio, bibendum quis fringilla a, laoreet vel orci. Proin vitae vulputate tortor.\n" + "Praesent cursus ultrices justo, ut feugiat ante vehicula quis.\n" + "Donec fringilla scelerisque mauris et viverra.\n" + "Maecenas adipiscing ornare scelerisque. Nullam at libero elit.\n" + "Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.\n" + "Nullam leo urna, tincidunt id semper eget, ultricies sed mi.\n" + "Morbi mauris massa, commodo id dignissim vel, lobortis et elit.\n" + "Fusce vel libero sed neque scelerisque venenatis.\n" + "Integer mattis tincidunt quam vitae iaculis.\n" + "Vivamus fringilla sem non velit venenatis fermentum.\n" + "Vivamus varius tincidunt nisi id vehicula.\n" + "Integer ullamcorper, enim vitae euismod rutrum, massa nisl semper ipsum,\n" + "vestibulum sodales sem ante in massa.\n" + "Vestibulum in augue non felis convallis viverra.\n" + "Mauris ultricies dolor sed massa convallis sed aliquet augue fringilla.\n" + "Duis erat eros, porta in accumsan in, blandit quis sem.\n" + "In hac habitasse platea dictumst. Etiam fringilla est id odio dapibus sit amet semper dui laoreet.\n"); m_text.setFont(getFont()); m_text.setCharacterSize(22); m_text.setPosition({30.f, 20.f}); @@ -121,8 +118,7 @@ public: } private: - - sf::Text m_text; + sf::Text m_text; sf::Shader m_shader; }; @@ -133,16 +129,14 @@ private: class StormBlink : public Effect { public: - - StormBlink() : - Effect("Storm + Blink") + StormBlink() : Effect("Storm + Blink") { } bool onLoad() override { - std::uniform_real_distribution x_distribution(0, 800); - std::uniform_real_distribution y_distribution(0, 600); + std::uniform_real_distribution x_distribution(0, 800); + std::uniform_real_distribution y_distribution(0, 600); std::uniform_int_distribution color_distribution(0, 255); // Create the points @@ -181,9 +175,8 @@ public: } private: - sf::VertexArray m_points; - sf::Shader m_shader; + sf::Shader m_shader; }; @@ -193,9 +186,7 @@ private: class Edge : public Effect { public: - - Edge() : - Effect("Edge Post-effect") + Edge() : Effect("Edge Post-effect") { } @@ -241,8 +232,10 @@ public: for (std::size_t i = 0; i < m_entities.size(); ++i) { sf::Vector2f position; - position.x = std::cos(0.25f * (time * static_cast(i) + static_cast(m_entities.size() - i))) * 300 + 350; - position.y = std::sin(0.25f * (time * static_cast(m_entities.size() - i) + static_cast(i))) * 200 + 250; + position.x = std::cos(0.25f * (time * static_cast(i) + static_cast(m_entities.size() - i))) * 300 + + 350; + position.y = std::sin(0.25f * (time * static_cast(m_entities.size() - i) + static_cast(i))) * 200 + + 250; m_entities[i].setPosition(position); } @@ -262,13 +255,12 @@ public: } private: - - sf::RenderTexture m_surface; - sf::Texture m_backgroundTexture; - sf::Texture m_entityTexture; - sf::Sprite m_backgroundSprite; + sf::RenderTexture m_surface; + sf::Texture m_backgroundTexture; + sf::Texture m_entityTexture; + sf::Sprite m_backgroundSprite; std::vector m_entities; - sf::Shader m_shader; + sf::Shader m_shader; }; @@ -278,10 +270,7 @@ private: class Geometry : public Effect { public: - - Geometry() : - Effect("Geometry Shader Billboards"), - m_pointCloud(sf::Points, 10000) + Geometry() : Effect("Geometry Shader Billboards"), m_pointCloud(sf::Points, 10000) { } @@ -336,8 +325,8 @@ public: sf::RenderStates statesCopy(states); // Prepare the render state - statesCopy.shader = &m_shader; - statesCopy.texture = &m_logoTexture; + statesCopy.shader = &m_shader; + statesCopy.texture = &m_logoTexture; statesCopy.transform = m_transform; // Draw the point cloud @@ -345,10 +334,9 @@ public: } private: - - sf::Texture m_logoTexture; - sf::Transform m_transform; - sf::Shader m_shader; + sf::Texture m_logoTexture; + sf::Transform m_transform; + sf::Shader m_shader; sf::VertexArray m_pointCloud; }; @@ -362,8 +350,7 @@ private: int main() { // Create the main window - sf::RenderWindow window(sf::VideoMode({800, 600}), "SFML Shader", - sf::Style::Titlebar | sf::Style::Close); + sf::RenderWindow window(sf::VideoMode({800, 600}), "SFML Shader", sf::Style::Titlebar | sf::Style::Close); window.setVerticalSyncEnabled(true); // Load the application font and pass it to the Effect class @@ -373,19 +360,13 @@ int main() Effect::setFont(font); // Create the effects - Pixelate pixelateEffect; - WaveBlur waveBlurEffect; + Pixelate pixelateEffect; + WaveBlur waveBlurEffect; StormBlink stormBlinkEffect; - Edge edgeEffect; - Geometry geometryEffect; + Edge edgeEffect; + Geometry geometryEffect; - const std::array effects{ - &pixelateEffect, - &waveBlurEffect, - &stormBlinkEffect, - &edgeEffect, - &geometryEffect - }; + const std::array effects{&pixelateEffect, &waveBlurEffect, &stormBlinkEffect, &edgeEffect, &geometryEffect}; std::size_t current = 0; @@ -461,9 +442,12 @@ int main() effects[current]->update(clock.getElapsedTime().asSeconds(), x, y); // Clear the window - if(effects[current]->getName() == "Edge Post-effect"){ + if (effects[current]->getName() == "Edge Post-effect") + { window.clear(sf::Color::White); - } else { + } + else + { window.clear(sf::Color(50, 50, 50)); } diff --git a/examples/sockets/Sockets.cpp b/examples/sockets/Sockets.cpp index 6bdd44bc1..7e5d290aa 100644 --- a/examples/sockets/Sockets.cpp +++ b/examples/sockets/Sockets.cpp @@ -2,8 +2,8 @@ //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// -#include #include +#include void runTcpServer(unsigned short port); @@ -26,12 +26,12 @@ int main() // TCP, UDP or connected UDP ? char protocol; std::cout << "Do you want to use TCP (t) or UDP (u)? "; - std::cin >> protocol; + std::cin >> protocol; // Client or server ? char who; std::cout << "Do you want to be a server (s) or a client (c)? "; - std::cin >> who; + std::cin >> who; if (protocol == 't') { diff --git a/examples/sockets/TCP.cpp b/examples/sockets/TCP.cpp index ecea209d0..a3af7f363 100644 --- a/examples/sockets/TCP.cpp +++ b/examples/sockets/TCP.cpp @@ -3,6 +3,7 @@ // Headers //////////////////////////////////////////////////////////// #include + #include #include @@ -35,7 +36,7 @@ void runTcpServer(unsigned short port) std::cout << "Message sent to the client: " << std::quoted(out) << std::endl; // Receive a message back from the client - char in[128]; + char in[128]; std::size_t received; if (socket.receive(in, sizeof(in), received) != sf::Socket::Done) return; @@ -55,9 +56,8 @@ void runTcpClient(unsigned short port) do { std::cout << "Type the address or name of the server to connect to: "; - std::cin >> server; - } - while (!server.has_value()); + std::cin >> server; + } while (!server.has_value()); // Create a socket for communicating with the server sf::TcpSocket socket; @@ -68,7 +68,7 @@ void runTcpClient(unsigned short port) std::cout << "Connected to server " << server.value() << std::endl; // Receive a message from the server - char in[128]; + char in[128]; std::size_t received; if (socket.receive(in, sizeof(in), received) != sf::Socket::Done) return; diff --git a/examples/sockets/UDP.cpp b/examples/sockets/UDP.cpp index 20854eec7..0a29a55c0 100644 --- a/examples/sockets/UDP.cpp +++ b/examples/sockets/UDP.cpp @@ -3,6 +3,7 @@ // Headers //////////////////////////////////////////////////////////// #include + #include #include #include @@ -23,10 +24,10 @@ void runUdpServer(unsigned short port) std::cout << "Server is listening to port " << port << ", waiting for a message... " << std::endl; // Wait for a message - char in[128]; - std::size_t received; + char in[128]; + std::size_t received; std::optional sender; - unsigned short senderPort; + unsigned short senderPort; if (socket.receive(in, sizeof(in), received, sender, senderPort) != sf::Socket::Done) return; std::cout << "Message received from client " << sender.value() << ": " << std::quoted(in) << std::endl; @@ -50,9 +51,8 @@ void runUdpClient(unsigned short port) do { std::cout << "Type the address or name of the server to connect to: "; - std::cin >> server; - } - while (!server.has_value()); + std::cin >> server; + } while (!server.has_value()); // Create a socket for communicating with the server sf::UdpSocket socket; @@ -64,10 +64,10 @@ void runUdpClient(unsigned short port) std::cout << "Message sent to the server: " << std::quoted(out) << std::endl; // Receive an answer from anyone (but most likely from the server) - char in[128]; - std::size_t received; + char in[128]; + std::size_t received; std::optional sender; - unsigned short senderPort; + unsigned short senderPort; if (socket.receive(in, sizeof(in), received, sender, senderPort) != sf::Socket::Done) return; std::cout << "Message received from " << sender.value() << ": " << std::quoted(in) << std::endl; diff --git a/examples/sound/Sound.cpp b/examples/sound/Sound.cpp index 67401cc82..8164b4f0f 100644 --- a/examples/sound/Sound.cpp +++ b/examples/sound/Sound.cpp @@ -3,6 +3,7 @@ // Headers //////////////////////////////////////////////////////////// #include + #include #include @@ -20,9 +21,9 @@ void playSound() // Display sound informations std::cout << "killdeer.wav:" << '\n' - << " " << buffer.getDuration().asSeconds() << " seconds" << '\n' - << " " << buffer.getSampleRate() << " samples / sec" << '\n' - << " " << buffer.getChannelCount() << " channels" << std::endl; + << " " << buffer.getDuration().asSeconds() << " seconds" << '\n' + << " " << buffer.getSampleRate() << " samples / sec" << '\n' + << " " << buffer.getChannelCount() << " channels" << std::endl; // Create a sound instance and play it sf::Sound sound(buffer); @@ -55,9 +56,9 @@ void playMusic(const std::filesystem::path& filename) // Display music informations std::cout << filename << ":" << '\n' - << " " << music.getDuration().asSeconds() << " seconds" << '\n' - << " " << music.getSampleRate() << " samples / sec" << '\n' - << " " << music.getChannelCount() << " channels" << std::endl; + << " " << music.getDuration().asSeconds() << " seconds" << '\n' + << " " << music.getSampleRate() << " samples / sec" << '\n' + << " " << music.getChannelCount() << " channels" << std::endl; // Play it music.play(); diff --git a/examples/sound_capture/SoundCapture.cpp b/examples/sound_capture/SoundCapture.cpp index f994a6f30..4eac48d7e 100644 --- a/examples/sound_capture/SoundCapture.cpp +++ b/examples/sound_capture/SoundCapture.cpp @@ -3,8 +3,9 @@ // Headers //////////////////////////////////////////////////////////// #include -#include + #include +#include //////////////////////////////////////////////////////////// @@ -25,7 +26,7 @@ int main() // Choose the sample rate unsigned int sampleRate; std::cout << "Please choose the sample rate for sound capture (44100 is CD quality): "; - std::cin >> sampleRate; + std::cin >> sampleRate; std::cin.ignore(10000, '\n'); // Wait for user input... @@ -51,14 +52,14 @@ int main() // Display captured sound informations std::cout << "Sound information:" << '\n' - << " " << buffer.getDuration().asSeconds() << " seconds" << '\n' - << " " << buffer.getSampleRate() << " samples / seconds" << '\n' - << " " << buffer.getChannelCount() << " channels" << std::endl; + << " " << buffer.getDuration().asSeconds() << " seconds" << '\n' + << " " << buffer.getSampleRate() << " samples / seconds" << '\n' + << " " << buffer.getChannelCount() << " channels" << std::endl; // Choose what to do with the recorded sound data char choice; std::cout << "What do you want to do with captured sound (p = play, s = save) ? "; - std::cin >> choice; + std::cin >> choice; std::cin.ignore(10000, '\n'); if (choice == 's') diff --git a/examples/tennis/Tennis.cpp b/examples/tennis/Tennis.cpp index c49c3c81a..20939f5e6 100644 --- a/examples/tennis/Tennis.cpp +++ b/examples/tennis/Tennis.cpp @@ -2,8 +2,9 @@ //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// -#include #include +#include + #include #ifdef SFML_SYSTEM_IOS @@ -28,16 +29,17 @@ std::filesystem::path resourcesDir() int main() { std::random_device rd; - std::mt19937 rng(rd()); + std::mt19937 rng(rd()); // Define some constants - const float gameWidth = 800; - const float gameHeight = 600; + const float gameWidth = 800; + const float gameHeight = 600; sf::Vector2f paddleSize(25, 100); - float ballRadius = 10.f; + float ballRadius = 10.f; // Create the window of the application - sf::RenderWindow window(sf::VideoMode({static_cast(gameWidth), static_cast(gameHeight)}, 32), "SFML Tennis", + sf::RenderWindow window(sf::VideoMode({static_cast(gameWidth), static_cast(gameHeight)}, 32), + "SFML Tennis", sf::Style::Titlebar | sf::Style::Close); window.setVerticalSyncEnabled(true); @@ -49,7 +51,7 @@ int main() // Create the SFML logo texture: sf::Texture sfmlLogoTexture; - if(!sfmlLogoTexture.loadFromFile(resourcesDir() / "sfml_logo.png")) + if (!sfmlLogoTexture.loadFromFile(resourcesDir() / "sfml_logo.png")) return EXIT_FAILURE; sf::Sprite sfmlLogo; sfmlLogo.setTexture(sfmlLogoTexture); @@ -91,22 +93,22 @@ int main() pauseMessage.setPosition({170.f, 200.f}); pauseMessage.setFillColor(sf::Color::White); - #ifdef SFML_SYSTEM_IOS +#ifdef SFML_SYSTEM_IOS pauseMessage.setString("Welcome to SFML Tennis!\nTouch the screen to start the game."); - #else +#else pauseMessage.setString("Welcome to SFML Tennis!\n\nPress space to start the game."); - #endif +#endif // Define the paddles properties - sf::Clock AITimer; - const sf::Time AITime = sf::seconds(0.1f); - const float paddleSpeed = 400.f; - float rightPaddleSpeed = 0.f; - const float ballSpeed = 400.f; - sf::Angle ballAngle = sf::degrees(0); // to be changed later + sf::Clock AITimer; + const sf::Time AITime = sf::seconds(0.1f); + const float paddleSpeed = 400.f; + float rightPaddleSpeed = 0.f; + const float ballSpeed = 400.f; + sf::Angle ballAngle = sf::degrees(0); // to be changed later sf::Clock clock; - bool isPlaying = false; + bool isPlaying = false; while (window.isOpen()) { // Handle events @@ -114,7 +116,7 @@ int main() { // Window closed or escape key pressed: exit if ((event.type == sf::Event::Closed) || - ((event.type == sf::Event::KeyPressed) && (event.key.code == sf::Keyboard::Escape))) + ((event.type == sf::Event::KeyPressed) && (event.key.code == sf::Keyboard::Escape))) { window.close(); break; @@ -140,8 +142,7 @@ int main() { // Make sure the ball initial angle is not too much vertical ballAngle = sf::degrees(std::uniform_real_distribution(0, 360)(rng)); - } - while (std::abs(std::cos(ballAngle.asRadians())) < 0.7f); + } while (std::abs(std::cos(ballAngle.asRadians())) < 0.7f); } } @@ -160,20 +161,19 @@ int main() float deltaTime = clock.restart().asSeconds(); // Move the player's paddle - if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up) && - (leftPaddle.getPosition().y - paddleSize.y / 2 > 5.f)) + if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up) && (leftPaddle.getPosition().y - paddleSize.y / 2 > 5.f)) { leftPaddle.move({0.f, -paddleSpeed * deltaTime}); } if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down) && - (leftPaddle.getPosition().y + paddleSize.y / 2 < gameHeight - 5.f)) + (leftPaddle.getPosition().y + paddleSize.y / 2 < gameHeight - 5.f)) { leftPaddle.move({0.f, paddleSpeed * deltaTime}); } if (sf::Touch::isDown(0)) { - sf::Vector2i pos = sf::Touch::getPosition(0); + sf::Vector2i pos = sf::Touch::getPosition(0); sf::Vector2f mappedPos = window.mapPixelToCoords(pos); leftPaddle.setPosition({leftPaddle.getPosition().x, mappedPos.y}); } @@ -200,11 +200,11 @@ int main() // Move the ball ball.move({ballSpeed * deltaTime, ballAngle}); - #ifdef SFML_SYSTEM_IOS +#ifdef SFML_SYSTEM_IOS const std::string inputString = "Touch the screen to restart."; - #else +#else const std::string inputString = "Press space to restart or\nescape to exit."; - #endif +#endif // Check collisions between the ball and the screen if (ball.getPosition().x - ballRadius < 0.f) diff --git a/examples/voip/Client.cpp b/examples/voip/Client.cpp index f718f0f2c..56c376796 100644 --- a/examples/voip/Client.cpp +++ b/examples/voip/Client.cpp @@ -4,6 +4,7 @@ //////////////////////////////////////////////////////////// #include #include + #include @@ -18,7 +19,6 @@ const sf::Uint8 clientEndOfStream = 2; class NetworkRecorder : public sf::SoundRecorder { public: - //////////////////////////////////////////////////////////// /// Constructor /// @@ -26,9 +26,7 @@ public: /// \param port Port of the remote host /// //////////////////////////////////////////////////////////// - NetworkRecorder(const sf::IpAddress& host, unsigned short port) : - m_host(host), - m_port(port) + NetworkRecorder(const sf::IpAddress& host, unsigned short port) : m_host(host), m_port(port) { } @@ -45,7 +43,6 @@ public: } private: - //////////////////////////////////////////////////////////// /// \see SoundRecorder::onStart /// @@ -125,9 +122,8 @@ void doClient(unsigned short port) do { std::cout << "Type address or name of the server to connect to: "; - std::cin >> server; - } - while (!server.has_value()); + std::cin >> server; + } while (!server.has_value()); // Create an instance of our custom recorder NetworkRecorder recorder(server.value(), port); diff --git a/examples/voip/Server.cpp b/examples/voip/Server.cpp index 64baca3d3..3335823f1 100644 --- a/examples/voip/Server.cpp +++ b/examples/voip/Server.cpp @@ -4,6 +4,7 @@ //////////////////////////////////////////////////////////// #include #include + #include #include #include @@ -21,14 +22,11 @@ const sf::Uint8 serverEndOfStream = 2; class NetworkAudioStream : public sf::SoundStream { public: - //////////////////////////////////////////////////////////// /// Default constructor /// //////////////////////////////////////////////////////////// - NetworkAudioStream() : - m_offset (0), - m_hasFinished(false) + NetworkAudioStream() : m_offset(0), m_hasFinished(false) { // Set the sound parameters initialize(1, 44100); @@ -66,7 +64,6 @@ public: } private: - //////////////////////////////////////////////////////////// /// /see SoundStream::OnGetData /// @@ -85,7 +82,8 @@ private: // (don't forget that we run in two separate threads) { std::scoped_lock lock(m_mutex); - m_tempBuffer.assign(m_samples.begin() + static_cast::difference_type>(m_offset), m_samples.end()); + m_tempBuffer.assign(m_samples.begin() + static_cast::difference_type>(m_offset), + m_samples.end()); } // Fill audio data to pass to the stream @@ -133,9 +131,11 @@ private: // (so we protect any operation on it with the mutex) { std::scoped_lock lock(m_mutex); - std::size_t oldSize = m_samples.size(); + std::size_t oldSize = m_samples.size(); m_samples.resize(oldSize + sampleCount); - std::memcpy(&(m_samples[oldSize]), static_cast(packet.getData()) + 1, sampleCount * sizeof(sf::Int16)); + std::memcpy(&(m_samples[oldSize]), + static_cast(packet.getData()) + 1, + sampleCount * sizeof(sf::Int16)); } } else if (id == serverEndOfStream) diff --git a/examples/voip/VoIP.cpp b/examples/voip/VoIP.cpp index 1bf6b0921..2130d608e 100644 --- a/examples/voip/VoIP.cpp +++ b/examples/voip/VoIP.cpp @@ -2,8 +2,8 @@ //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// -#include #include +#include //////////////////////////////////////////////////////////// @@ -28,7 +28,7 @@ int main() // Client or server ? char who; std::cout << "Do you want to be a server ('s') or a client ('c')? "; - std::cin >> who; + std::cin >> who; if (who == 's') { diff --git a/examples/vulkan/Vulkan.cpp b/examples/vulkan/Vulkan.cpp index c04ec2a61..7d66fda2c 100644 --- a/examples/vulkan/Vulkan.cpp +++ b/examples/vulkan/Vulkan.cpp @@ -7,14 +7,14 @@ // Include graphics because we use sf::Image for loading images #include - #include + #include +#include +#include #include #include #include -#include -#include //////////////////////////////////////////////////////////// @@ -22,176 +22,178 @@ //////////////////////////////////////////////////////////// namespace { - using Vec3 = float[3]; - using Matrix = float[4][4]; +using Vec3 = float[3]; +using Matrix = float[4][4]; - // Multiply 2 matrices - void matrixMultiply(Matrix& result, const Matrix& left, const Matrix& right) +// Multiply 2 matrices +void matrixMultiply(Matrix& result, const Matrix& left, const Matrix& right) +{ + Matrix temp; + + for (int i = 0; i < 4; ++i) { - Matrix temp; - - for (int i = 0; i < 4; ++i) - { - for (int j = 0; j < 4; ++j) - temp[i][j] = left[0][j] * right[i][0] + left[1][j] * right[i][1] + left[2][j] * right[i][2] + left[3][j] * right[i][3]; - } - - std::memcpy(result, temp, sizeof(Matrix)); + for (int j = 0; j < 4; ++j) + temp[i][j] = left[0][j] * right[i][0] + left[1][j] * right[i][1] + left[2][j] * right[i][2] + + left[3][j] * right[i][3]; } - // Rotate a matrix around the x-axis - void matrixRotateX(Matrix& result, sf::Angle angle) - { - float rad = angle.asRadians(); - - // clang-format off - Matrix matrix = { - {1.f, 0.f, 0.f, 0.f}, - {0.f, std::cos(rad), std::sin(rad), 0.f}, - {0.f, -std::sin(rad), std::cos(rad), 0.f}, - {0.f, 0.f, 0.f, 1.f} - }; - // clang-format on - - matrixMultiply(result, result, matrix); - } - - // Rotate a matrix around the y-axis - void matrixRotateY(Matrix& result, sf::Angle angle) - { - float rad = angle.asRadians(); - - // clang-format off - Matrix matrix = { - { std::cos(rad), 0.f, std::sin(rad), 0.f}, - { 0.f, 1.f, 0.f, 0.f}, - {-std::sin(rad), 0.f, std::cos(rad), 0.f}, - { 0.f, 0.f, 0.f, 1.f} - }; - // clang-format on - - matrixMultiply(result, result, matrix); - } - - // Rotate a matrix around the z-axis - void matrixRotateZ(Matrix& result, sf::Angle angle) - { - float rad = angle.asRadians(); - - // clang-format off - Matrix matrix = { - { std::cos(rad), std::sin(rad), 0.f, 0.f}, - {-std::sin(rad), std::cos(rad), 0.f, 0.f}, - { 0.f, 0.f, 1.f, 0.f}, - { 0.f, 0.f, 0.f, 1.f} - }; - // clang-format on - - matrixMultiply(result, result, matrix); - } - - // Construct a lookat view matrix - void matrixLookAt(Matrix& result, const Vec3& eye, const Vec3& center, const Vec3& up) - { - // Forward-looking vector - // clang-format off - Vec3 forward = { - center[0] - eye[0], - center[1] - eye[1], - center[2] - eye[2] - }; - // clang-format on - - // Normalize - float factor = 1.0f / std::sqrt(forward[0] * forward[0] + forward[1] * forward[1] + forward[2] * forward[2]); - - for(float& f : forward) - f *= factor; - - // Side vector (Forward cross product Up) - // clang-format off - Vec3 side = { - forward[1] * up[2] - forward[2] * up[1], - forward[2] * up[0] - forward[0] * up[2], - forward[0] * up[1] - forward[1] * up[0] - }; - // clang-format on - - // Normalize - factor = 1.0f / std::sqrt(side[0] * side[0] + side[1] * side[1] + side[2] * side[2]); - - for(float& f : side) - f *= factor; - - result[0][0] = side[0]; - result[0][1] = side[1] * forward[2] - side[2] * forward[1]; - result[0][2] = -forward[0]; - result[0][3] = 0.f; - - result[1][0] = side[1]; - result[1][1] = side[2] * forward[0] - side[0] * forward[2]; - result[1][2] = -forward[1]; - result[1][3] = 0.f; - - result[2][0] = side[2]; - result[2][1] = side[0] * forward[1] - side[1] * forward[0]; - result[2][2] = -forward[2]; - result[2][3] = 0.f; - - result[3][0] = (-eye[0]) * result[0][0] + (-eye[1]) * result[1][0] + (-eye[2]) * result[2][0]; - result[3][1] = (-eye[0]) * result[0][1] + (-eye[1]) * result[1][1] + (-eye[2]) * result[2][1]; - result[3][2] = (-eye[0]) * result[0][2] + (-eye[1]) * result[1][2] + (-eye[2]) * result[2][2]; - result[3][3] = (-eye[0]) * result[0][3] + (-eye[1]) * result[1][3] + (-eye[2]) * result[2][3] + 1.0f; - } - - // Construct a perspective projection matrix - void matrixPerspective(Matrix& result, sf::Angle fov, float aspect, float nearPlane, float farPlane) - { - const float a = 1.f / std::tan(fov.asRadians() / 2.f); - - result[0][0] = a / aspect; - result[0][1] = 0.f; - result[0][2] = 0.f; - result[0][3] = 0.f; - - result[1][0] = 0.f; - result[1][1] = -a; - result[1][2] = 0.f; - result[1][3] = 0.f; - - result[2][0] = 0.f; - result[2][1] = 0.f; - result[2][2] = -((farPlane + nearPlane) / (farPlane - nearPlane)); - result[2][3] = -1.f; - - result[3][0] = 0.f; - result[3][1] = 0.f; - result[3][2] = -((2.f * farPlane * nearPlane) / (farPlane - nearPlane)); - result[3][3] = 0.f; - } - - // Clamp a value between low and high values - template - T clamp(T value, T low, T high) - { - return (value <= low) ? low : ((value >= high) ? high : value); - } - - // Helper function we pass to GLAD to load Vulkan functions via SFML - GLADapiproc getVulkanFunction(const char* name) - { - return sf::Vulkan::getFunction(name); - } - - // Debug we pass to Vulkan to call when it detects warnings or errors - VKAPI_ATTR VkBool32 VKAPI_CALL debugCallback(VkDebugReportFlagsEXT, VkDebugReportObjectTypeEXT, uint64_t, size_t, int32_t, const char*, const char* pMessage, void*) - { - std::cerr << pMessage << std::endl; - - return VK_FALSE; - } + std::memcpy(result, temp, sizeof(Matrix)); } +// Rotate a matrix around the x-axis +void matrixRotateX(Matrix& result, sf::Angle angle) +{ + float rad = angle.asRadians(); + + // clang-format off + Matrix matrix = { + {1.f, 0.f, 0.f, 0.f}, + {0.f, std::cos(rad), std::sin(rad), 0.f}, + {0.f, -std::sin(rad), std::cos(rad), 0.f}, + {0.f, 0.f, 0.f, 1.f} + }; + // clang-format on + + matrixMultiply(result, result, matrix); +} + +// Rotate a matrix around the y-axis +void matrixRotateY(Matrix& result, sf::Angle angle) +{ + float rad = angle.asRadians(); + + // clang-format off + Matrix matrix = { + { std::cos(rad), 0.f, std::sin(rad), 0.f}, + { 0.f, 1.f, 0.f, 0.f}, + {-std::sin(rad), 0.f, std::cos(rad), 0.f}, + { 0.f, 0.f, 0.f, 1.f} + }; + // clang-format on + + matrixMultiply(result, result, matrix); +} + +// Rotate a matrix around the z-axis +void matrixRotateZ(Matrix& result, sf::Angle angle) +{ + float rad = angle.asRadians(); + + // clang-format off + Matrix matrix = { + { std::cos(rad), std::sin(rad), 0.f, 0.f}, + {-std::sin(rad), std::cos(rad), 0.f, 0.f}, + { 0.f, 0.f, 1.f, 0.f}, + { 0.f, 0.f, 0.f, 1.f} + }; + // clang-format on + + matrixMultiply(result, result, matrix); +} + +// Construct a lookat view matrix +void matrixLookAt(Matrix& result, const Vec3& eye, const Vec3& center, const Vec3& up) +{ + // Forward-looking vector + // clang-format off + Vec3 forward = { + center[0] - eye[0], + center[1] - eye[1], + center[2] - eye[2] + }; + // clang-format on + + // Normalize + float factor = 1.0f / std::sqrt(forward[0] * forward[0] + forward[1] * forward[1] + forward[2] * forward[2]); + + for (float& f : forward) + f *= factor; + + // Side vector (Forward cross product Up) + // clang-format off + Vec3 side = { + forward[1] * up[2] - forward[2] * up[1], + forward[2] * up[0] - forward[0] * up[2], + forward[0] * up[1] - forward[1] * up[0] + }; + // clang-format on + + // Normalize + factor = 1.0f / std::sqrt(side[0] * side[0] + side[1] * side[1] + side[2] * side[2]); + + for (float& f : side) + f *= factor; + + result[0][0] = side[0]; + result[0][1] = side[1] * forward[2] - side[2] * forward[1]; + result[0][2] = -forward[0]; + result[0][3] = 0.f; + + result[1][0] = side[1]; + result[1][1] = side[2] * forward[0] - side[0] * forward[2]; + result[1][2] = -forward[1]; + result[1][3] = 0.f; + + result[2][0] = side[2]; + result[2][1] = side[0] * forward[1] - side[1] * forward[0]; + result[2][2] = -forward[2]; + result[2][3] = 0.f; + + result[3][0] = (-eye[0]) * result[0][0] + (-eye[1]) * result[1][0] + (-eye[2]) * result[2][0]; + result[3][1] = (-eye[0]) * result[0][1] + (-eye[1]) * result[1][1] + (-eye[2]) * result[2][1]; + result[3][2] = (-eye[0]) * result[0][2] + (-eye[1]) * result[1][2] + (-eye[2]) * result[2][2]; + result[3][3] = (-eye[0]) * result[0][3] + (-eye[1]) * result[1][3] + (-eye[2]) * result[2][3] + 1.0f; +} + +// Construct a perspective projection matrix +void matrixPerspective(Matrix& result, sf::Angle fov, float aspect, float nearPlane, float farPlane) +{ + const float a = 1.f / std::tan(fov.asRadians() / 2.f); + + result[0][0] = a / aspect; + result[0][1] = 0.f; + result[0][2] = 0.f; + result[0][3] = 0.f; + + result[1][0] = 0.f; + result[1][1] = -a; + result[1][2] = 0.f; + result[1][3] = 0.f; + + result[2][0] = 0.f; + result[2][1] = 0.f; + result[2][2] = -((farPlane + nearPlane) / (farPlane - nearPlane)); + result[2][3] = -1.f; + + result[3][0] = 0.f; + result[3][1] = 0.f; + result[3][2] = -((2.f * farPlane * nearPlane) / (farPlane - nearPlane)); + result[3][3] = 0.f; +} + +// Clamp a value between low and high values +template +T clamp(T value, T low, T high) +{ + return (value <= low) ? low : ((value >= high) ? high : value); +} + +// Helper function we pass to GLAD to load Vulkan functions via SFML +GLADapiproc getVulkanFunction(const char* name) +{ + return sf::Vulkan::getFunction(name); +} + +// Debug we pass to Vulkan to call when it detects warnings or errors +VKAPI_ATTR VkBool32 VKAPI_CALL + debugCallback(VkDebugReportFlagsEXT, VkDebugReportObjectTypeEXT, uint64_t, size_t, int32_t, const char*, const char* pMessage, void*) +{ + std::cerr << pMessage << std::endl; + + return VK_FALSE; +} +} // namespace + //////////////////////////////////////////////////////////// // VulkanExample class @@ -238,34 +240,62 @@ public: descriptorPool(0) { // Vulkan setup procedure - if (vulkanAvailable) setupInstance(); - if (vulkanAvailable) setupDebugReportCallback(); - if (vulkanAvailable) setupSurface(); - if (vulkanAvailable) setupPhysicalDevice(); - if (vulkanAvailable) setupLogicalDevice(); - if (vulkanAvailable) setupSwapchain(); - if (vulkanAvailable) setupSwapchainImages(); - if (vulkanAvailable) setupShaders(); - if (vulkanAvailable) setupRenderpass(); - if (vulkanAvailable) setupDescriptorSetLayout(); - if (vulkanAvailable) setupPipelineLayout(); - if (vulkanAvailable) setupPipeline(); - if (vulkanAvailable) setupCommandPool(); - if (vulkanAvailable) setupVertexBuffer(); - if (vulkanAvailable) setupIndexBuffer(); - if (vulkanAvailable) setupUniformBuffers(); - if (vulkanAvailable) setupDepthImage(); - if (vulkanAvailable) setupDepthImageView(); - if (vulkanAvailable) setupTextureImage(); - if (vulkanAvailable) setupTextureImageView(); - if (vulkanAvailable) setupTextureSampler(); - if (vulkanAvailable) setupFramebuffers(); - if (vulkanAvailable) setupDescriptorPool(); - if (vulkanAvailable) setupDescriptorSets(); - if (vulkanAvailable) setupCommandBuffers(); - if (vulkanAvailable) setupDraw(); - if (vulkanAvailable) setupSemaphores(); - if (vulkanAvailable) setupFences(); + if (vulkanAvailable) + setupInstance(); + if (vulkanAvailable) + setupDebugReportCallback(); + if (vulkanAvailable) + setupSurface(); + if (vulkanAvailable) + setupPhysicalDevice(); + if (vulkanAvailable) + setupLogicalDevice(); + if (vulkanAvailable) + setupSwapchain(); + if (vulkanAvailable) + setupSwapchainImages(); + if (vulkanAvailable) + setupShaders(); + if (vulkanAvailable) + setupRenderpass(); + if (vulkanAvailable) + setupDescriptorSetLayout(); + if (vulkanAvailable) + setupPipelineLayout(); + if (vulkanAvailable) + setupPipeline(); + if (vulkanAvailable) + setupCommandPool(); + if (vulkanAvailable) + setupVertexBuffer(); + if (vulkanAvailable) + setupIndexBuffer(); + if (vulkanAvailable) + setupUniformBuffers(); + if (vulkanAvailable) + setupDepthImage(); + if (vulkanAvailable) + setupDepthImageView(); + if (vulkanAvailable) + setupTextureImage(); + if (vulkanAvailable) + setupTextureImageView(); + if (vulkanAvailable) + setupTextureSampler(); + if (vulkanAvailable) + setupFramebuffers(); + if (vulkanAvailable) + setupDescriptorPool(); + if (vulkanAvailable) + setupDescriptorSets(); + if (vulkanAvailable) + setupCommandBuffers(); + if (vulkanAvailable) + setupDraw(); + if (vulkanAvailable) + setupSemaphores(); + if (vulkanAvailable) + setupFences(); // If something went wrong, notify the user by setting the window title if (!vulkanAvailable) @@ -405,16 +435,26 @@ public: cleanupSwapchain(); // Swapchain setup procedure - if (vulkanAvailable) setupSwapchain(); - if (vulkanAvailable) setupSwapchainImages(); - if (vulkanAvailable) setupPipelineLayout(); - if (vulkanAvailable) setupRenderpass(); - if (vulkanAvailable) setupPipeline(); - if (vulkanAvailable) setupDepthImage(); - if (vulkanAvailable) setupDepthImageView(); - if (vulkanAvailable) setupFramebuffers(); - if (vulkanAvailable) setupCommandBuffers(); - if (vulkanAvailable) setupDraw(); + if (vulkanAvailable) + setupSwapchain(); + if (vulkanAvailable) + setupSwapchainImages(); + if (vulkanAvailable) + setupPipelineLayout(); + if (vulkanAvailable) + setupRenderpass(); + if (vulkanAvailable) + setupPipeline(); + if (vulkanAvailable) + setupDepthImage(); + if (vulkanAvailable) + setupDepthImageView(); + if (vulkanAvailable) + setupFramebuffers(); + if (vulkanAvailable) + setupCommandBuffers(); + if (vulkanAvailable) + setupDraw(); } // Setup Vulkan instance @@ -479,20 +519,20 @@ public: requiredExtentions.push_back(VK_EXT_DEBUG_REPORT_EXTENSION_NAME); // Register our application information - VkApplicationInfo applicationInfo = VkApplicationInfo(); - applicationInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO; - applicationInfo.pApplicationName = "SFML Vulkan Test"; + VkApplicationInfo applicationInfo = VkApplicationInfo(); + applicationInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO; + applicationInfo.pApplicationName = "SFML Vulkan Test"; applicationInfo.applicationVersion = VK_MAKE_VERSION(1, 0, 0); - applicationInfo.pEngineName = "SFML Vulkan Test Engine"; - applicationInfo.engineVersion = VK_MAKE_VERSION(1, 0, 0); - applicationInfo.apiVersion = VK_API_VERSION_1_0; + applicationInfo.pEngineName = "SFML Vulkan Test Engine"; + applicationInfo.engineVersion = VK_MAKE_VERSION(1, 0, 0); + applicationInfo.apiVersion = VK_API_VERSION_1_0; - VkInstanceCreateInfo instanceCreateInfo = VkInstanceCreateInfo(); - instanceCreateInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO; - instanceCreateInfo.pApplicationInfo = &applicationInfo; - instanceCreateInfo.enabledLayerCount = static_cast(validationLayers.size()); - instanceCreateInfo.ppEnabledLayerNames = validationLayers.data(); - instanceCreateInfo.enabledExtensionCount = static_cast(requiredExtentions.size()); + VkInstanceCreateInfo instanceCreateInfo = VkInstanceCreateInfo(); + instanceCreateInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO; + instanceCreateInfo.pApplicationInfo = &applicationInfo; + instanceCreateInfo.enabledLayerCount = static_cast(validationLayers.size()); + instanceCreateInfo.ppEnabledLayerNames = validationLayers.data(); + instanceCreateInfo.enabledExtensionCount = static_cast(requiredExtentions.size()); instanceCreateInfo.ppEnabledExtensionNames = requiredExtentions.data(); // Try to create a Vulkan instance with debug report enabled @@ -503,7 +543,7 @@ public: { requiredExtentions.pop_back(); - instanceCreateInfo.enabledExtensionCount = static_cast(requiredExtentions.size()); + instanceCreateInfo.enabledExtensionCount = static_cast(requiredExtentions.size()); instanceCreateInfo.ppEnabledExtensionNames = requiredExtentions.data(); result = vkCreateInstance(&instanceCreateInfo, 0, &instance); @@ -530,7 +570,8 @@ public: // Register for warnings and errors VkDebugReportCallbackCreateInfoEXT debugReportCallbackCreateInfo = VkDebugReportCallbackCreateInfoEXT(); debugReportCallbackCreateInfo.sType = VK_STRUCTURE_TYPE_DEBUG_REPORT_CALLBACK_CREATE_INFO_EXT; - debugReportCallbackCreateInfo.flags = VK_DEBUG_REPORT_WARNING_BIT_EXT | VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT | VK_DEBUG_REPORT_ERROR_BIT_EXT; + debugReportCallbackCreateInfo.flags = VK_DEBUG_REPORT_WARNING_BIT_EXT | + VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT | VK_DEBUG_REPORT_ERROR_BIT_EXT; debugReportCallbackCreateInfo.pfnCallback = debugCallback; // Create the debug callback @@ -639,21 +680,24 @@ public: vkGetPhysicalDeviceFormatProperties(gpu, VK_FORMAT_D24_UNORM_S8_UINT, &formatProperties); - if (formatProperties.optimalTilingFeatures & VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT) { + if (formatProperties.optimalTilingFeatures & VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT) + { depthFormat = VK_FORMAT_D24_UNORM_S8_UINT; } else { vkGetPhysicalDeviceFormatProperties(gpu, VK_FORMAT_D32_SFLOAT_S8_UINT, &formatProperties); - if (formatProperties.optimalTilingFeatures & VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT) { + if (formatProperties.optimalTilingFeatures & VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT) + { depthFormat = VK_FORMAT_D32_SFLOAT_S8_UINT; } else { vkGetPhysicalDeviceFormatProperties(gpu, VK_FORMAT_D32_SFLOAT, &formatProperties); - if (formatProperties.optimalTilingFeatures & VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT) { + if (formatProperties.optimalTilingFeatures & VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT) + { depthFormat = VK_FORMAT_D32_SFLOAT; } else @@ -701,25 +745,25 @@ public: float queuePriority = 1.0f; VkDeviceQueueCreateInfo deviceQueueCreateInfo = VkDeviceQueueCreateInfo(); - deviceQueueCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO; - deviceQueueCreateInfo.queueCount = 1; - deviceQueueCreateInfo.queueFamilyIndex = static_cast(queueFamilyIndex); - deviceQueueCreateInfo.pQueuePriorities = &queuePriority; + deviceQueueCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO; + deviceQueueCreateInfo.queueCount = 1; + deviceQueueCreateInfo.queueFamilyIndex = static_cast(queueFamilyIndex); + deviceQueueCreateInfo.pQueuePriorities = &queuePriority; // Enable the swapchain extension - const char* extentions[1] = { VK_KHR_SWAPCHAIN_EXTENSION_NAME }; + const char* extentions[1] = {VK_KHR_SWAPCHAIN_EXTENSION_NAME}; // Enable anisotropic filtering VkPhysicalDeviceFeatures physicalDeviceFeatures = VkPhysicalDeviceFeatures(); - physicalDeviceFeatures.samplerAnisotropy = VK_TRUE; + physicalDeviceFeatures.samplerAnisotropy = VK_TRUE; - VkDeviceCreateInfo deviceCreateInfo = VkDeviceCreateInfo(); - deviceCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO; - deviceCreateInfo.enabledExtensionCount = 1; + VkDeviceCreateInfo deviceCreateInfo = VkDeviceCreateInfo(); + deviceCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO; + deviceCreateInfo.enabledExtensionCount = 1; deviceCreateInfo.ppEnabledExtensionNames = extentions; - deviceCreateInfo.queueCreateInfoCount = 1; - deviceCreateInfo.pQueueCreateInfos = &deviceQueueCreateInfo; - deviceCreateInfo.pEnabledFeatures = &physicalDeviceFeatures; + deviceCreateInfo.queueCreateInfoCount = 1; + deviceCreateInfo.pQueueCreateInfos = &deviceQueueCreateInfo; + deviceCreateInfo.pEnabledFeatures = &physicalDeviceFeatures; // Create our logical device if (vkCreateDevice(gpu, &deviceCreateInfo, 0, &device) != VK_SUCCESS) @@ -756,16 +800,17 @@ public: if ((surfaceFormats.size() == 1) && (surfaceFormats[0].format == VK_FORMAT_UNDEFINED)) { - swapchainFormat.format = VK_FORMAT_B8G8R8A8_UNORM; + swapchainFormat.format = VK_FORMAT_B8G8R8A8_UNORM; swapchainFormat.colorSpace = VK_COLOR_SPACE_SRGB_NONLINEAR_KHR; } else if (!surfaceFormats.empty()) { for (VkSurfaceFormatKHR& surfaceFormat : surfaceFormats) { - if ((surfaceFormat.format == VK_FORMAT_B8G8R8A8_UNORM) && (surfaceFormat.colorSpace == VK_COLOR_SPACE_SRGB_NONLINEAR_KHR)) + if ((surfaceFormat.format == VK_FORMAT_B8G8R8A8_UNORM) && + (surfaceFormat.colorSpace == VK_COLOR_SPACE_SRGB_NONLINEAR_KHR)) { - swapchainFormat.format = VK_FORMAT_B8G8R8A8_UNORM; + swapchainFormat.format = VK_FORMAT_B8G8R8A8_UNORM; swapchainFormat.colorSpace = VK_COLOR_SPACE_SRGB_NONLINEAR_KHR; break; @@ -819,26 +864,30 @@ public: return; } - swapchainExtent.width = clamp(window.getSize().x, surfaceCapabilities.minImageExtent.width, surfaceCapabilities.maxImageExtent.width); - swapchainExtent.height = clamp(window.getSize().y, surfaceCapabilities.minImageExtent.height, surfaceCapabilities.maxImageExtent.height); + swapchainExtent.width = clamp(window.getSize().x, + surfaceCapabilities.minImageExtent.width, + surfaceCapabilities.maxImageExtent.width); + swapchainExtent.height = clamp(window.getSize().y, + surfaceCapabilities.minImageExtent.height, + surfaceCapabilities.maxImageExtent.height); auto imageCount = clamp(2, surfaceCapabilities.minImageCount, surfaceCapabilities.maxImageCount); VkSwapchainCreateInfoKHR swapchainCreateInfo = VkSwapchainCreateInfoKHR(); - swapchainCreateInfo.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR; - swapchainCreateInfo.surface = surface; - swapchainCreateInfo.minImageCount = imageCount; - swapchainCreateInfo.imageFormat = swapchainFormat.format; - swapchainCreateInfo.imageColorSpace = swapchainFormat.colorSpace; - swapchainCreateInfo.imageExtent = swapchainExtent; - swapchainCreateInfo.imageArrayLayers = 1; - swapchainCreateInfo.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; - swapchainCreateInfo.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE; - swapchainCreateInfo.preTransform = surfaceCapabilities.currentTransform; - swapchainCreateInfo.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR; - swapchainCreateInfo.presentMode = presentMode; - swapchainCreateInfo.clipped = VK_TRUE; - swapchainCreateInfo.oldSwapchain = VK_NULL_HANDLE; + swapchainCreateInfo.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR; + swapchainCreateInfo.surface = surface; + swapchainCreateInfo.minImageCount = imageCount; + swapchainCreateInfo.imageFormat = swapchainFormat.format; + swapchainCreateInfo.imageColorSpace = swapchainFormat.colorSpace; + swapchainCreateInfo.imageExtent = swapchainExtent; + swapchainCreateInfo.imageArrayLayers = 1; + swapchainCreateInfo.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; + swapchainCreateInfo.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE; + swapchainCreateInfo.preTransform = surfaceCapabilities.currentTransform; + swapchainCreateInfo.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR; + swapchainCreateInfo.presentMode = presentMode; + swapchainCreateInfo.clipped = VK_TRUE; + swapchainCreateInfo.oldSwapchain = VK_NULL_HANDLE; // Create the swapchain if (vkCreateSwapchainKHR(device, &swapchainCreateInfo, 0, &swapchain) != VK_SUCCESS) @@ -869,19 +918,19 @@ public: return; } - VkImageViewCreateInfo imageViewCreateInfo = VkImageViewCreateInfo(); - imageViewCreateInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO; - imageViewCreateInfo.viewType = VK_IMAGE_VIEW_TYPE_2D; - imageViewCreateInfo.format = swapchainFormat.format; - imageViewCreateInfo.components.r = VK_COMPONENT_SWIZZLE_IDENTITY; - imageViewCreateInfo.components.g = VK_COMPONENT_SWIZZLE_IDENTITY; - imageViewCreateInfo.components.b = VK_COMPONENT_SWIZZLE_IDENTITY; - imageViewCreateInfo.components.a = VK_COMPONENT_SWIZZLE_IDENTITY; - imageViewCreateInfo.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; - imageViewCreateInfo.subresourceRange.baseMipLevel = 0; - imageViewCreateInfo.subresourceRange.levelCount = 1; + VkImageViewCreateInfo imageViewCreateInfo = VkImageViewCreateInfo(); + imageViewCreateInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO; + imageViewCreateInfo.viewType = VK_IMAGE_VIEW_TYPE_2D; + imageViewCreateInfo.format = swapchainFormat.format; + imageViewCreateInfo.components.r = VK_COMPONENT_SWIZZLE_IDENTITY; + imageViewCreateInfo.components.g = VK_COMPONENT_SWIZZLE_IDENTITY; + imageViewCreateInfo.components.b = VK_COMPONENT_SWIZZLE_IDENTITY; + imageViewCreateInfo.components.a = VK_COMPONENT_SWIZZLE_IDENTITY; + imageViewCreateInfo.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; + imageViewCreateInfo.subresourceRange.baseMipLevel = 0; + imageViewCreateInfo.subresourceRange.levelCount = 1; imageViewCreateInfo.subresourceRange.baseArrayLayer = 0; - imageViewCreateInfo.subresourceRange.layerCount = 1; + imageViewCreateInfo.subresourceRange.layerCount = 1; // Create an image view for each swapchain image for (std::size_t i = 0; i < swapchainImages.size(); ++i) @@ -900,7 +949,7 @@ public: void setupShaders() { VkShaderModuleCreateInfo shaderModuleCreateInfo = VkShaderModuleCreateInfo(); - shaderModuleCreateInfo.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO; + shaderModuleCreateInfo.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO; // Use the vertex shader SPIR-V code to create a vertex shader module { @@ -921,7 +970,7 @@ public: } shaderModuleCreateInfo.codeSize = buffer.size() * sizeof(uint32_t); - shaderModuleCreateInfo.pCode = buffer.data(); + shaderModuleCreateInfo.pCode = buffer.data(); if (vkCreateShaderModule(device, &shaderModuleCreateInfo, 0, &vertexShaderModule) != VK_SUCCESS) { @@ -949,7 +998,7 @@ public: } shaderModuleCreateInfo.codeSize = buffer.size() * sizeof(uint32_t); - shaderModuleCreateInfo.pCode = buffer.data(); + shaderModuleCreateInfo.pCode = buffer.data(); if (vkCreateShaderModule(device, &shaderModuleCreateInfo, 0, &fragmentShaderModule) != VK_SUCCESS) { @@ -959,17 +1008,17 @@ public: } // Prepare the shader stage information for later pipeline creation - shaderStages[0]= VkPipelineShaderStageCreateInfo(); - shaderStages[0].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; - shaderStages[0].stage = VK_SHADER_STAGE_VERTEX_BIT; + shaderStages[0] = VkPipelineShaderStageCreateInfo(); + shaderStages[0].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; + shaderStages[0].stage = VK_SHADER_STAGE_VERTEX_BIT; shaderStages[0].module = vertexShaderModule; - shaderStages[0].pName = "main"; + shaderStages[0].pName = "main"; - shaderStages[1]= VkPipelineShaderStageCreateInfo(); - shaderStages[1].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; - shaderStages[1].stage = VK_SHADER_STAGE_FRAGMENT_BIT; + shaderStages[1] = VkPipelineShaderStageCreateInfo(); + shaderStages[1].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; + shaderStages[1].stage = VK_SHADER_STAGE_FRAGMENT_BIT; shaderStages[1].module = fragmentShaderModule; - shaderStages[1].pName = "main"; + shaderStages[1].pName = "main"; } // Setup renderpass and its subpass dependencies @@ -978,58 +1027,58 @@ public: VkAttachmentDescription attachmentDescriptions[2]; // Color attachment - attachmentDescriptions[0] = VkAttachmentDescription(); - attachmentDescriptions[0].format = swapchainFormat.format; - attachmentDescriptions[0].samples = VK_SAMPLE_COUNT_1_BIT; - attachmentDescriptions[0].loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR; - attachmentDescriptions[0].storeOp = VK_ATTACHMENT_STORE_OP_STORE; - attachmentDescriptions[0].stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE; + attachmentDescriptions[0] = VkAttachmentDescription(); + attachmentDescriptions[0].format = swapchainFormat.format; + attachmentDescriptions[0].samples = VK_SAMPLE_COUNT_1_BIT; + attachmentDescriptions[0].loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR; + attachmentDescriptions[0].storeOp = VK_ATTACHMENT_STORE_OP_STORE; + attachmentDescriptions[0].stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE; attachmentDescriptions[0].stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; - attachmentDescriptions[0].initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; - attachmentDescriptions[0].finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR; + attachmentDescriptions[0].initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; + attachmentDescriptions[0].finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR; // Depth attachment - attachmentDescriptions[1] = VkAttachmentDescription(); - attachmentDescriptions[1].format = depthFormat; - attachmentDescriptions[1].samples = VK_SAMPLE_COUNT_1_BIT; - attachmentDescriptions[1].loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR; - attachmentDescriptions[1].storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; - attachmentDescriptions[1].stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE; + attachmentDescriptions[1] = VkAttachmentDescription(); + attachmentDescriptions[1].format = depthFormat; + attachmentDescriptions[1].samples = VK_SAMPLE_COUNT_1_BIT; + attachmentDescriptions[1].loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR; + attachmentDescriptions[1].storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; + attachmentDescriptions[1].stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE; attachmentDescriptions[1].stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; - attachmentDescriptions[1].initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; - attachmentDescriptions[1].finalLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL; + attachmentDescriptions[1].initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; + attachmentDescriptions[1].finalLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL; VkAttachmentReference colorAttachmentReference = {}; - colorAttachmentReference.attachment = 0; - colorAttachmentReference.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; + colorAttachmentReference.attachment = 0; + colorAttachmentReference.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; VkAttachmentReference depthStencilAttachmentReference = {}; - depthStencilAttachmentReference.attachment = 1; - depthStencilAttachmentReference.layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL; + depthStencilAttachmentReference.attachment = 1; + depthStencilAttachmentReference.layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL; // Set up the renderpass to depend on commands that execute before the renderpass begins - VkSubpassDescription subpassDescription = VkSubpassDescription(); - subpassDescription.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS; - subpassDescription.colorAttachmentCount = 1; - subpassDescription.pColorAttachments = &colorAttachmentReference; + VkSubpassDescription subpassDescription = VkSubpassDescription(); + subpassDescription.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS; + subpassDescription.colorAttachmentCount = 1; + subpassDescription.pColorAttachments = &colorAttachmentReference; subpassDescription.pDepthStencilAttachment = &depthStencilAttachmentReference; VkSubpassDependency subpassDependency = VkSubpassDependency(); - subpassDependency.srcSubpass = VK_SUBPASS_EXTERNAL; - subpassDependency.srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; - subpassDependency.srcAccessMask = 0; - subpassDependency.dstSubpass = 0; - subpassDependency.dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; + subpassDependency.srcSubpass = VK_SUBPASS_EXTERNAL; + subpassDependency.srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; + subpassDependency.srcAccessMask = 0; + subpassDependency.dstSubpass = 0; + subpassDependency.dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; subpassDependency.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; VkRenderPassCreateInfo renderPassCreateInfo = VkRenderPassCreateInfo(); - renderPassCreateInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO; - renderPassCreateInfo.attachmentCount = 2; - renderPassCreateInfo.pAttachments = attachmentDescriptions; - renderPassCreateInfo.subpassCount = 1; - renderPassCreateInfo.pSubpasses = &subpassDescription; - renderPassCreateInfo.dependencyCount = 1; - renderPassCreateInfo.pDependencies = &subpassDependency; + renderPassCreateInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO; + renderPassCreateInfo.attachmentCount = 2; + renderPassCreateInfo.pAttachments = attachmentDescriptions; + renderPassCreateInfo.subpassCount = 1; + renderPassCreateInfo.pSubpasses = &subpassDescription; + renderPassCreateInfo.dependencyCount = 1; + renderPassCreateInfo.pDependencies = &subpassDependency; // Create the renderpass if (vkCreateRenderPass(device, &renderPassCreateInfo, 0, &renderPass) != VK_SUCCESS) @@ -1045,23 +1094,23 @@ public: VkDescriptorSetLayoutBinding descriptorSetLayoutBindings[2]; // Layout binding for uniform buffer - descriptorSetLayoutBindings[0] = VkDescriptorSetLayoutBinding(); - descriptorSetLayoutBindings[0].binding = 0; - descriptorSetLayoutBindings[0].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER; + descriptorSetLayoutBindings[0] = VkDescriptorSetLayoutBinding(); + descriptorSetLayoutBindings[0].binding = 0; + descriptorSetLayoutBindings[0].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER; descriptorSetLayoutBindings[0].descriptorCount = 1; - descriptorSetLayoutBindings[0].stageFlags = VK_SHADER_STAGE_VERTEX_BIT; + descriptorSetLayoutBindings[0].stageFlags = VK_SHADER_STAGE_VERTEX_BIT; // Layout binding for texture sampler - descriptorSetLayoutBindings[1] = VkDescriptorSetLayoutBinding(); - descriptorSetLayoutBindings[1].binding = 1; - descriptorSetLayoutBindings[1].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; + descriptorSetLayoutBindings[1] = VkDescriptorSetLayoutBinding(); + descriptorSetLayoutBindings[1].binding = 1; + descriptorSetLayoutBindings[1].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; descriptorSetLayoutBindings[1].descriptorCount = 1; - descriptorSetLayoutBindings[1].stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT; + descriptorSetLayoutBindings[1].stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT; VkDescriptorSetLayoutCreateInfo descriptorSetLayoutCreateInfo = VkDescriptorSetLayoutCreateInfo(); - descriptorSetLayoutCreateInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO; + descriptorSetLayoutCreateInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO; descriptorSetLayoutCreateInfo.bindingCount = 2; - descriptorSetLayoutCreateInfo.pBindings = descriptorSetLayoutBindings; + descriptorSetLayoutCreateInfo.pBindings = descriptorSetLayoutBindings; // Create descriptor set layout if (vkCreateDescriptorSetLayout(device, &descriptorSetLayoutCreateInfo, 0, &descriptorSetLayout) != VK_SUCCESS) @@ -1075,9 +1124,9 @@ public: void setupPipelineLayout() { VkPipelineLayoutCreateInfo pipelineLayoutCreateInfo = VkPipelineLayoutCreateInfo(); - pipelineLayoutCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO; - pipelineLayoutCreateInfo.setLayoutCount = 1; - pipelineLayoutCreateInfo.pSetLayouts = &descriptorSetLayout; + pipelineLayoutCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO; + pipelineLayoutCreateInfo.setLayoutCount = 1; + pipelineLayoutCreateInfo.pSetLayouts = &descriptorSetLayout; // Create pipeline layout if (vkCreatePipelineLayout(device, &pipelineLayoutCreateInfo, 0, &pipelineLayout) != VK_SUCCESS) @@ -1092,129 +1141,131 @@ public: { // Set up how the vertex shader pulls data out of our vertex buffer VkVertexInputBindingDescription vertexInputBindingDescription = VkVertexInputBindingDescription(); - vertexInputBindingDescription.binding = 0; - vertexInputBindingDescription.stride = sizeof(float) * 9; - vertexInputBindingDescription.inputRate = VK_VERTEX_INPUT_RATE_VERTEX; + vertexInputBindingDescription.binding = 0; + vertexInputBindingDescription.stride = sizeof(float) * 9; + vertexInputBindingDescription.inputRate = VK_VERTEX_INPUT_RATE_VERTEX; // Set up how the vertex buffer data is interpreted as attributes by the vertex shader VkVertexInputAttributeDescription vertexInputAttributeDescriptions[3]; // Position attribute - vertexInputAttributeDescriptions[0] = VkVertexInputAttributeDescription(); - vertexInputAttributeDescriptions[0].binding = 0; + vertexInputAttributeDescriptions[0] = VkVertexInputAttributeDescription(); + vertexInputAttributeDescriptions[0].binding = 0; vertexInputAttributeDescriptions[0].location = 0; - vertexInputAttributeDescriptions[0].format = VK_FORMAT_R32G32B32_SFLOAT; - vertexInputAttributeDescriptions[0].offset = sizeof(float) * 0; + vertexInputAttributeDescriptions[0].format = VK_FORMAT_R32G32B32_SFLOAT; + vertexInputAttributeDescriptions[0].offset = sizeof(float) * 0; // Color attribute - vertexInputAttributeDescriptions[1] = VkVertexInputAttributeDescription(); - vertexInputAttributeDescriptions[1].binding = 0; + vertexInputAttributeDescriptions[1] = VkVertexInputAttributeDescription(); + vertexInputAttributeDescriptions[1].binding = 0; vertexInputAttributeDescriptions[1].location = 1; - vertexInputAttributeDescriptions[1].format = VK_FORMAT_R32G32B32A32_SFLOAT; - vertexInputAttributeDescriptions[1].offset = sizeof(float) * 3; + vertexInputAttributeDescriptions[1].format = VK_FORMAT_R32G32B32A32_SFLOAT; + vertexInputAttributeDescriptions[1].offset = sizeof(float) * 3; // Texture coordinate attribute - vertexInputAttributeDescriptions[2] = VkVertexInputAttributeDescription(); - vertexInputAttributeDescriptions[2].binding = 0; + vertexInputAttributeDescriptions[2] = VkVertexInputAttributeDescription(); + vertexInputAttributeDescriptions[2].binding = 0; vertexInputAttributeDescriptions[2].location = 2; - vertexInputAttributeDescriptions[2].format = VK_FORMAT_R32G32_SFLOAT; - vertexInputAttributeDescriptions[2].offset = sizeof(float) * 7; + vertexInputAttributeDescriptions[2].format = VK_FORMAT_R32G32_SFLOAT; + vertexInputAttributeDescriptions[2].offset = sizeof(float) * 7; VkPipelineVertexInputStateCreateInfo vertexInputStateCreateInfo = VkPipelineVertexInputStateCreateInfo(); vertexInputStateCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO; - vertexInputStateCreateInfo.vertexBindingDescriptionCount = 1; - vertexInputStateCreateInfo.pVertexBindingDescriptions = &vertexInputBindingDescription; + vertexInputStateCreateInfo.vertexBindingDescriptionCount = 1; + vertexInputStateCreateInfo.pVertexBindingDescriptions = &vertexInputBindingDescription; vertexInputStateCreateInfo.vertexAttributeDescriptionCount = 3; - vertexInputStateCreateInfo.pVertexAttributeDescriptions = vertexInputAttributeDescriptions; + vertexInputStateCreateInfo.pVertexAttributeDescriptions = vertexInputAttributeDescriptions; // We want to generate a triangle list with our vertex data VkPipelineInputAssemblyStateCreateInfo inputAssemblyStateCreateInfo = VkPipelineInputAssemblyStateCreateInfo(); - inputAssemblyStateCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO; + inputAssemblyStateCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO; inputAssemblyStateCreateInfo.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; inputAssemblyStateCreateInfo.primitiveRestartEnable = VK_FALSE; // Set up the viewport VkViewport viewport = VkViewport(); - viewport.x = 0.0f; - viewport.y = 0.0f; - viewport.width = static_cast(swapchainExtent.width); - viewport.height = static_cast(swapchainExtent.height); - viewport.minDepth = 0.0f; - viewport.maxDepth = 1.f; + viewport.x = 0.0f; + viewport.y = 0.0f; + viewport.width = static_cast(swapchainExtent.width); + viewport.height = static_cast(swapchainExtent.height); + viewport.minDepth = 0.0f; + viewport.maxDepth = 1.f; // Set up the scissor region VkRect2D scissor = VkRect2D(); scissor.offset.x = 0; scissor.offset.y = 0; - scissor.extent = swapchainExtent; + scissor.extent = swapchainExtent; VkPipelineViewportStateCreateInfo pipelineViewportStateCreateInfo = VkPipelineViewportStateCreateInfo(); - pipelineViewportStateCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO; + pipelineViewportStateCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO; pipelineViewportStateCreateInfo.viewportCount = 1; - pipelineViewportStateCreateInfo.pViewports = &viewport; - pipelineViewportStateCreateInfo.scissorCount = 1; - pipelineViewportStateCreateInfo.pScissors = &scissor; + pipelineViewportStateCreateInfo.pViewports = &viewport; + pipelineViewportStateCreateInfo.scissorCount = 1; + pipelineViewportStateCreateInfo.pScissors = &scissor; // Set up rasterization parameters: fill polygons, no backface culling, front face is counter-clockwise VkPipelineRasterizationStateCreateInfo pipelineRasterizationStateCreateInfo = VkPipelineRasterizationStateCreateInfo(); pipelineRasterizationStateCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO; - pipelineRasterizationStateCreateInfo.depthClampEnable = VK_FALSE; + pipelineRasterizationStateCreateInfo.depthClampEnable = VK_FALSE; pipelineRasterizationStateCreateInfo.rasterizerDiscardEnable = VK_FALSE; - pipelineRasterizationStateCreateInfo.polygonMode = VK_POLYGON_MODE_FILL; - pipelineRasterizationStateCreateInfo.lineWidth = 1.0f; - pipelineRasterizationStateCreateInfo.cullMode = VK_CULL_MODE_NONE; - pipelineRasterizationStateCreateInfo.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE; - pipelineRasterizationStateCreateInfo.depthBiasEnable = VK_FALSE; + pipelineRasterizationStateCreateInfo.polygonMode = VK_POLYGON_MODE_FILL; + pipelineRasterizationStateCreateInfo.lineWidth = 1.0f; + pipelineRasterizationStateCreateInfo.cullMode = VK_CULL_MODE_NONE; + pipelineRasterizationStateCreateInfo.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE; + pipelineRasterizationStateCreateInfo.depthBiasEnable = VK_FALSE; // Enable depth testing and disable scissor testing VkPipelineDepthStencilStateCreateInfo pipelineDepthStencilStateCreateInfo = VkPipelineDepthStencilStateCreateInfo(); pipelineDepthStencilStateCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO; - pipelineDepthStencilStateCreateInfo.depthTestEnable = VK_TRUE; - pipelineDepthStencilStateCreateInfo.depthWriteEnable = VK_TRUE; - pipelineDepthStencilStateCreateInfo.depthCompareOp = VK_COMPARE_OP_LESS; + pipelineDepthStencilStateCreateInfo.depthTestEnable = VK_TRUE; + pipelineDepthStencilStateCreateInfo.depthWriteEnable = VK_TRUE; + pipelineDepthStencilStateCreateInfo.depthCompareOp = VK_COMPARE_OP_LESS; pipelineDepthStencilStateCreateInfo.depthBoundsTestEnable = VK_FALSE; - pipelineDepthStencilStateCreateInfo.stencilTestEnable = VK_FALSE; + pipelineDepthStencilStateCreateInfo.stencilTestEnable = VK_FALSE; // Enable multi-sampling VkPipelineMultisampleStateCreateInfo pipelineMultisampleStateCreateInfo = VkPipelineMultisampleStateCreateInfo(); pipelineMultisampleStateCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO; - pipelineMultisampleStateCreateInfo.sampleShadingEnable = VK_FALSE; + pipelineMultisampleStateCreateInfo.sampleShadingEnable = VK_FALSE; pipelineMultisampleStateCreateInfo.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT; // Set up blending parameters VkPipelineColorBlendAttachmentState pipelineColorBlendAttachmentState = VkPipelineColorBlendAttachmentState(); - pipelineColorBlendAttachmentState.blendEnable = VK_TRUE; - pipelineColorBlendAttachmentState.srcColorBlendFactor = VK_BLEND_FACTOR_SRC_ALPHA; - pipelineColorBlendAttachmentState.dstColorBlendFactor = VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA; - pipelineColorBlendAttachmentState.colorBlendOp = VK_BLEND_OP_ADD; - pipelineColorBlendAttachmentState.srcAlphaBlendFactor = VK_BLEND_FACTOR_ONE; - pipelineColorBlendAttachmentState.dstAlphaBlendFactor = VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA; - pipelineColorBlendAttachmentState.alphaBlendOp = VK_BLEND_OP_ADD; - pipelineColorBlendAttachmentState.colorWriteMask = VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT; + pipelineColorBlendAttachmentState.blendEnable = VK_TRUE; + pipelineColorBlendAttachmentState.srcColorBlendFactor = VK_BLEND_FACTOR_SRC_ALPHA; + pipelineColorBlendAttachmentState.dstColorBlendFactor = VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA; + pipelineColorBlendAttachmentState.colorBlendOp = VK_BLEND_OP_ADD; + pipelineColorBlendAttachmentState.srcAlphaBlendFactor = VK_BLEND_FACTOR_ONE; + pipelineColorBlendAttachmentState.dstAlphaBlendFactor = VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA; + pipelineColorBlendAttachmentState.alphaBlendOp = VK_BLEND_OP_ADD; + pipelineColorBlendAttachmentState.colorWriteMask = VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | + VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT; VkPipelineColorBlendStateCreateInfo pipelineColorBlendStateCreateInfo = VkPipelineColorBlendStateCreateInfo(); - pipelineColorBlendStateCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO; - pipelineColorBlendStateCreateInfo.logicOpEnable = VK_FALSE; + pipelineColorBlendStateCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO; + pipelineColorBlendStateCreateInfo.logicOpEnable = VK_FALSE; pipelineColorBlendStateCreateInfo.attachmentCount = 1; - pipelineColorBlendStateCreateInfo.pAttachments = &pipelineColorBlendAttachmentState; + pipelineColorBlendStateCreateInfo.pAttachments = &pipelineColorBlendAttachmentState; VkGraphicsPipelineCreateInfo graphicsPipelineCreateInfo = VkGraphicsPipelineCreateInfo(); - graphicsPipelineCreateInfo.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO; - graphicsPipelineCreateInfo.stageCount = 2; - graphicsPipelineCreateInfo.pStages = shaderStages; - graphicsPipelineCreateInfo.pVertexInputState = &vertexInputStateCreateInfo; - graphicsPipelineCreateInfo.pInputAssemblyState = &inputAssemblyStateCreateInfo; - graphicsPipelineCreateInfo.pViewportState = &pipelineViewportStateCreateInfo; - graphicsPipelineCreateInfo.pRasterizationState = &pipelineRasterizationStateCreateInfo; - graphicsPipelineCreateInfo.pDepthStencilState = &pipelineDepthStencilStateCreateInfo; - graphicsPipelineCreateInfo.pMultisampleState = &pipelineMultisampleStateCreateInfo; - graphicsPipelineCreateInfo.pColorBlendState = &pipelineColorBlendStateCreateInfo; - graphicsPipelineCreateInfo.layout = pipelineLayout; - graphicsPipelineCreateInfo.renderPass = renderPass; - graphicsPipelineCreateInfo.subpass = 0; + graphicsPipelineCreateInfo.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO; + graphicsPipelineCreateInfo.stageCount = 2; + graphicsPipelineCreateInfo.pStages = shaderStages; + graphicsPipelineCreateInfo.pVertexInputState = &vertexInputStateCreateInfo; + graphicsPipelineCreateInfo.pInputAssemblyState = &inputAssemblyStateCreateInfo; + graphicsPipelineCreateInfo.pViewportState = &pipelineViewportStateCreateInfo; + graphicsPipelineCreateInfo.pRasterizationState = &pipelineRasterizationStateCreateInfo; + graphicsPipelineCreateInfo.pDepthStencilState = &pipelineDepthStencilStateCreateInfo; + graphicsPipelineCreateInfo.pMultisampleState = &pipelineMultisampleStateCreateInfo; + graphicsPipelineCreateInfo.pColorBlendState = &pipelineColorBlendStateCreateInfo; + graphicsPipelineCreateInfo.layout = pipelineLayout; + graphicsPipelineCreateInfo.renderPass = renderPass; + graphicsPipelineCreateInfo.subpass = 0; // Create our graphics pipeline - if (vkCreateGraphicsPipelines(device, VK_NULL_HANDLE, 1, &graphicsPipelineCreateInfo, 0, &graphicsPipeline) != VK_SUCCESS) + if (vkCreateGraphicsPipelines(device, VK_NULL_HANDLE, 1, &graphicsPipelineCreateInfo, 0, &graphicsPipeline) != + VK_SUCCESS) { vulkanAvailable = false; return; @@ -1227,12 +1278,12 @@ public: swapchainFramebuffers.resize(swapchainImageViews.size()); VkFramebufferCreateInfo framebufferCreateInfo = VkFramebufferCreateInfo(); - framebufferCreateInfo.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO; - framebufferCreateInfo.renderPass = renderPass; - framebufferCreateInfo.attachmentCount = 2; - framebufferCreateInfo.width = swapchainExtent.width; - framebufferCreateInfo.height = swapchainExtent.height; - framebufferCreateInfo.layers = 1; + framebufferCreateInfo.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO; + framebufferCreateInfo.renderPass = renderPass; + framebufferCreateInfo.attachmentCount = 2; + framebufferCreateInfo.width = swapchainExtent.width; + framebufferCreateInfo.height = swapchainExtent.height; + framebufferCreateInfo.layers = 1; for (std::size_t i = 0; i < swapchainFramebuffers.size(); ++i) { @@ -1255,9 +1306,9 @@ public: { // We want to be able to reset command buffers after submitting them VkCommandPoolCreateInfo commandPoolCreateInfo = VkCommandPoolCreateInfo(); - commandPoolCreateInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO; - commandPoolCreateInfo.queueFamilyIndex = static_cast(queueFamilyIndex); - commandPoolCreateInfo.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT; + commandPoolCreateInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO; + commandPoolCreateInfo.queueFamilyIndex = static_cast(queueFamilyIndex); + commandPoolCreateInfo.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT; // Create our command pool if (vkCreateCommandPool(device, &commandPoolCreateInfo, 0, &commandPool) != VK_SUCCESS) @@ -1268,14 +1319,18 @@ public: } // Helper to create a generic buffer with the specified size, usage and memory flags - bool createBuffer(VkDeviceSize size, VkBufferUsageFlags usage, VkMemoryPropertyFlags properties, VkBuffer& buffer, VkDeviceMemory& memory) + bool createBuffer(VkDeviceSize size, + VkBufferUsageFlags usage, + VkMemoryPropertyFlags properties, + VkBuffer& buffer, + VkDeviceMemory& memory) { // We only have a single queue so we can request exclusive access VkBufferCreateInfo bufferCreateInfo = VkBufferCreateInfo(); - bufferCreateInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; - bufferCreateInfo.size = size; - bufferCreateInfo.usage = usage; - bufferCreateInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE; + bufferCreateInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; + bufferCreateInfo.size = size; + bufferCreateInfo.usage = usage; + bufferCreateInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE; // Create the buffer, this does not allocate any memory for it yet if (vkCreateBuffer(device, &bufferCreateInfo, 0, &buffer) != VK_SUCCESS) @@ -1302,9 +1357,9 @@ public: return false; VkMemoryAllocateInfo memoryAllocateInfo = VkMemoryAllocateInfo(); - memoryAllocateInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; - memoryAllocateInfo.allocationSize = memoryRequirements.size; - memoryAllocateInfo.memoryTypeIndex = memoryType; + memoryAllocateInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; + memoryAllocateInfo.allocationSize = memoryRequirements.size; + memoryAllocateInfo.memoryTypeIndex = memoryType; // Allocate the memory out of the GPU pool for the required memory type if (vkAllocateMemory(device, &memoryAllocateInfo, 0, &memory) != VK_SUCCESS) @@ -1322,10 +1377,10 @@ public: { // Allocate a primary command buffer out of our command pool VkCommandBufferAllocateInfo commandBufferAllocateInfo = VkCommandBufferAllocateInfo(); - commandBufferAllocateInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO; - commandBufferAllocateInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; - commandBufferAllocateInfo.commandPool = commandPool; - commandBufferAllocateInfo.commandBufferCount = 1; + commandBufferAllocateInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO; + commandBufferAllocateInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; + commandBufferAllocateInfo.commandPool = commandPool; + commandBufferAllocateInfo.commandBufferCount = 1; VkCommandBuffer commandBuffer; @@ -1334,8 +1389,8 @@ public: // Begin the command buffer VkCommandBufferBeginInfo commandBufferBeginInfo = VkCommandBufferBeginInfo(); - commandBufferBeginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; - commandBufferBeginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; + commandBufferBeginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; + commandBufferBeginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; if (vkBeginCommandBuffer(commandBuffer, &commandBufferBeginInfo) != VK_SUCCESS) { @@ -1346,19 +1401,19 @@ public: // Add our buffer copy command VkBufferCopy bufferCopy = VkBufferCopy(); - bufferCopy.srcOffset = 0; - bufferCopy.dstOffset = 0; - bufferCopy.size = size; + bufferCopy.srcOffset = 0; + bufferCopy.dstOffset = 0; + bufferCopy.size = size; vkCmdCopyBuffer(commandBuffer, src, dst, 1, &bufferCopy); // End and submit the command buffer vkEndCommandBuffer(commandBuffer); - VkSubmitInfo submitInfo = VkSubmitInfo(); - submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; + VkSubmitInfo submitInfo = VkSubmitInfo(); + submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; submitInfo.commandBufferCount = 1; - submitInfo.pCommandBuffers = &commandBuffer; + submitInfo.pCommandBuffers = &commandBuffer; if (vkQueueSubmit(queue, 1, &submitInfo, VK_NULL_HANDLE) != VK_SUCCESS) { @@ -1420,16 +1475,14 @@ public: // clang-format on // Create a staging buffer that is writable by the CPU - VkBuffer stagingBuffer = 0; + VkBuffer stagingBuffer = 0; VkDeviceMemory stagingBufferMemory = 0; - if (!createBuffer( - sizeof(vertexData), - VK_BUFFER_USAGE_TRANSFER_SRC_BIT, - VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, - stagingBuffer, - stagingBufferMemory - )) + if (!createBuffer(sizeof(vertexData), + VK_BUFFER_USAGE_TRANSFER_SRC_BIT, + VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, + stagingBuffer, + stagingBufferMemory)) { vulkanAvailable = false; return; @@ -1454,13 +1507,11 @@ public: vkUnmapMemory(device, stagingBufferMemory); // Create the GPU local vertex buffer - if (!createBuffer( - sizeof(vertexData), - VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, - VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, - vertexBuffer, - vertexBufferMemory - )) + if (!createBuffer(sizeof(vertexData), + VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, + VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, + vertexBuffer, + vertexBufferMemory)) { vkFreeMemory(device, stagingBufferMemory, 0); vkDestroyBuffer(device, stagingBuffer, 0); @@ -1503,16 +1554,14 @@ public: // clang-format on // Create a staging buffer that is writable by the CPU - VkBuffer stagingBuffer = 0; + VkBuffer stagingBuffer = 0; VkDeviceMemory stagingBufferMemory = 0; - if (!createBuffer( - sizeof(indexData), - VK_BUFFER_USAGE_TRANSFER_SRC_BIT, - VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, - stagingBuffer, - stagingBufferMemory - )) + if (!createBuffer(sizeof(indexData), + VK_BUFFER_USAGE_TRANSFER_SRC_BIT, + VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, + stagingBuffer, + stagingBufferMemory)) { vulkanAvailable = false; return; @@ -1537,13 +1586,11 @@ public: vkUnmapMemory(device, stagingBufferMemory); // Create the GPU local index buffer - if (!createBuffer( - sizeof(indexData), - VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_INDEX_BUFFER_BIT, - VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, - indexBuffer, - indexBufferMemory - )) + if (!createBuffer(sizeof(indexData), + VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_INDEX_BUFFER_BIT, + VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, + indexBuffer, + indexBufferMemory)) { vkFreeMemory(device, stagingBufferMemory, 0); vkDestroyBuffer(device, stagingBuffer, 0); @@ -1570,13 +1617,11 @@ public: uniformBuffersMemory.push_back(0); // The uniform buffer will be host visible and coherent since we use it for streaming data every frame - if (!createBuffer( - sizeof(Matrix) * 3, - VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, - VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, - uniformBuffers[i], - uniformBuffersMemory[i] - )) + if (!createBuffer(sizeof(Matrix) * 3, + VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, + VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, + uniformBuffers[i], + uniformBuffersMemory[i])) { vulkanAvailable = false; return; @@ -1585,23 +1630,30 @@ public: } // Helper to create a generic image with the specified size, format, usage and memory flags - bool createImage(uint32_t width, uint32_t height, VkFormat format, VkImageTiling tiling, VkImageUsageFlags usage, VkMemoryPropertyFlags properties, VkImage& image, VkDeviceMemory& imageMemory) + bool createImage(uint32_t width, + uint32_t height, + VkFormat format, + VkImageTiling tiling, + VkImageUsageFlags usage, + VkMemoryPropertyFlags properties, + VkImage& image, + VkDeviceMemory& imageMemory) { // We only have a single queue so we can request exclusive access VkImageCreateInfo imageCreateInfo = VkImageCreateInfo(); - imageCreateInfo.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO; - imageCreateInfo.imageType = VK_IMAGE_TYPE_2D; - imageCreateInfo.extent.width = width; - imageCreateInfo.extent.height = height; - imageCreateInfo.extent.depth = 1; - imageCreateInfo.mipLevels = 1; - imageCreateInfo.arrayLayers = 1; - imageCreateInfo.format = format; - imageCreateInfo.tiling = tiling; - imageCreateInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; - imageCreateInfo.usage = usage; - imageCreateInfo.samples = VK_SAMPLE_COUNT_1_BIT; - imageCreateInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE; + imageCreateInfo.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO; + imageCreateInfo.imageType = VK_IMAGE_TYPE_2D; + imageCreateInfo.extent.width = width; + imageCreateInfo.extent.height = height; + imageCreateInfo.extent.depth = 1; + imageCreateInfo.mipLevels = 1; + imageCreateInfo.arrayLayers = 1; + imageCreateInfo.format = format; + imageCreateInfo.tiling = tiling; + imageCreateInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; + imageCreateInfo.usage = usage; + imageCreateInfo.samples = VK_SAMPLE_COUNT_1_BIT; + imageCreateInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE; // Create the image, this does not allocate any memory for it yet if (vkCreateImage(device, &imageCreateInfo, 0, &image) != VK_SUCCESS) @@ -1628,9 +1680,9 @@ public: return false; VkMemoryAllocateInfo memoryAllocateInfo = VkMemoryAllocateInfo(); - memoryAllocateInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; - memoryAllocateInfo.allocationSize = memoryRequirements.size; - memoryAllocateInfo.memoryTypeIndex = memoryType; + memoryAllocateInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; + memoryAllocateInfo.allocationSize = memoryRequirements.size; + memoryAllocateInfo.memoryTypeIndex = memoryType; // Allocate the memory out of the GPU pool for the required memory type if (vkAllocateMemory(device, &memoryAllocateInfo, 0, &imageMemory) != VK_SUCCESS) @@ -1647,16 +1699,14 @@ public: void setupDepthImage() { // Create our depth image - if (!createImage( - swapchainExtent.width, - swapchainExtent.height, - depthFormat, - VK_IMAGE_TILING_OPTIMAL, - VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT, - VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, - depthImage, - depthImageMemory - )) + if (!createImage(swapchainExtent.width, + swapchainExtent.height, + depthFormat, + VK_IMAGE_TILING_OPTIMAL, + VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT, + VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, + depthImage, + depthImageMemory)) { vulkanAvailable = false; return; @@ -1664,10 +1714,10 @@ public: // Allocate a command buffer VkCommandBufferAllocateInfo commandBufferAllocateInfo = VkCommandBufferAllocateInfo(); - commandBufferAllocateInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO; - commandBufferAllocateInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; - commandBufferAllocateInfo.commandPool = commandPool; - commandBufferAllocateInfo.commandBufferCount = 1; + commandBufferAllocateInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO; + commandBufferAllocateInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; + commandBufferAllocateInfo.commandPool = commandPool; + commandBufferAllocateInfo.commandBufferCount = 1; VkCommandBuffer commandBuffer; @@ -1679,13 +1729,13 @@ public: // Begin the command buffer VkCommandBufferBeginInfo commandBufferBeginInfo = VkCommandBufferBeginInfo(); - commandBufferBeginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; - commandBufferBeginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; + commandBufferBeginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; + commandBufferBeginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; - VkSubmitInfo submitInfo = VkSubmitInfo(); - submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; + VkSubmitInfo submitInfo = VkSubmitInfo(); + submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; submitInfo.commandBufferCount = 1; - submitInfo.pCommandBuffers = &commandBuffer; + submitInfo.pCommandBuffers = &commandBuffer; if (vkBeginCommandBuffer(commandBuffer, &commandBufferBeginInfo) != VK_SUCCESS) { @@ -1696,22 +1746,32 @@ public: } // Submit a barrier to transition the image layout to depth stencil optimal - VkImageMemoryBarrier barrier = VkImageMemoryBarrier(); - barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; - barrier.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED; - barrier.newLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL; - barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - barrier.image = depthImage; - barrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT | ((depthFormat == VK_FORMAT_D32_SFLOAT) ? 0 : VK_IMAGE_ASPECT_STENCIL_BIT); - barrier.subresourceRange.baseMipLevel = 0; - barrier.subresourceRange.levelCount = 1; + VkImageMemoryBarrier barrier = VkImageMemoryBarrier(); + barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; + barrier.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED; + barrier.newLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL; + barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + barrier.image = depthImage; + barrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT | + ((depthFormat == VK_FORMAT_D32_SFLOAT) ? 0 : VK_IMAGE_ASPECT_STENCIL_BIT); + barrier.subresourceRange.baseMipLevel = 0; + barrier.subresourceRange.levelCount = 1; barrier.subresourceRange.baseArrayLayer = 0; - barrier.subresourceRange.layerCount = 1; - barrier.srcAccessMask = 0; + barrier.subresourceRange.layerCount = 1; + barrier.srcAccessMask = 0; barrier.dstAccessMask = VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT; - vkCmdPipelineBarrier(commandBuffer, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT, 0, 0, 0, 0, 0, 1, &barrier); + vkCmdPipelineBarrier(commandBuffer, + VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, + VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT, + 0, + 0, + 0, + 0, + 0, + 1, + &barrier); // End and submit the command buffer if (vkEndCommandBuffer(commandBuffer) != VK_SUCCESS) @@ -1747,15 +1807,17 @@ public: void setupDepthImageView() { VkImageViewCreateInfo imageViewCreateInfo = VkImageViewCreateInfo(); - imageViewCreateInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO; - imageViewCreateInfo.image = depthImage; - imageViewCreateInfo.viewType = VK_IMAGE_VIEW_TYPE_2D; - imageViewCreateInfo.format = depthFormat; - imageViewCreateInfo.subresourceRange.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT | ((depthFormat == VK_FORMAT_D32_SFLOAT) ? 0 : VK_IMAGE_ASPECT_STENCIL_BIT); - imageViewCreateInfo.subresourceRange.baseMipLevel = 0; - imageViewCreateInfo.subresourceRange.levelCount = 1; + imageViewCreateInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO; + imageViewCreateInfo.image = depthImage; + imageViewCreateInfo.viewType = VK_IMAGE_VIEW_TYPE_2D; + imageViewCreateInfo.format = depthFormat; + imageViewCreateInfo.subresourceRange + .aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT | + ((depthFormat == VK_FORMAT_D32_SFLOAT) ? 0 : VK_IMAGE_ASPECT_STENCIL_BIT); + imageViewCreateInfo.subresourceRange.baseMipLevel = 0; + imageViewCreateInfo.subresourceRange.levelCount = 1; imageViewCreateInfo.subresourceRange.baseArrayLayer = 0; - imageViewCreateInfo.subresourceRange.layerCount = 1; + imageViewCreateInfo.subresourceRange.layerCount = 1; // Create the depth image view if (vkCreateImageView(device, &imageViewCreateInfo, 0, &depthImageView) != VK_SUCCESS) @@ -1780,9 +1842,13 @@ public: // Create a staging buffer to transfer the data with VkDeviceSize imageSize = imageData.getSize().x * imageData.getSize().y * 4; - VkBuffer stagingBuffer; + VkBuffer stagingBuffer; VkDeviceMemory stagingBufferMemory; - createBuffer(imageSize, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, stagingBuffer, stagingBufferMemory); + createBuffer(imageSize, + VK_BUFFER_USAGE_TRANSFER_SRC_BIT, + VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, + stagingBuffer, + stagingBufferMemory); void* ptr; @@ -1803,16 +1869,14 @@ public: vkUnmapMemory(device, stagingBufferMemory); // Create a GPU local image - if (!createImage( - imageData.getSize().x, - imageData.getSize().y, - VK_FORMAT_R8G8B8A8_UNORM, - VK_IMAGE_TILING_OPTIMAL, - VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT, - VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, - textureImage, - textureImageMemory - )) + if (!createImage(imageData.getSize().x, + imageData.getSize().y, + VK_FORMAT_R8G8B8A8_UNORM, + VK_IMAGE_TILING_OPTIMAL, + VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT, + VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, + textureImage, + textureImageMemory)) { vkFreeMemory(device, stagingBufferMemory, 0); vkDestroyBuffer(device, stagingBuffer, 0); @@ -1823,10 +1887,10 @@ public: // Create a command buffer VkCommandBufferAllocateInfo commandBufferAllocateInfo = VkCommandBufferAllocateInfo(); - commandBufferAllocateInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO; - commandBufferAllocateInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; - commandBufferAllocateInfo.commandPool = commandPool; - commandBufferAllocateInfo.commandBufferCount = 1; + commandBufferAllocateInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO; + commandBufferAllocateInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; + commandBufferAllocateInfo.commandPool = commandPool; + commandBufferAllocateInfo.commandBufferCount = 1; VkCommandBuffer commandBuffer; @@ -1841,13 +1905,13 @@ public: // Begin the command buffer VkCommandBufferBeginInfo commandBufferBeginInfo = VkCommandBufferBeginInfo(); - commandBufferBeginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; - commandBufferBeginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; + commandBufferBeginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; + commandBufferBeginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; - VkSubmitInfo submitInfo = VkSubmitInfo(); - submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; + VkSubmitInfo submitInfo = VkSubmitInfo(); + submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; submitInfo.commandBufferCount = 1; - submitInfo.pCommandBuffers = &commandBuffer; + submitInfo.pCommandBuffers = &commandBuffer; if (vkBeginCommandBuffer(commandBuffer, &commandBufferBeginInfo) != VK_SUCCESS) { @@ -1861,20 +1925,20 @@ public: } // Submit a barrier to transition the image layout to transfer destionation optimal - VkImageMemoryBarrier barrier = VkImageMemoryBarrier(); - barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; - barrier.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED; - barrier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; - barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - barrier.image = textureImage; - barrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; - barrier.subresourceRange.baseMipLevel = 0; - barrier.subresourceRange.levelCount = 1; + VkImageMemoryBarrier barrier = VkImageMemoryBarrier(); + barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; + barrier.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED; + barrier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; + barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + barrier.image = textureImage; + barrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; + barrier.subresourceRange.baseMipLevel = 0; + barrier.subresourceRange.levelCount = 1; barrier.subresourceRange.baseArrayLayer = 0; - barrier.subresourceRange.layerCount = 1; - barrier.srcAccessMask = 0; - barrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; + barrier.subresourceRange.layerCount = 1; + barrier.srcAccessMask = 0; + barrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; vkCmdPipelineBarrier(commandBuffer, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, 0, 0, 0, 1, &barrier); @@ -1925,20 +1989,20 @@ public: } // Copy the staging buffer contents into the image - VkBufferImageCopy bufferImageCopy = VkBufferImageCopy(); - bufferImageCopy.bufferOffset = 0; - bufferImageCopy.bufferRowLength = 0; - bufferImageCopy.bufferImageHeight = 0; - bufferImageCopy.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; - bufferImageCopy.imageSubresource.mipLevel = 0; + VkBufferImageCopy bufferImageCopy = VkBufferImageCopy(); + bufferImageCopy.bufferOffset = 0; + bufferImageCopy.bufferRowLength = 0; + bufferImageCopy.bufferImageHeight = 0; + bufferImageCopy.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; + bufferImageCopy.imageSubresource.mipLevel = 0; bufferImageCopy.imageSubresource.baseArrayLayer = 0; - bufferImageCopy.imageSubresource.layerCount = 1; - bufferImageCopy.imageOffset.x = 0; - bufferImageCopy.imageOffset.y = 0; - bufferImageCopy.imageOffset.z = 0; - bufferImageCopy.imageExtent.width = imageData.getSize().x; - bufferImageCopy.imageExtent.height = imageData.getSize().y; - bufferImageCopy.imageExtent.depth = 1; + bufferImageCopy.imageSubresource.layerCount = 1; + bufferImageCopy.imageOffset.x = 0; + bufferImageCopy.imageOffset.y = 0; + bufferImageCopy.imageOffset.z = 0; + bufferImageCopy.imageExtent.width = imageData.getSize().x; + bufferImageCopy.imageExtent.height = imageData.getSize().y; + bufferImageCopy.imageExtent.depth = 1; vkCmdCopyBufferToImage(commandBuffer, stagingBuffer, textureImage, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &bufferImageCopy); @@ -1990,12 +2054,21 @@ public: } // Submit a barrier to transition the image layout from transfer destionation optimal to shader read-only optimal - barrier.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; - barrier.newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; + barrier.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; + barrier.newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT; - vkCmdPipelineBarrier(commandBuffer, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, 0, 0, 0, 0, 0, 1, &barrier); + vkCmdPipelineBarrier(commandBuffer, + VK_PIPELINE_STAGE_TRANSFER_BIT, + VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, + 0, + 0, + 0, + 0, + 0, + 1, + &barrier); // End and submit the command buffer if (vkEndCommandBuffer(commandBuffer) != VK_SUCCESS) @@ -2042,16 +2115,16 @@ public: // Create an image view for our texture void setupTextureImageView() { - VkImageViewCreateInfo imageViewCreateInfo = VkImageViewCreateInfo(); - imageViewCreateInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO; - imageViewCreateInfo.image = textureImage; - imageViewCreateInfo.viewType = VK_IMAGE_VIEW_TYPE_2D; - imageViewCreateInfo.format = VK_FORMAT_R8G8B8A8_UNORM; - imageViewCreateInfo.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; - imageViewCreateInfo.subresourceRange.baseMipLevel = 0; - imageViewCreateInfo.subresourceRange.levelCount = 1; + VkImageViewCreateInfo imageViewCreateInfo = VkImageViewCreateInfo(); + imageViewCreateInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO; + imageViewCreateInfo.image = textureImage; + imageViewCreateInfo.viewType = VK_IMAGE_VIEW_TYPE_2D; + imageViewCreateInfo.format = VK_FORMAT_R8G8B8A8_UNORM; + imageViewCreateInfo.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; + imageViewCreateInfo.subresourceRange.baseMipLevel = 0; + imageViewCreateInfo.subresourceRange.levelCount = 1; imageViewCreateInfo.subresourceRange.baseArrayLayer = 0; - imageViewCreateInfo.subresourceRange.layerCount = 1; + imageViewCreateInfo.subresourceRange.layerCount = 1; // Create our texture image view if (vkCreateImageView(device, &imageViewCreateInfo, 0, &textureImageView) != VK_SUCCESS) @@ -2065,23 +2138,23 @@ public: void setupTextureSampler() { // Sampler parameters: linear min/mag filtering, 4x anisotropic - VkSamplerCreateInfo samplerCreateInfo = VkSamplerCreateInfo(); - samplerCreateInfo.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO; - samplerCreateInfo.magFilter = VK_FILTER_LINEAR; - samplerCreateInfo.minFilter = VK_FILTER_LINEAR; - samplerCreateInfo.addressModeU = VK_SAMPLER_ADDRESS_MODE_REPEAT; - samplerCreateInfo.addressModeV = VK_SAMPLER_ADDRESS_MODE_REPEAT; - samplerCreateInfo.addressModeW = VK_SAMPLER_ADDRESS_MODE_REPEAT; - samplerCreateInfo.anisotropyEnable = VK_TRUE; - samplerCreateInfo.maxAnisotropy = 4; - samplerCreateInfo.borderColor = VK_BORDER_COLOR_INT_OPAQUE_BLACK; + VkSamplerCreateInfo samplerCreateInfo = VkSamplerCreateInfo(); + samplerCreateInfo.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO; + samplerCreateInfo.magFilter = VK_FILTER_LINEAR; + samplerCreateInfo.minFilter = VK_FILTER_LINEAR; + samplerCreateInfo.addressModeU = VK_SAMPLER_ADDRESS_MODE_REPEAT; + samplerCreateInfo.addressModeV = VK_SAMPLER_ADDRESS_MODE_REPEAT; + samplerCreateInfo.addressModeW = VK_SAMPLER_ADDRESS_MODE_REPEAT; + samplerCreateInfo.anisotropyEnable = VK_TRUE; + samplerCreateInfo.maxAnisotropy = 4; + samplerCreateInfo.borderColor = VK_BORDER_COLOR_INT_OPAQUE_BLACK; samplerCreateInfo.unnormalizedCoordinates = VK_FALSE; - samplerCreateInfo.compareEnable = VK_FALSE; - samplerCreateInfo.compareOp = VK_COMPARE_OP_ALWAYS; - samplerCreateInfo.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR; - samplerCreateInfo.mipLodBias = 0.0f; - samplerCreateInfo.minLod = 0.0f; - samplerCreateInfo.maxLod = 0.0f; + samplerCreateInfo.compareEnable = VK_FALSE; + samplerCreateInfo.compareOp = VK_COMPARE_OP_ALWAYS; + samplerCreateInfo.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR; + samplerCreateInfo.mipLodBias = 0.0f; + samplerCreateInfo.minLod = 0.0f; + samplerCreateInfo.maxLod = 0.0f; // Create our sampler if (vkCreateSampler(device, &samplerCreateInfo, 0, &textureSampler) != VK_SUCCESS) @@ -2097,19 +2170,19 @@ public: // We need to allocate as many descriptor sets as we have frames in flight VkDescriptorPoolSize descriptorPoolSizes[2]; - descriptorPoolSizes[0] = VkDescriptorPoolSize(); - descriptorPoolSizes[0].type = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER; + descriptorPoolSizes[0] = VkDescriptorPoolSize(); + descriptorPoolSizes[0].type = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER; descriptorPoolSizes[0].descriptorCount = static_cast(swapchainImages.size()); - descriptorPoolSizes[1] = VkDescriptorPoolSize(); - descriptorPoolSizes[1].type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; + descriptorPoolSizes[1] = VkDescriptorPoolSize(); + descriptorPoolSizes[1].type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; descriptorPoolSizes[1].descriptorCount = static_cast(swapchainImages.size()); VkDescriptorPoolCreateInfo descriptorPoolCreateInfo = VkDescriptorPoolCreateInfo(); - descriptorPoolCreateInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO; - descriptorPoolCreateInfo.poolSizeCount = 2; - descriptorPoolCreateInfo.pPoolSizes = descriptorPoolSizes; - descriptorPoolCreateInfo.maxSets = static_cast(swapchainImages.size()); + descriptorPoolCreateInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO; + descriptorPoolCreateInfo.poolSizeCount = 2; + descriptorPoolCreateInfo.pPoolSizes = descriptorPoolSizes; + descriptorPoolCreateInfo.maxSets = static_cast(swapchainImages.size()); // Create the descriptor pool if (vkCreateDescriptorPool(device, &descriptorPoolCreateInfo, 0, &descriptorPool) != VK_SUCCESS) @@ -2126,10 +2199,10 @@ public: std::vector descriptorSetLayouts(swapchainImages.size(), descriptorSetLayout); VkDescriptorSetAllocateInfo descriptorSetAllocateInfo = VkDescriptorSetAllocateInfo(); - descriptorSetAllocateInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO; - descriptorSetAllocateInfo.descriptorPool = descriptorPool; - descriptorSetAllocateInfo.descriptorSetCount = static_cast(swapchainImages.size()); - descriptorSetAllocateInfo.pSetLayouts = descriptorSetLayouts.data(); + descriptorSetAllocateInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO; + descriptorSetAllocateInfo.descriptorPool = descriptorPool; + descriptorSetAllocateInfo.descriptorSetCount = static_cast(swapchainImages.size()); + descriptorSetAllocateInfo.pSetLayouts = descriptorSetLayouts.data(); descriptorSets.resize(swapchainImages.size()); @@ -2148,33 +2221,33 @@ public: // Uniform buffer binding information VkDescriptorBufferInfo descriptorBufferInfo = VkDescriptorBufferInfo(); - descriptorBufferInfo.buffer = uniformBuffers[i]; - descriptorBufferInfo.offset = 0; - descriptorBufferInfo.range = sizeof(Matrix) * 3; + descriptorBufferInfo.buffer = uniformBuffers[i]; + descriptorBufferInfo.offset = 0; + descriptorBufferInfo.range = sizeof(Matrix) * 3; - writeDescriptorSets[0] = VkWriteDescriptorSet(); - writeDescriptorSets[0].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; - writeDescriptorSets[0].dstSet = descriptorSets[i]; - writeDescriptorSets[0].dstBinding = 0; + writeDescriptorSets[0] = VkWriteDescriptorSet(); + writeDescriptorSets[0].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; + writeDescriptorSets[0].dstSet = descriptorSets[i]; + writeDescriptorSets[0].dstBinding = 0; writeDescriptorSets[0].dstArrayElement = 0; - writeDescriptorSets[0].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER; + writeDescriptorSets[0].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER; writeDescriptorSets[0].descriptorCount = 1; - writeDescriptorSets[0].pBufferInfo = &descriptorBufferInfo; + writeDescriptorSets[0].pBufferInfo = &descriptorBufferInfo; // Texture sampler binding information VkDescriptorImageInfo descriptorImageInfo = VkDescriptorImageInfo(); - descriptorImageInfo.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; - descriptorImageInfo.imageView = textureImageView; - descriptorImageInfo.sampler = textureSampler; + descriptorImageInfo.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; + descriptorImageInfo.imageView = textureImageView; + descriptorImageInfo.sampler = textureSampler; - writeDescriptorSets[1] = VkWriteDescriptorSet(); - writeDescriptorSets[1].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; - writeDescriptorSets[1].dstSet = descriptorSets[i]; - writeDescriptorSets[1].dstBinding = 1; + writeDescriptorSets[1] = VkWriteDescriptorSet(); + writeDescriptorSets[1].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; + writeDescriptorSets[1].dstSet = descriptorSets[i]; + writeDescriptorSets[1].dstBinding = 1; writeDescriptorSets[1].dstArrayElement = 0; - writeDescriptorSets[1].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; + writeDescriptorSets[1].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; writeDescriptorSets[1].descriptorCount = 1; - writeDescriptorSets[1].pImageInfo = &descriptorImageInfo; + writeDescriptorSets[1].pImageInfo = &descriptorImageInfo; // Update the desciptor set vkUpdateDescriptorSets(device, 2, writeDescriptorSets, 0, 0); @@ -2189,10 +2262,10 @@ public: // These are primary command buffers VkCommandBufferAllocateInfo commandBufferAllocateInfo = VkCommandBufferAllocateInfo(); - commandBufferAllocateInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO; - commandBufferAllocateInfo.commandPool = commandPool; - commandBufferAllocateInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; - commandBufferAllocateInfo.commandBufferCount = static_cast(commandBuffers.size()); + commandBufferAllocateInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO; + commandBufferAllocateInfo.commandPool = commandPool; + commandBufferAllocateInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; + commandBufferAllocateInfo.commandBufferCount = static_cast(commandBuffers.size()); // Allocate the command buffers from our command pool if (vkAllocateCommandBuffers(device, &commandBufferAllocateInfo, commandBuffers.data()) != VK_SUCCESS) @@ -2210,30 +2283,30 @@ public: VkClearValue clearColors[2]; // Clear color buffer to opaque black - clearColors[0] = VkClearValue(); + clearColors[0] = VkClearValue(); clearColors[0].color.float32[0] = 0.0f; clearColors[0].color.float32[1] = 0.0f; clearColors[0].color.float32[2] = 0.0f; clearColors[0].color.float32[3] = 0.0f; // Clear depth to 1.0f - clearColors[1] = VkClearValue(); - clearColors[1].depthStencil.depth = 1.0f; + clearColors[1] = VkClearValue(); + clearColors[1].depthStencil.depth = 1.0f; clearColors[1].depthStencil.stencil = 0; VkRenderPassBeginInfo renderPassBeginInfo = VkRenderPassBeginInfo(); - renderPassBeginInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO; - renderPassBeginInfo.renderPass = renderPass; - renderPassBeginInfo.renderArea.offset.x = 0; - renderPassBeginInfo.renderArea.offset.y = 0; - renderPassBeginInfo.renderArea.extent = swapchainExtent; - renderPassBeginInfo.clearValueCount = 2; - renderPassBeginInfo.pClearValues = clearColors; + renderPassBeginInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO; + renderPassBeginInfo.renderPass = renderPass; + renderPassBeginInfo.renderArea.offset.x = 0; + renderPassBeginInfo.renderArea.offset.y = 0; + renderPassBeginInfo.renderArea.extent = swapchainExtent; + renderPassBeginInfo.clearValueCount = 2; + renderPassBeginInfo.pClearValues = clearColors; // Simultaneous use: this command buffer can be resubmitted to a queue before a previous submission is completed VkCommandBufferBeginInfo commandBufferBeginInfo = VkCommandBufferBeginInfo(); - commandBufferBeginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; - commandBufferBeginInfo.flags = VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT; + commandBufferBeginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; + commandBufferBeginInfo.flags = VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT; // Set up the command buffers for each frame in flight for (std::size_t i = 0; i < commandBuffers.size(); ++i) @@ -2262,7 +2335,14 @@ public: vkCmdBindIndexBuffer(commandBuffers[i], indexBuffer, 0, VK_INDEX_TYPE_UINT16); // Bind our descriptor sets - vkCmdBindDescriptorSets(commandBuffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLayout, 0, 1, &descriptorSets[i], 0, 0); + vkCmdBindDescriptorSets(commandBuffers[i], + VK_PIPELINE_BIND_POINT_GRAPHICS, + pipelineLayout, + 0, + 1, + &descriptorSets[i], + 0, + 0); // Draw our primitives vkCmdDrawIndexed(commandBuffers[i], 36, 1, 0, 0, 0); @@ -2283,7 +2363,7 @@ public: void setupSemaphores() { VkSemaphoreCreateInfo semaphoreCreateInfo = VkSemaphoreCreateInfo(); - semaphoreCreateInfo.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO; + semaphoreCreateInfo.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO; // Create a semaphore to track when an swapchain image is available for each frame in flight for (std::size_t i = 0; i < maxFramesInFlight; ++i) @@ -2317,8 +2397,8 @@ public: { // Create the fences in the signaled state VkFenceCreateInfo fenceCreateInfo = VkFenceCreateInfo(); - fenceCreateInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO; - fenceCreateInfo.flags = VK_FENCE_CREATE_SIGNALED_BIT; + fenceCreateInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO; + fenceCreateInfo.flags = VK_FENCE_CREATE_SIGNALED_BIT; // Create a fence to track when queue submission is complete for each frame in flight for (std::size_t i = 0; i < maxFramesInFlight; ++i) @@ -2338,12 +2418,7 @@ public: void updateUniformBuffer(float elapsed) { // Construct the model matrix - Matrix model = { - { 1.0f, 0.0f, 0.0f, 0.0f }, - { 0.0f, 1.0f, 0.0f, 0.0f }, - { 0.0f, 0.0f, 1.0f, 0.0f }, - { 0.0f, 0.0f, 0.0f, 1.0f } - }; + Matrix model = {{1.0f, 0.0f, 0.0f, 0.0f}, {0.0f, 1.0f, 0.0f, 0.0f}, {0.0f, 0.0f, 1.0f, 0.0f}, {0.0f, 0.0f, 0.0f, 1.0f}}; matrixRotateX(model, sf::degrees(elapsed * 59.0f)); matrixRotateY(model, sf::degrees(elapsed * 83.0f)); @@ -2351,9 +2426,9 @@ public: // Translate the model based on the mouse position sf::Vector2f mousePosition = sf::Vector2f(sf::Mouse::getPosition(window)); - sf::Vector2f windowSize = sf::Vector2f(window.getSize()); - float x = clamp( mousePosition.x * 2.f / windowSize.x - 1.f, -1.0f, 1.0f) * 2.0f; - float y = clamp(-mousePosition.y * 2.f / windowSize.y + 1.f, -1.0f, 1.0f) * 1.5f; + sf::Vector2f windowSize = sf::Vector2f(window.getSize()); + float x = clamp(mousePosition.x * 2.f / windowSize.x - 1.f, -1.0f, 1.0f) * 2.0f; + float y = clamp(-mousePosition.y * 2.f / windowSize.y + 1.f, -1.0f, 1.0f) * 1.5f; model[3][0] -= x; model[3][2] += y; @@ -2368,10 +2443,10 @@ public: matrixLookAt(view, eye, center, up); // Construct the projection matrix - const sf::Angle fov = sf::degrees(45); - const float aspect = static_cast(swapchainExtent.width) / static_cast(swapchainExtent.height); - const float nearPlane = 0.1f; - const float farPlane = 10.0f; + const sf::Angle fov = sf::degrees(45); + const float aspect = static_cast(swapchainExtent.width) / static_cast(swapchainExtent.height); + const float nearPlane = 0.1f; + const float farPlane = 10.0f; Matrix projection; @@ -2380,15 +2455,16 @@ public: char* ptr; // Map the current frame's uniform buffer into our address space - if (vkMapMemory(device, uniformBuffersMemory[currentFrame], 0, sizeof(Matrix) * 3, 0, reinterpret_cast(&ptr)) != VK_SUCCESS) + if (vkMapMemory(device, uniformBuffersMemory[currentFrame], 0, sizeof(Matrix) * 3, 0, reinterpret_cast(&ptr)) != + VK_SUCCESS) { vulkanAvailable = false; return; } // Copy the matrix data into the current frame's uniform buffer - std::memcpy(ptr + sizeof(Matrix) * 0, model, sizeof(Matrix)); - std::memcpy(ptr + sizeof(Matrix) * 1, view, sizeof(Matrix)); + std::memcpy(ptr + sizeof(Matrix) * 0, model, sizeof(Matrix)); + std::memcpy(ptr + sizeof(Matrix) * 1, view, sizeof(Matrix)); std::memcpy(ptr + sizeof(Matrix) * 2, projection, sizeof(Matrix)); // Unmap the buffer @@ -2404,7 +2480,12 @@ public: { // Get the next image in the swapchain - VkResult result = vkAcquireNextImageKHR(device, swapchain, std::numeric_limits::max(), imageAvailableSemaphores[currentFrame], VK_NULL_HANDLE, &imageIndex); + VkResult result = vkAcquireNextImageKHR(device, + swapchain, + std::numeric_limits::max(), + imageAvailableSemaphores[currentFrame], + VK_NULL_HANDLE, + &imageIndex); // Check if we need to re-create the swapchain (e.g. if the window was resized) if (result == VK_ERROR_OUT_OF_DATE_KHR) @@ -2414,7 +2495,8 @@ public: return; } - if ((result != VK_SUCCESS) && (result != VK_TIMEOUT) && (result != VK_NOT_READY) && (result != VK_SUBOPTIMAL_KHR)) + if ((result != VK_SUCCESS) && (result != VK_TIMEOUT) && (result != VK_NOT_READY) && + (result != VK_SUBOPTIMAL_KHR)) { vulkanAvailable = false; return; @@ -2425,15 +2507,15 @@ public: VkPipelineStageFlags waitStages = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; // Signal the render finished semaphore once the queue has been processed - VkSubmitInfo submitInfo = VkSubmitInfo(); - submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; - submitInfo.waitSemaphoreCount = 1; - submitInfo.pWaitSemaphores = &imageAvailableSemaphores[currentFrame]; - submitInfo.pWaitDstStageMask = &waitStages; - submitInfo.commandBufferCount = 1; - submitInfo.pCommandBuffers = &commandBuffers[imageIndex]; + VkSubmitInfo submitInfo = VkSubmitInfo(); + submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; + submitInfo.waitSemaphoreCount = 1; + submitInfo.pWaitSemaphores = &imageAvailableSemaphores[currentFrame]; + submitInfo.pWaitDstStageMask = &waitStages; + submitInfo.commandBufferCount = 1; + submitInfo.pCommandBuffers = &commandBuffers[imageIndex]; submitInfo.signalSemaphoreCount = 1; - submitInfo.pSignalSemaphores = &renderFinishedSemaphores[currentFrame]; + submitInfo.pSignalSemaphores = &renderFinishedSemaphores[currentFrame]; vkResetFences(device, 1, &fences[currentFrame]); @@ -2444,13 +2526,13 @@ public: } // Wait for rendering to complete before presenting - VkPresentInfoKHR presentInfo = VkPresentInfoKHR(); - presentInfo.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR; + VkPresentInfoKHR presentInfo = VkPresentInfoKHR(); + presentInfo.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR; presentInfo.waitSemaphoreCount = 1; - presentInfo.pWaitSemaphores = &renderFinishedSemaphores[currentFrame]; - presentInfo.swapchainCount = 1; - presentInfo.pSwapchains = &swapchain; - presentInfo.pImageIndices = &imageIndex; + presentInfo.pWaitSemaphores = &renderFinishedSemaphores[currentFrame]; + presentInfo.swapchainCount = 1; + presentInfo.pSwapchains = &swapchain; + presentInfo.pImageIndices = &imageIndex; { // Queue presentation @@ -2514,50 +2596,50 @@ private: bool vulkanAvailable; const unsigned int maxFramesInFlight; - unsigned int currentFrame; - bool swapchainOutOfDate; + unsigned int currentFrame; + bool swapchainOutOfDate; - VkInstance instance; - VkDebugReportCallbackEXT debugReportCallback; - VkSurfaceKHR surface; - VkPhysicalDevice gpu; - int queueFamilyIndex; - VkDevice device; - VkQueue queue; - VkSurfaceFormatKHR swapchainFormat; - VkExtent2D swapchainExtent; - VkSwapchainKHR swapchain; - std::vector swapchainImages; - std::vector swapchainImageViews; - VkFormat depthFormat; - VkImage depthImage; - VkDeviceMemory depthImageMemory; - VkImageView depthImageView; - VkShaderModule vertexShaderModule; - VkShaderModule fragmentShaderModule; + VkInstance instance; + VkDebugReportCallbackEXT debugReportCallback; + VkSurfaceKHR surface; + VkPhysicalDevice gpu; + int queueFamilyIndex; + VkDevice device; + VkQueue queue; + VkSurfaceFormatKHR swapchainFormat; + VkExtent2D swapchainExtent; + VkSwapchainKHR swapchain; + std::vector swapchainImages; + std::vector swapchainImageViews; + VkFormat depthFormat; + VkImage depthImage; + VkDeviceMemory depthImageMemory; + VkImageView depthImageView; + VkShaderModule vertexShaderModule; + VkShaderModule fragmentShaderModule; VkPipelineShaderStageCreateInfo shaderStages[2]; - VkDescriptorSetLayout descriptorSetLayout; - VkPipelineLayout pipelineLayout; - VkRenderPass renderPass; - VkPipeline graphicsPipeline; - std::vector swapchainFramebuffers; - VkCommandPool commandPool; - VkBuffer vertexBuffer; - VkDeviceMemory vertexBufferMemory; - VkBuffer indexBuffer; - VkDeviceMemory indexBufferMemory; - std::vector uniformBuffers; - std::vector uniformBuffersMemory; - VkImage textureImage; - VkDeviceMemory textureImageMemory; - VkImageView textureImageView; - VkSampler textureSampler; - VkDescriptorPool descriptorPool; - std::vector descriptorSets; - std::vector commandBuffers; - std::vector imageAvailableSemaphores; - std::vector renderFinishedSemaphores; - std::vector fences; + VkDescriptorSetLayout descriptorSetLayout; + VkPipelineLayout pipelineLayout; + VkRenderPass renderPass; + VkPipeline graphicsPipeline; + std::vector swapchainFramebuffers; + VkCommandPool commandPool; + VkBuffer vertexBuffer; + VkDeviceMemory vertexBufferMemory; + VkBuffer indexBuffer; + VkDeviceMemory indexBufferMemory; + std::vector uniformBuffers; + std::vector uniformBuffersMemory; + VkImage textureImage; + VkDeviceMemory textureImageMemory; + VkImageView textureImageView; + VkSampler textureSampler; + VkDescriptorPool descriptorPool; + std::vector descriptorSets; + std::vector commandBuffers; + std::vector imageAvailableSemaphores; + std::vector renderFinishedSemaphores; + std::vector fences; }; diff --git a/examples/win32/Win32.cpp b/examples/win32/Win32.cpp index a779c2355..5c9bf10b7 100644 --- a/examples/win32/Win32.cpp +++ b/examples/win32/Win32.cpp @@ -6,8 +6,8 @@ #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN #endif -#include #include +#include HWND button; @@ -69,14 +69,44 @@ int main() RegisterClass(&windowClass); // Let's create the main window - HWND window = CreateWindow(TEXT("SFML App"), TEXT("SFML Win32"), WS_SYSMENU | WS_VISIBLE, 200, 200, 660, 520, nullptr, nullptr, instance, nullptr); + HWND window = CreateWindow(TEXT("SFML App"), + TEXT("SFML Win32"), + WS_SYSMENU | WS_VISIBLE, + 200, + 200, + 660, + 520, + nullptr, + nullptr, + instance, + nullptr); // Add a button for exiting button = CreateWindow(TEXT("BUTTON"), TEXT("Quit"), WS_CHILD | WS_VISIBLE, 560, 440, 80, 40, window, nullptr, instance, nullptr); // Let's create two SFML views - HWND view1 = CreateWindow(TEXT("STATIC"), nullptr, WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS, 20, 20, 300, 400, window, nullptr, instance, nullptr); - HWND view2 = CreateWindow(TEXT("STATIC"), nullptr, WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS, 340, 20, 300, 400, window, nullptr, instance, nullptr); + HWND view1 = CreateWindow(TEXT("STATIC"), + nullptr, + WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS, + 20, + 20, + 300, + 400, + window, + nullptr, + instance, + nullptr); + HWND view2 = CreateWindow(TEXT("STATIC"), + nullptr, + WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS, + 340, + 20, + 300, + 400, + window, + nullptr, + instance, + nullptr); sf::RenderWindow SFMLView1(view1); sf::RenderWindow SFMLView2(view2); diff --git a/examples/window/Window.cpp b/examples/window/Window.cpp index e1a2a312f..85251c30c 100644 --- a/examples/window/Window.cpp +++ b/examples/window/Window.cpp @@ -2,6 +2,7 @@ // Headers //////////////////////////////////////////////////////////// #include + #include #define GLAD_GL_IMPLEMENTATION @@ -12,8 +13,8 @@ #endif #include -#include #include +#include //////////////////////////////////////////////////////////// /// Entry point of application diff --git a/include/SFML/Audio.hpp b/include/SFML/Audio.hpp index 597a94396..e69aaadad 100644 --- a/include/SFML/Audio.hpp +++ b/include/SFML/Audio.hpp @@ -29,7 +29,6 @@ // Headers //////////////////////////////////////////////////////////// -#include #include #include #include @@ -43,6 +42,7 @@ #include #include #include +#include #endif // SFML_AUDIO_HPP diff --git a/include/SFML/Audio/AlResource.hpp b/include/SFML/Audio/AlResource.hpp index 9f22ea793..85efd7f03 100644 --- a/include/SFML/Audio/AlResource.hpp +++ b/include/SFML/Audio/AlResource.hpp @@ -40,7 +40,6 @@ namespace sf class SFML_AUDIO_API AlResource { protected: - //////////////////////////////////////////////////////////// /// \brief Default constructor /// diff --git a/include/SFML/Audio/Export.hpp b/include/SFML/Audio/Export.hpp index 812fd5e48..8557154b3 100644 --- a/include/SFML/Audio/Export.hpp +++ b/include/SFML/Audio/Export.hpp @@ -36,11 +36,11 @@ //////////////////////////////////////////////////////////// #if defined(SFML_AUDIO_EXPORTS) - #define SFML_AUDIO_API SFML_API_EXPORT +#define SFML_AUDIO_API SFML_API_EXPORT #else - #define SFML_AUDIO_API SFML_API_IMPORT +#define SFML_AUDIO_API SFML_API_IMPORT #endif diff --git a/include/SFML/Audio/InputSoundFile.hpp b/include/SFML/Audio/InputSoundFile.hpp index 15ab376d9..baabe08ea 100644 --- a/include/SFML/Audio/InputSoundFile.hpp +++ b/include/SFML/Audio/InputSoundFile.hpp @@ -29,10 +29,11 @@ // Headers //////////////////////////////////////////////////////////// #include + +#include #include #include #include -#include namespace sf @@ -48,7 +49,6 @@ class SoundFileReader; class SFML_AUDIO_API InputSoundFile { public: - //////////////////////////////////////////////////////////// /// \brief Default constructor /// diff --git a/include/SFML/Audio/Listener.hpp b/include/SFML/Audio/Listener.hpp index c017f0120..6d2cf6475 100644 --- a/include/SFML/Audio/Listener.hpp +++ b/include/SFML/Audio/Listener.hpp @@ -29,6 +29,7 @@ // Headers //////////////////////////////////////////////////////////// #include + #include @@ -42,7 +43,6 @@ namespace sf class SFML_AUDIO_API Listener { public: - //////////////////////////////////////////////////////////// /// \brief Change the global volume of all the sounds and musics /// diff --git a/include/SFML/Audio/Music.hpp b/include/SFML/Audio/Music.hpp index 5a0e00ca7..b4bb5aee7 100644 --- a/include/SFML/Audio/Music.hpp +++ b/include/SFML/Audio/Music.hpp @@ -29,8 +29,10 @@ // Headers //////////////////////////////////////////////////////////// #include -#include + #include +#include + #include #include #include @@ -48,7 +50,6 @@ class InputStream; class SFML_AUDIO_API Music : public SoundStream { public: - //////////////////////////////////////////////////////////// /// \brief Structure defining a time range using the template type /// @@ -62,7 +63,6 @@ public: //////////////////////////////////////////////////////////// Span() { - } //////////////////////////////////////////////////////////// @@ -72,11 +72,8 @@ public: /// \param len Initial Length /// //////////////////////////////////////////////////////////// - Span(T off, T len): - offset(off), - length(len) + Span(T off, T len) : offset(off), length(len) { - } T offset; //!< The beginning offset of the time range @@ -211,7 +208,6 @@ public: void setLoopPoints(TimeSpan timePoints); protected: - //////////////////////////////////////////////////////////// /// \brief Request a new chunk of audio samples from the stream source /// @@ -246,7 +242,6 @@ protected: Int64 onLoop() override; private: - //////////////////////////////////////////////////////////// /// \brief Initialize the internal state after loading a new music /// diff --git a/include/SFML/Audio/OutputSoundFile.hpp b/include/SFML/Audio/OutputSoundFile.hpp index c750d6352..ab25a5226 100644 --- a/include/SFML/Audio/OutputSoundFile.hpp +++ b/include/SFML/Audio/OutputSoundFile.hpp @@ -29,6 +29,7 @@ // Headers //////////////////////////////////////////////////////////// #include + #include #include #include @@ -45,7 +46,6 @@ class SoundFileWriter; class SFML_AUDIO_API OutputSoundFile { public: - //////////////////////////////////////////////////////////// /// \brief Default constructor /// @@ -102,7 +102,6 @@ public: void close(); private: - //////////////////////////////////////////////////////////// // Member data //////////////////////////////////////////////////////////// diff --git a/include/SFML/Audio/Sound.hpp b/include/SFML/Audio/Sound.hpp index 3b511d080..25b07bb8a 100644 --- a/include/SFML/Audio/Sound.hpp +++ b/include/SFML/Audio/Sound.hpp @@ -29,7 +29,9 @@ // Headers //////////////////////////////////////////////////////////// #include + #include + #include @@ -45,7 +47,6 @@ class SoundBuffer; class SFML_AUDIO_API Sound : public SoundSource { public: - //////////////////////////////////////////////////////////// /// \brief Default constructor /// @@ -199,7 +200,7 @@ public: /// \return Reference to self /// //////////////////////////////////////////////////////////// - Sound& operator =(const Sound& right); + Sound& operator=(const Sound& right); //////////////////////////////////////////////////////////// /// \brief Reset the internal buffer of the sound @@ -213,7 +214,6 @@ public: void resetBuffer(); private: - //////////////////////////////////////////////////////////// // Member data //////////////////////////////////////////////////////////// diff --git a/include/SFML/Audio/SoundBuffer.hpp b/include/SFML/Audio/SoundBuffer.hpp index 69c94323f..e5a055470 100644 --- a/include/SFML/Audio/SoundBuffer.hpp +++ b/include/SFML/Audio/SoundBuffer.hpp @@ -29,12 +29,14 @@ // Headers //////////////////////////////////////////////////////////// #include + #include #include + #include #include -#include #include +#include namespace sf @@ -50,7 +52,6 @@ class InputStream; class SFML_AUDIO_API SoundBuffer : AlResource { public: - //////////////////////////////////////////////////////////// /// \brief Default constructor /// @@ -222,10 +223,9 @@ public: /// \return Reference to self /// //////////////////////////////////////////////////////////// - SoundBuffer& operator =(const SoundBuffer& right); + SoundBuffer& operator=(const SoundBuffer& right); private: - friend class Sound; //////////////////////////////////////////////////////////// @@ -268,7 +268,7 @@ private: //////////////////////////////////////////////////////////// // Types //////////////////////////////////////////////////////////// - using SoundList = std::unordered_set; //!< Set of unique sound instances + using SoundList = std::unordered_set; //!< Set of unique sound instances //////////////////////////////////////////////////////////// // Member data diff --git a/include/SFML/Audio/SoundBufferRecorder.hpp b/include/SFML/Audio/SoundBufferRecorder.hpp index 0d861cf1a..a20b99d61 100644 --- a/include/SFML/Audio/SoundBufferRecorder.hpp +++ b/include/SFML/Audio/SoundBufferRecorder.hpp @@ -29,8 +29,10 @@ // Headers //////////////////////////////////////////////////////////// #include + #include #include + #include @@ -44,7 +46,6 @@ namespace sf class SFML_AUDIO_API SoundBufferRecorder : public SoundRecorder { public: - //////////////////////////////////////////////////////////// /// \brief destructor /// @@ -65,7 +66,6 @@ public: const SoundBuffer& getBuffer() const; protected: - //////////////////////////////////////////////////////////// /// \brief Start capturing audio data /// @@ -92,7 +92,6 @@ protected: void onStop() override; private: - //////////////////////////////////////////////////////////// // Member data //////////////////////////////////////////////////////////// diff --git a/include/SFML/Audio/SoundFileFactory.hpp b/include/SFML/Audio/SoundFileFactory.hpp index 5008bef9b..309932884 100644 --- a/include/SFML/Audio/SoundFileFactory.hpp +++ b/include/SFML/Audio/SoundFileFactory.hpp @@ -29,6 +29,7 @@ // Headers //////////////////////////////////////////////////////////// #include + #include #include #include @@ -48,7 +49,6 @@ class SoundFileWriter; class SFML_AUDIO_API SoundFileFactory { public: - //////////////////////////////////////////////////////////// /// \brief Register a new reader /// @@ -133,7 +133,6 @@ public: static std::unique_ptr createWriterFromFilename(const std::filesystem::path& filename); private: - //////////////////////////////////////////////////////////// // Types //////////////////////////////////////////////////////////// diff --git a/include/SFML/Audio/SoundFileFactory.inl b/include/SFML/Audio/SoundFileFactory.inl index cb00602ff..669ce82f7 100644 --- a/include/SFML/Audio/SoundFileFactory.inl +++ b/include/SFML/Audio/SoundFileFactory.inl @@ -31,9 +31,17 @@ namespace sf { namespace priv { - template std::unique_ptr createReader() { return std::make_unique(); } - template std::unique_ptr createWriter() { return std::make_unique(); } +template +std::unique_ptr createReader() +{ + return std::make_unique(); } +template +std::unique_ptr createWriter() +{ + return std::make_unique(); +} +} // namespace priv //////////////////////////////////////////////////////////// template @@ -44,7 +52,7 @@ void SoundFileFactory::registerReader() // Create a new factory with the functions provided by the class ReaderFactory factory; - factory.check = &T::check; + factory.check = &T::check; factory.create = &priv::createReader; // Add it @@ -75,7 +83,7 @@ void SoundFileFactory::registerWriter() // Create a new factory with the functions provided by the class WriterFactory factory; - factory.check = &T::check; + factory.check = &T::check; factory.create = &priv::createWriter; // Add it diff --git a/include/SFML/Audio/SoundFileReader.hpp b/include/SFML/Audio/SoundFileReader.hpp index 32158944a..52be01956 100644 --- a/include/SFML/Audio/SoundFileReader.hpp +++ b/include/SFML/Audio/SoundFileReader.hpp @@ -57,7 +57,9 @@ public: /// \brief Virtual destructor /// //////////////////////////////////////////////////////////// - virtual ~SoundFileReader() {} + virtual ~SoundFileReader() + { + } //////////////////////////////////////////////////////////// /// \brief Open a sound file for reading diff --git a/include/SFML/Audio/SoundFileWriter.hpp b/include/SFML/Audio/SoundFileWriter.hpp index 3afeed65a..75c0e1206 100644 --- a/include/SFML/Audio/SoundFileWriter.hpp +++ b/include/SFML/Audio/SoundFileWriter.hpp @@ -29,6 +29,7 @@ // Headers //////////////////////////////////////////////////////////// #include + #include #include @@ -42,12 +43,13 @@ namespace sf class SFML_AUDIO_API SoundFileWriter { public: - //////////////////////////////////////////////////////////// /// \brief Virtual destructor /// //////////////////////////////////////////////////////////// - virtual ~SoundFileWriter() {} + virtual ~SoundFileWriter() + { + } //////////////////////////////////////////////////////////// /// \brief Open a sound file for writing @@ -59,7 +61,9 @@ public: /// \return True if the file was successfully opened /// //////////////////////////////////////////////////////////// - [[nodiscard]] virtual bool open(const std::filesystem::path& filename, unsigned int sampleRate, unsigned int channelCount) = 0; + [[nodiscard]] virtual bool open(const std::filesystem::path& filename, + unsigned int sampleRate, + unsigned int channelCount) = 0; //////////////////////////////////////////////////////////// /// \brief Write audio samples to the open file diff --git a/include/SFML/Audio/SoundRecorder.hpp b/include/SFML/Audio/SoundRecorder.hpp index 3b906121e..2aef0c155 100644 --- a/include/SFML/Audio/SoundRecorder.hpp +++ b/include/SFML/Audio/SoundRecorder.hpp @@ -29,11 +29,13 @@ // Headers //////////////////////////////////////////////////////////// #include + #include #include -#include + #include #include +#include namespace sf @@ -45,7 +47,6 @@ namespace sf class SFML_AUDIO_API SoundRecorder : AlResource { public: - //////////////////////////////////////////////////////////// /// \brief destructor /// @@ -186,7 +187,6 @@ public: static bool isAvailable(); protected: - //////////////////////////////////////////////////////////// /// \brief Default constructor /// @@ -254,7 +254,6 @@ protected: virtual void onStop(); private: - //////////////////////////////////////////////////////////// /// \brief Function called as the entry point of the thread /// @@ -303,13 +302,13 @@ private: //////////////////////////////////////////////////////////// // Member data //////////////////////////////////////////////////////////// - std::thread m_thread; //!< Thread running the background recording task - std::vector m_samples; //!< Buffer to store captured samples - unsigned int m_sampleRate; //!< Sample rate - Time m_processingInterval; //!< Time period between calls to onProcessSamples - bool m_isCapturing; //!< Capturing state - std::string m_deviceName; //!< Name of the audio capture device - unsigned int m_channelCount; //!< Number of recording channels + std::thread m_thread; //!< Thread running the background recording task + std::vector m_samples; //!< Buffer to store captured samples + unsigned int m_sampleRate; //!< Sample rate + Time m_processingInterval; //!< Time period between calls to onProcessSamples + bool m_isCapturing; //!< Capturing state + std::string m_deviceName; //!< Name of the audio capture device + unsigned int m_channelCount; //!< Number of recording channels }; } // namespace sf diff --git a/include/SFML/Audio/SoundSource.hpp b/include/SFML/Audio/SoundSource.hpp index a6b2fb02c..7f70dd96a 100644 --- a/include/SFML/Audio/SoundSource.hpp +++ b/include/SFML/Audio/SoundSource.hpp @@ -29,6 +29,7 @@ // Headers //////////////////////////////////////////////////////////// #include + #include #include @@ -42,7 +43,6 @@ namespace sf class SFML_AUDIO_API SoundSource : AlResource { public: - //////////////////////////////////////////////////////////// /// \brief Enumeration of the sound source states /// @@ -232,7 +232,7 @@ public: /// \return Reference to self /// //////////////////////////////////////////////////////////// - SoundSource& operator =(const SoundSource& right); + SoundSource& operator=(const SoundSource& right); //////////////////////////////////////////////////////////// /// \brief Start or resume playing the sound source @@ -278,7 +278,6 @@ public: virtual Status getStatus() const; protected: - //////////////////////////////////////////////////////////// /// \brief Default constructor /// diff --git a/include/SFML/Audio/SoundStream.hpp b/include/SFML/Audio/SoundStream.hpp index 8a9d3cb43..1628d8ec9 100644 --- a/include/SFML/Audio/SoundStream.hpp +++ b/include/SFML/Audio/SoundStream.hpp @@ -29,8 +29,10 @@ // Headers //////////////////////////////////////////////////////////// #include + #include #include + #include #include #include @@ -45,7 +47,6 @@ namespace sf class SFML_AUDIO_API SoundStream : public SoundSource { public: - //////////////////////////////////////////////////////////// /// \brief Structure defining a chunk of audio data to stream /// @@ -179,7 +180,6 @@ public: bool getLoop() const; protected: - enum { NoLoop = -1 //!< "Invalid" endSeeks value, telling us to continue uninterrupted @@ -266,7 +266,6 @@ protected: void setProcessingInterval(Time interval); private: - //////////////////////////////////////////////////////////// /// \brief Function called as the entry point of the thread /// @@ -331,25 +330,25 @@ private: enum { - BufferCount = 3, //!< Number of audio buffers used by the streaming loop - BufferRetries = 2 //!< Number of retries (excluding initial try) for onGetData() + BufferCount = 3, //!< Number of audio buffers used by the streaming loop + BufferRetries = 2 //!< Number of retries (excluding initial try) for onGetData() }; //////////////////////////////////////////////////////////// // Member data //////////////////////////////////////////////////////////// - std::thread m_thread; //!< Thread running the background tasks - mutable std::recursive_mutex m_threadMutex; //!< Thread mutex - Status m_threadStartState; //!< State the thread starts in (Playing, Paused, Stopped) - bool m_isStreaming; //!< Streaming state (true = playing, false = stopped) - unsigned int m_buffers[BufferCount]; //!< Sound buffers used to store temporary audio data - unsigned int m_channelCount; //!< Number of channels (1 = mono, 2 = stereo, ...) - unsigned int m_sampleRate; //!< Frequency (samples / second) - Int32 m_format; //!< Format of the internal sound buffers - bool m_loop; //!< Loop flag (true to loop, false to play once) - Uint64 m_samplesProcessed; //!< Number of samples processed since beginning of the stream + std::thread m_thread; //!< Thread running the background tasks + mutable std::recursive_mutex m_threadMutex; //!< Thread mutex + Status m_threadStartState; //!< State the thread starts in (Playing, Paused, Stopped) + bool m_isStreaming; //!< Streaming state (true = playing, false = stopped) + unsigned int m_buffers[BufferCount]; //!< Sound buffers used to store temporary audio data + unsigned int m_channelCount; //!< Number of channels (1 = mono, 2 = stereo, ...) + unsigned int m_sampleRate; //!< Frequency (samples / second) + Int32 m_format; //!< Format of the internal sound buffers + bool m_loop; //!< Loop flag (true to loop, false to play once) + Uint64 m_samplesProcessed; //!< Number of samples processed since beginning of the stream Int64 m_bufferSeeks[BufferCount]; //!< If buffer is an "end buffer", holds next seek position, else NoLoop. For play offset calculation. - Time m_processingInterval; //!< Interval for checking and filling the internal sound buffers. + Time m_processingInterval; //!< Interval for checking and filling the internal sound buffers. }; } // namespace sf diff --git a/include/SFML/Config.hpp b/include/SFML/Config.hpp index 4bec8cb2f..7a1d0bfc7 100644 --- a/include/SFML/Config.hpp +++ b/include/SFML/Config.hpp @@ -35,9 +35,9 @@ //////////////////////////////////////////////////////////// // Define the SFML version //////////////////////////////////////////////////////////// -#define SFML_VERSION_MAJOR 3 -#define SFML_VERSION_MINOR 0 -#define SFML_VERSION_PATCH 0 +#define SFML_VERSION_MAJOR 3 +#define SFML_VERSION_MINOR 0 +#define SFML_VERSION_PATCH 0 #define SFML_VERSION_IS_RELEASE false @@ -47,73 +47,73 @@ //////////////////////////////////////////////////////////// #if defined(_WIN32) - // Windows - #define SFML_SYSTEM_WINDOWS - #ifndef NOMINMAX - #define NOMINMAX - #endif +// Windows +#define SFML_SYSTEM_WINDOWS +#ifndef NOMINMAX +#define NOMINMAX +#endif #elif defined(__APPLE__) && defined(__MACH__) - // Apple platform, see which one it is - #include "TargetConditionals.h" +// Apple platform, see which one it is +#include "TargetConditionals.h" - #if TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR +#if TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR - // iOS - #define SFML_SYSTEM_IOS +// iOS +#define SFML_SYSTEM_IOS - #elif TARGET_OS_MAC +#elif TARGET_OS_MAC - // MacOS - #define SFML_SYSTEM_MACOS - - #else - - // Unsupported Apple system - #error This Apple operating system is not supported by SFML library - - #endif - -#elif defined(__unix__) - - // UNIX system, see which one it is - #if defined(__ANDROID__) - - // Android - #define SFML_SYSTEM_ANDROID - - #elif defined(__linux__) - - // Linux - #define SFML_SYSTEM_LINUX - - #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) - - // FreeBSD - #define SFML_SYSTEM_FREEBSD - - #elif defined(__OpenBSD__) - - // OpenBSD - #define SFML_SYSTEM_OPENBSD - - #elif defined(__NetBSD__) - - // NetBSD - #define SFML_SYSTEM_NETBSD - - #else - - // Unsupported UNIX system - #error This UNIX operating system is not supported by SFML library - - #endif +// MacOS +#define SFML_SYSTEM_MACOS #else - // Unsupported system - #error This operating system is not supported by SFML library +// Unsupported Apple system +#error This Apple operating system is not supported by SFML library + +#endif + +#elif defined(__unix__) + +// UNIX system, see which one it is +#if defined(__ANDROID__) + +// Android +#define SFML_SYSTEM_ANDROID + +#elif defined(__linux__) + +// Linux +#define SFML_SYSTEM_LINUX + +#elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) + +// FreeBSD +#define SFML_SYSTEM_FREEBSD + +#elif defined(__OpenBSD__) + +// OpenBSD +#define SFML_SYSTEM_OPENBSD + +#elif defined(__NetBSD__) + +// NetBSD +#define SFML_SYSTEM_NETBSD + +#else + +// Unsupported UNIX system +#error This UNIX operating system is not supported by SFML library + +#endif + +#else + +// Unsupported system +#error This operating system is not supported by SFML library #endif @@ -123,7 +123,7 @@ //////////////////////////////////////////////////////////// #if !defined(NDEBUG) - #define SFML_DEBUG +#define SFML_DEBUG #endif @@ -133,31 +133,31 @@ //////////////////////////////////////////////////////////// #if !defined(SFML_STATIC) - #if defined(SFML_SYSTEM_WINDOWS) +#if defined(SFML_SYSTEM_WINDOWS) - // Windows compilers need specific (and different) keywords for export and import - #define SFML_API_EXPORT __declspec(dllexport) - #define SFML_API_IMPORT __declspec(dllimport) +// Windows compilers need specific (and different) keywords for export and import +#define SFML_API_EXPORT __declspec(dllexport) +#define SFML_API_IMPORT __declspec(dllimport) - // For Visual C++ compilers, we also need to turn off this annoying C4251 warning - #ifdef _MSC_VER +// For Visual C++ compilers, we also need to turn off this annoying C4251 warning +#ifdef _MSC_VER - #pragma warning(disable: 4251) +#pragma warning(disable : 4251) - #endif +#endif - #else // Linux, FreeBSD, Mac OS X +#else // Linux, FreeBSD, Mac OS X - #define SFML_API_EXPORT __attribute__ ((__visibility__ ("default"))) - #define SFML_API_IMPORT __attribute__ ((__visibility__ ("default"))) +#define SFML_API_EXPORT __attribute__((__visibility__("default"))) +#define SFML_API_IMPORT __attribute__((__visibility__("default"))) - #endif +#endif #else - // Static build doesn't need import/export macros - #define SFML_API_EXPORT - #define SFML_API_IMPORT +// Static build doesn't need import/export macros +#define SFML_API_EXPORT +#define SFML_API_IMPORT #endif @@ -167,21 +167,21 @@ //////////////////////////////////////////////////////////// namespace sf { - // 8 bits integer types - using Int8 = std::int8_t; - using Uint8 = std::uint8_t; +// 8 bits integer types +using Int8 = std::int8_t; +using Uint8 = std::uint8_t; - // 16 bits integer types - using Int16 = std::int16_t; - using Uint16 = std::uint16_t; +// 16 bits integer types +using Int16 = std::int16_t; +using Uint16 = std::uint16_t; - // 32 bits integer types - using Int32 = std::int32_t; - using Uint32 = std::uint32_t; +// 32 bits integer types +using Int32 = std::int32_t; +using Uint32 = std::uint32_t; - // 64 bits integer types - using Int64 = std::int64_t; - using Uint64 = std::uint64_t; +// 64 bits integer types +using Int64 = std::int64_t; +using Uint64 = std::uint64_t; } // namespace sf diff --git a/include/SFML/GpuPreference.hpp b/include/SFML/GpuPreference.hpp index 84c9509c5..565cbb10d 100644 --- a/include/SFML/GpuPreference.hpp +++ b/include/SFML/GpuPreference.hpp @@ -60,13 +60,13 @@ //////////////////////////////////////////////////////////// #if defined(SFML_SYSTEM_WINDOWS) - #define SFML_DEFINE_DISCRETE_GPU_PREFERENCE \ - extern "C" __declspec(dllexport) unsigned long NvOptimusEnablement = 1; \ - extern "C" __declspec(dllexport) unsigned long AmdPowerXpressRequestHighPerformance = 1; +#define SFML_DEFINE_DISCRETE_GPU_PREFERENCE \ + extern "C" __declspec(dllexport) unsigned long NvOptimusEnablement = 1; \ + extern "C" __declspec(dllexport) unsigned long AmdPowerXpressRequestHighPerformance = 1; #else - #define SFML_DEFINE_DISCRETE_GPU_PREFERENCE +#define SFML_DEFINE_DISCRETE_GPU_PREFERENCE #endif diff --git a/include/SFML/Graphics.hpp b/include/SFML/Graphics.hpp index ff82d0ce1..95498c2fa 100644 --- a/include/SFML/Graphics.hpp +++ b/include/SFML/Graphics.hpp @@ -29,7 +29,6 @@ // Headers //////////////////////////////////////////////////////////// -#include #include #include #include @@ -56,6 +55,7 @@ #include #include #include +#include #endif // SFML_GRAPHICS_HPP diff --git a/include/SFML/Graphics/BlendMode.hpp b/include/SFML/Graphics/BlendMode.hpp index d6775b7f5..da21efba5 100644 --- a/include/SFML/Graphics/BlendMode.hpp +++ b/include/SFML/Graphics/BlendMode.hpp @@ -107,9 +107,12 @@ struct SFML_GRAPHICS_API BlendMode /// \param alphaBlendEquation Specifies how to combine the source and destination alphas. /// //////////////////////////////////////////////////////////// - BlendMode(Factor colorSourceFactor, Factor colorDestinationFactor, - Equation colorBlendEquation, Factor alphaSourceFactor, - Factor alphaDestinationFactor, Equation alphaBlendEquation); + BlendMode(Factor colorSourceFactor, + Factor colorDestinationFactor, + Equation colorBlendEquation, + Factor alphaSourceFactor, + Factor alphaDestinationFactor, + Equation alphaBlendEquation); //////////////////////////////////////////////////////////// // Member Data @@ -132,7 +135,7 @@ struct SFML_GRAPHICS_API BlendMode /// \return True if blending modes are equal, false if they are different /// //////////////////////////////////////////////////////////// -SFML_GRAPHICS_API bool operator ==(const BlendMode& left, const BlendMode& right); +SFML_GRAPHICS_API bool operator==(const BlendMode& left, const BlendMode& right); //////////////////////////////////////////////////////////// /// \relates BlendMode @@ -144,7 +147,7 @@ SFML_GRAPHICS_API bool operator ==(const BlendMode& left, const BlendMode& right /// \return True if blending modes are different, false if they are equal /// //////////////////////////////////////////////////////////// -SFML_GRAPHICS_API bool operator !=(const BlendMode& left, const BlendMode& right); +SFML_GRAPHICS_API bool operator!=(const BlendMode& left, const BlendMode& right); //////////////////////////////////////////////////////////// // Commonly used blending modes diff --git a/include/SFML/Graphics/CircleShape.hpp b/include/SFML/Graphics/CircleShape.hpp index 558b795ce..2773be237 100644 --- a/include/SFML/Graphics/CircleShape.hpp +++ b/include/SFML/Graphics/CircleShape.hpp @@ -29,6 +29,7 @@ // Headers //////////////////////////////////////////////////////////// #include + #include @@ -41,7 +42,6 @@ namespace sf class SFML_GRAPHICS_API CircleShape : public Shape { public: - //////////////////////////////////////////////////////////// /// \brief Default constructor /// @@ -107,7 +107,6 @@ public: Vector2f getPoint(std::size_t index) const override; private: - //////////////////////////////////////////////////////////// // Member data //////////////////////////////////////////////////////////// diff --git a/include/SFML/Graphics/Color.hpp b/include/SFML/Graphics/Color.hpp index 3ea136dcd..de497347b 100644 --- a/include/SFML/Graphics/Color.hpp +++ b/include/SFML/Graphics/Color.hpp @@ -40,7 +40,6 @@ namespace sf class Color { public: - //////////////////////////////////////////////////////////// /// \brief Default constructor /// @@ -111,7 +110,7 @@ public: /// \return True if colors are equal, false if they are different /// //////////////////////////////////////////////////////////// -[[nodiscard]] constexpr bool operator ==(const Color& left, const Color& right); +[[nodiscard]] constexpr bool operator==(const Color& left, const Color& right); //////////////////////////////////////////////////////////// /// \relates Color @@ -125,7 +124,7 @@ public: /// \return True if colors are different, false if they are equal /// //////////////////////////////////////////////////////////// -[[nodiscard]] constexpr bool operator !=(const Color& left, const Color& right); +[[nodiscard]] constexpr bool operator!=(const Color& left, const Color& right); //////////////////////////////////////////////////////////// /// \relates Color @@ -140,7 +139,7 @@ public: /// \return Result of \a left + \a right /// //////////////////////////////////////////////////////////// -[[nodiscard]] constexpr Color operator +(const Color& left, const Color& right); +[[nodiscard]] constexpr Color operator+(const Color& left, const Color& right); //////////////////////////////////////////////////////////// /// \relates Color @@ -155,7 +154,7 @@ public: /// \return Result of \a left - \a right /// //////////////////////////////////////////////////////////// -[[nodiscard]] constexpr Color operator -(const Color& left, const Color& right); +[[nodiscard]] constexpr Color operator-(const Color& left, const Color& right); //////////////////////////////////////////////////////////// /// \relates Color @@ -172,7 +171,7 @@ public: /// \return Result of \a left * \a right /// //////////////////////////////////////////////////////////// -[[nodiscard]] constexpr Color operator *(const Color& left, const Color& right); +[[nodiscard]] constexpr Color operator*(const Color& left, const Color& right); //////////////////////////////////////////////////////////// /// \relates Color @@ -188,7 +187,7 @@ public: /// \return Reference to \a left /// //////////////////////////////////////////////////////////// -constexpr Color& operator +=(Color& left, const Color& right); +constexpr Color& operator+=(Color& left, const Color& right); //////////////////////////////////////////////////////////// /// \relates Color @@ -204,7 +203,7 @@ constexpr Color& operator +=(Color& left, const Color& right); /// \return Reference to \a left /// //////////////////////////////////////////////////////////// -constexpr Color& operator -=(Color& left, const Color& right); +constexpr Color& operator-=(Color& left, const Color& right); //////////////////////////////////////////////////////////// /// \relates Color @@ -222,7 +221,7 @@ constexpr Color& operator -=(Color& left, const Color& right); /// \return Reference to \a left /// //////////////////////////////////////////////////////////// -constexpr Color& operator *=(Color& left, const Color& right); +constexpr Color& operator*=(Color& left, const Color& right); #include diff --git a/include/SFML/Graphics/Color.inl b/include/SFML/Graphics/Color.inl index f6a5621eb..b63898a65 100644 --- a/include/SFML/Graphics/Color.inl +++ b/include/SFML/Graphics/Color.inl @@ -24,24 +24,14 @@ //////////////////////////////////////////////////////////// -constexpr Color::Color() : -r(0), -g(0), -b(0), -a(255) +constexpr Color::Color() : r(0), g(0), b(0), a(255) { - } //////////////////////////////////////////////////////////// -constexpr Color::Color(Uint8 red, Uint8 green, Uint8 blue, Uint8 alpha) : -r(red), -g(green), -b(blue), -a(alpha) +constexpr Color::Color(Uint8 red, Uint8 green, Uint8 blue, Uint8 alpha) : r(red), g(green), b(blue), a(alpha) { - } @@ -52,7 +42,6 @@ g(static_cast((color & 0x00ff0000) >> 16)), b(static_cast((color & 0x0000ff00) >> 8)), a(static_cast(color & 0x000000ff)) { - } @@ -64,24 +53,21 @@ constexpr Uint32 Color::toInteger() const //////////////////////////////////////////////////////////// -constexpr bool operator ==(const Color& left, const Color& right) +constexpr bool operator==(const Color& left, const Color& right) { - return (left.r == right.r) && - (left.g == right.g) && - (left.b == right.b) && - (left.a == right.a); + return (left.r == right.r) && (left.g == right.g) && (left.b == right.b) && (left.a == right.a); } //////////////////////////////////////////////////////////// -constexpr bool operator !=(const Color& left, const Color& right) +constexpr bool operator!=(const Color& left, const Color& right) { return !(left == right); } //////////////////////////////////////////////////////////// -constexpr Color operator +(const Color& left, const Color& right) +constexpr Color operator+(const Color& left, const Color& right) { const auto clampedAdd = [](Uint8 lhs, Uint8 rhs) -> Uint8 { @@ -97,7 +83,7 @@ constexpr Color operator +(const Color& left, const Color& right) //////////////////////////////////////////////////////////// -constexpr Color operator -(const Color& left, const Color& right) +constexpr Color operator-(const Color& left, const Color& right) { const auto clampedSub = [](Uint8 lhs, Uint8 rhs) -> Uint8 { @@ -113,7 +99,7 @@ constexpr Color operator -(const Color& left, const Color& right) //////////////////////////////////////////////////////////// -constexpr Color operator *(const Color& left, const Color& right) +constexpr Color operator*(const Color& left, const Color& right) { const auto scaledMul = [](Uint8 lhs, Uint8 rhs) -> Uint8 { @@ -129,21 +115,21 @@ constexpr Color operator *(const Color& left, const Color& right) //////////////////////////////////////////////////////////// -constexpr Color& operator +=(Color& left, const Color& right) +constexpr Color& operator+=(Color& left, const Color& right) { return left = left + right; } //////////////////////////////////////////////////////////// -constexpr Color& operator -=(Color& left, const Color& right) +constexpr Color& operator-=(Color& left, const Color& right) { return left = left - right; } //////////////////////////////////////////////////////////// -constexpr Color& operator *=(Color& left, const Color& right) +constexpr Color& operator*=(Color& left, const Color& right) { return left = left * right; } diff --git a/include/SFML/Graphics/ConvexShape.hpp b/include/SFML/Graphics/ConvexShape.hpp index 6c8bc7429..bfa83ce74 100644 --- a/include/SFML/Graphics/ConvexShape.hpp +++ b/include/SFML/Graphics/ConvexShape.hpp @@ -29,7 +29,9 @@ // Headers //////////////////////////////////////////////////////////// #include + #include + #include @@ -42,7 +44,6 @@ namespace sf class SFML_GRAPHICS_API ConvexShape : public Shape { public: - //////////////////////////////////////////////////////////// /// \brief Default constructor /// @@ -112,7 +113,6 @@ public: Vector2f getPoint(std::size_t index) const override; private: - //////////////////////////////////////////////////////////// // Member data //////////////////////////////////////////////////////////// diff --git a/include/SFML/Graphics/Drawable.hpp b/include/SFML/Graphics/Drawable.hpp index 78c157d61..1b6afc3b2 100644 --- a/include/SFML/Graphics/Drawable.hpp +++ b/include/SFML/Graphics/Drawable.hpp @@ -44,15 +44,15 @@ class RenderStates; class SFML_GRAPHICS_API Drawable { public: - //////////////////////////////////////////////////////////// /// \brief Virtual destructor /// //////////////////////////////////////////////////////////// - virtual ~Drawable() {} + virtual ~Drawable() + { + } protected: - friend class RenderTarget; //////////////////////////////////////////////////////////// diff --git a/include/SFML/Graphics/Export.hpp b/include/SFML/Graphics/Export.hpp index 76bc8e668..13ed4c4de 100644 --- a/include/SFML/Graphics/Export.hpp +++ b/include/SFML/Graphics/Export.hpp @@ -36,11 +36,11 @@ //////////////////////////////////////////////////////////// #if defined(SFML_GRAPHICS_EXPORTS) - #define SFML_GRAPHICS_API SFML_API_EXPORT +#define SFML_GRAPHICS_API SFML_API_EXPORT #else - #define SFML_GRAPHICS_API SFML_API_IMPORT +#define SFML_GRAPHICS_API SFML_API_IMPORT #endif diff --git a/include/SFML/Graphics/Font.hpp b/include/SFML/Graphics/Font.hpp index 0d2097f6e..627b5ffc2 100644 --- a/include/SFML/Graphics/Font.hpp +++ b/include/SFML/Graphics/Font.hpp @@ -29,9 +29,11 @@ // Headers //////////////////////////////////////////////////////////// #include + #include -#include #include +#include + #include #include #include @@ -56,7 +58,6 @@ class InputStream; class SFML_GRAPHICS_API Font { public: - //////////////////////////////////////////////////////////// /// \brief Holds various information about a font /// @@ -67,7 +68,6 @@ public: }; public: - //////////////////////////////////////////////////////////// /// \brief Default constructor /// @@ -327,17 +327,18 @@ public: /// \return Reference to self /// //////////////////////////////////////////////////////////// - Font& operator =(const Font& right); + Font& operator=(const Font& right); private: - //////////////////////////////////////////////////////////// /// \brief Structure defining a row of glyphs /// //////////////////////////////////////////////////////////// struct Row { - Row(unsigned int rowTop, unsigned int rowHeight) : width(0), top(rowTop), height(rowHeight) {} + Row(unsigned int rowTop, unsigned int rowHeight) : width(0), top(rowTop), height(rowHeight) + { + } unsigned int width; //!< Current width of the row unsigned int top; //!< Y position of the row into the texture @@ -422,14 +423,14 @@ private: //////////////////////////////////////////////////////////// // Member data //////////////////////////////////////////////////////////// - std::shared_ptr m_fontHandles; //!< Shared information about the internal font instance - bool m_isSmooth; //!< Status of the smooth filter - Info m_info; //!< Information about the font - mutable PageTable m_pages; //!< Table containing the glyphs pages by character size - mutable std::vector m_pixelBuffer; //!< Pixel buffer holding a glyph's pixels before being written to the texture - #ifdef SFML_SYSTEM_ANDROID - std::unique_ptr m_stream; //!< Asset file streamer (if loaded from file) - #endif + std::shared_ptr m_fontHandles; //!< Shared information about the internal font instance + bool m_isSmooth; //!< Status of the smooth filter + Info m_info; //!< Information about the font + mutable PageTable m_pages; //!< Table containing the glyphs pages by character size + mutable std::vector m_pixelBuffer; //!< Pixel buffer holding a glyph's pixels before being written to the texture +#ifdef SFML_SYSTEM_ANDROID + std::unique_ptr m_stream; //!< Asset file streamer (if loaded from file) +#endif }; } // namespace sf diff --git a/include/SFML/Graphics/Glsl.hpp b/include/SFML/Graphics/Glsl.hpp index 8cbad2b88..666677442 100644 --- a/include/SFML/Graphics/Glsl.hpp +++ b/include/SFML/Graphics/Glsl.hpp @@ -28,10 +28,11 @@ //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// -#include #include +#include #include #include + #include @@ -39,12 +40,12 @@ namespace sf { namespace priv { - // Forward declarations - template - struct Matrix; +// Forward declarations +template +struct Matrix; - template - struct Vector4; +template +struct Vector4; #include @@ -58,136 +59,136 @@ namespace priv namespace Glsl { - //////////////////////////////////////////////////////////// - /// \brief 2D float vector (\p vec2 in GLSL) - /// - //////////////////////////////////////////////////////////// - using Vec2 = Vector2; +//////////////////////////////////////////////////////////// +/// \brief 2D float vector (\p vec2 in GLSL) +/// +//////////////////////////////////////////////////////////// +using Vec2 = Vector2; - //////////////////////////////////////////////////////////// - /// \brief 2D int vector (\p ivec2 in GLSL) - /// - //////////////////////////////////////////////////////////// - using Ivec2 = Vector2; +//////////////////////////////////////////////////////////// +/// \brief 2D int vector (\p ivec2 in GLSL) +/// +//////////////////////////////////////////////////////////// +using Ivec2 = Vector2; - //////////////////////////////////////////////////////////// - /// \brief 2D bool vector (\p bvec2 in GLSL) - /// - //////////////////////////////////////////////////////////// - using Bvec2 = Vector2; +//////////////////////////////////////////////////////////// +/// \brief 2D bool vector (\p bvec2 in GLSL) +/// +//////////////////////////////////////////////////////////// +using Bvec2 = Vector2; - //////////////////////////////////////////////////////////// - /// \brief 3D float vector (\p vec3 in GLSL) - /// - //////////////////////////////////////////////////////////// - using Vec3 = Vector3; +//////////////////////////////////////////////////////////// +/// \brief 3D float vector (\p vec3 in GLSL) +/// +//////////////////////////////////////////////////////////// +using Vec3 = Vector3; - //////////////////////////////////////////////////////////// - /// \brief 3D int vector (\p ivec3 in GLSL) - /// - //////////////////////////////////////////////////////////// - using Ivec3 = Vector3; +//////////////////////////////////////////////////////////// +/// \brief 3D int vector (\p ivec3 in GLSL) +/// +//////////////////////////////////////////////////////////// +using Ivec3 = Vector3; - //////////////////////////////////////////////////////////// - /// \brief 3D bool vector (\p bvec3 in GLSL) - /// - //////////////////////////////////////////////////////////// - using Bvec3 = Vector3; +//////////////////////////////////////////////////////////// +/// \brief 3D bool vector (\p bvec3 in GLSL) +/// +//////////////////////////////////////////////////////////// +using Bvec3 = Vector3; #ifdef SFML_DOXYGEN - //////////////////////////////////////////////////////////// - /// \brief 4D float vector (\p vec4 in GLSL) - /// - /// 4D float vectors can be implicitly converted from sf::Color - /// instances. Each color channel is normalized from integers - /// in [0, 255] to floating point values in [0, 1]. - /// \code - /// sf::Glsl::Vec4 zeroVector; - /// sf::Glsl::Vec4 vector(1.f, 2.f, 3.f, 4.f); - /// sf::Glsl::Vec4 color = sf::Color::Cyan; - /// \endcode - //////////////////////////////////////////////////////////// - using Vec4 = implementation-defined; +//////////////////////////////////////////////////////////// +/// \brief 4D float vector (\p vec4 in GLSL) +/// +/// 4D float vectors can be implicitly converted from sf::Color +/// instances. Each color channel is normalized from integers +/// in [0, 255] to floating point values in [0, 1]. +/// \code +/// sf::Glsl::Vec4 zeroVector; +/// sf::Glsl::Vec4 vector(1.f, 2.f, 3.f, 4.f); +/// sf::Glsl::Vec4 color = sf::Color::Cyan; +/// \endcode +//////////////////////////////////////////////////////////// +using Vec4 = ImplementationDefined; - //////////////////////////////////////////////////////////// - /// \brief 4D int vector (\p ivec4 in GLSL) - /// - /// 4D int vectors can be implicitly converted from sf::Color - /// instances. Each color channel remains unchanged inside - /// the integer interval [0, 255]. - /// \code - /// sf::Glsl::Ivec4 zeroVector; - /// sf::Glsl::Ivec4 vector(1, 2, 3, 4); - /// sf::Glsl::Ivec4 color = sf::Color::Cyan; - /// \endcode - //////////////////////////////////////////////////////////// - using Ivec4 = implementation-defined; +//////////////////////////////////////////////////////////// +/// \brief 4D int vector (\p ivec4 in GLSL) +/// +/// 4D int vectors can be implicitly converted from sf::Color +/// instances. Each color channel remains unchanged inside +/// the integer interval [0, 255]. +/// \code +/// sf::Glsl::Ivec4 zeroVector; +/// sf::Glsl::Ivec4 vector(1, 2, 3, 4); +/// sf::Glsl::Ivec4 color = sf::Color::Cyan; +/// \endcode +//////////////////////////////////////////////////////////// +using Ivec4 = ImplementationDefined; - //////////////////////////////////////////////////////////// - /// \brief 4D bool vector (\p bvec4 in GLSL) - /// - //////////////////////////////////////////////////////////// - using Bvec4 = implementation-defined; +//////////////////////////////////////////////////////////// +/// \brief 4D bool vector (\p bvec4 in GLSL) +/// +//////////////////////////////////////////////////////////// +using Bvec4 = ImplementationDefined; - //////////////////////////////////////////////////////////// - /// \brief 3x3 float matrix (\p mat3 in GLSL) - /// - /// The matrix can be constructed from an array with 3x3 - /// elements, aligned in column-major order. For example, - /// a translation by (x, y) looks as follows: - /// \code - /// float array[9] = - /// { - /// 1, 0, 0, - /// 0, 1, 0, - /// x, y, 1 - /// }; - /// - /// sf::Glsl::Mat3 matrix(array); - /// \endcode - /// - /// Mat3 can also be implicitly converted from sf::Transform: - /// \code - /// sf::Transform transform; - /// sf::Glsl::Mat3 matrix = transform; - /// \endcode - //////////////////////////////////////////////////////////// - using Mat3 = implementation-defined; +//////////////////////////////////////////////////////////// +/// \brief 3x3 float matrix (\p mat3 in GLSL) +/// +/// The matrix can be constructed from an array with 3x3 +/// elements, aligned in column-major order. For example, +/// a translation by (x, y) looks as follows: +/// \code +/// float array[9] = +/// { +/// 1, 0, 0, +/// 0, 1, 0, +/// x, y, 1 +/// }; +/// +/// sf::Glsl::Mat3 matrix(array); +/// \endcode +/// +/// Mat3 can also be implicitly converted from sf::Transform: +/// \code +/// sf::Transform transform; +/// sf::Glsl::Mat3 matrix = transform; +/// \endcode +//////////////////////////////////////////////////////////// +using Mat3 = ImplementationDefined; - //////////////////////////////////////////////////////////// - /// \brief 4x4 float matrix (\p mat4 in GLSL) - /// - /// The matrix can be constructed from an array with 4x4 - /// elements, aligned in column-major order. For example, - /// a translation by (x, y, z) looks as follows: - /// \code - /// float array[16] = - /// { - /// 1, 0, 0, 0, - /// 0, 1, 0, 0, - /// 0, 0, 1, 0, - /// x, y, z, 1 - /// }; - /// - /// sf::Glsl::Mat4 matrix(array); - /// \endcode - /// - /// Mat4 can also be implicitly converted from sf::Transform: - /// \code - /// sf::Transform transform; - /// sf::Glsl::Mat4 matrix = transform; - /// \endcode - //////////////////////////////////////////////////////////// - using Mat4 = implementation-defined; +//////////////////////////////////////////////////////////// +/// \brief 4x4 float matrix (\p mat4 in GLSL) +/// +/// The matrix can be constructed from an array with 4x4 +/// elements, aligned in column-major order. For example, +/// a translation by (x, y, z) looks as follows: +/// \code +/// float array[16] = +/// { +/// 1, 0, 0, 0, +/// 0, 1, 0, 0, +/// 0, 0, 1, 0, +/// x, y, z, 1 +/// }; +/// +/// sf::Glsl::Mat4 matrix(array); +/// \endcode +/// +/// Mat4 can also be implicitly converted from sf::Transform: +/// \code +/// sf::Transform transform; +/// sf::Glsl::Mat4 matrix = transform; +/// \endcode +//////////////////////////////////////////////////////////// +using Mat4 = ImplementationDefined; #else // SFML_DOXYGEN - using Vec4 = priv::Vector4; - using Ivec4 = priv::Vector4; - using Bvec4 = priv::Vector4; - using Mat3 = priv::Matrix<3, 3>; - using Mat4 = priv::Matrix<4, 4>; +using Vec4 = priv::Vector4; +using Ivec4 = priv::Vector4; +using Bvec4 = priv::Vector4; +using Mat3 = priv::Matrix<3, 3>; +using Mat4 = priv::Matrix<4, 4>; #endif // SFML_DOXYGEN diff --git a/include/SFML/Graphics/Glsl.inl b/include/SFML/Graphics/Glsl.inl index 15c89137c..464b02ed6 100644 --- a/include/SFML/Graphics/Glsl.inl +++ b/include/SFML/Graphics/Glsl.inl @@ -95,11 +95,7 @@ struct Vector4 /// \brief Default constructor, creates a zero vector /// //////////////////////////////////////////////////////////// - Vector4() : - x(0), - y(0), - z(0), - w(0) + Vector4() : x(0), y(0), z(0), w(0) { } @@ -112,11 +108,7 @@ struct Vector4 /// \param W Component of the 4D vector /// //////////////////////////////////////////////////////////// - Vector4(T X, T Y, T Z, T W) : - x(X), - y(Y), - z(Z), - w(W) + Vector4(T X, T Y, T Z, T W) : x(X), y(Y), z(Z), w(W) { } diff --git a/include/SFML/Graphics/Glyph.hpp b/include/SFML/Graphics/Glyph.hpp index 24340df42..3794870d4 100644 --- a/include/SFML/Graphics/Glyph.hpp +++ b/include/SFML/Graphics/Glyph.hpp @@ -29,6 +29,7 @@ // Headers //////////////////////////////////////////////////////////// #include + #include @@ -41,12 +42,13 @@ namespace sf class SFML_GRAPHICS_API Glyph { public: - //////////////////////////////////////////////////////////// /// \brief Default constructor /// //////////////////////////////////////////////////////////// - Glyph() : advance(0), lsbDelta(0), rsbDelta(0) {} + Glyph() : advance(0), lsbDelta(0), rsbDelta(0) + { + } //////////////////////////////////////////////////////////// // Member data diff --git a/include/SFML/Graphics/Image.hpp b/include/SFML/Graphics/Image.hpp index 6ec8db1ba..2845822d0 100644 --- a/include/SFML/Graphics/Image.hpp +++ b/include/SFML/Graphics/Image.hpp @@ -29,8 +29,10 @@ // Headers //////////////////////////////////////////////////////////// #include + #include #include + #include #include #include @@ -47,7 +49,6 @@ class InputStream; class SFML_GRAPHICS_API Image { public: - //////////////////////////////////////////////////////////// /// \brief Create the image and fill it with a unique color /// @@ -211,7 +212,10 @@ public: /// \return True if the operation was successful, false otherwise /// //////////////////////////////////////////////////////////// - [[nodiscard]] bool copy(const Image& source, const Vector2u& dest, const IntRect& sourceRect = IntRect({0, 0}, {0, 0}), bool applyAlpha = false); + [[nodiscard]] bool copy(const Image& source, + const Vector2u& dest, + const IntRect& sourceRect = IntRect({0, 0}, {0, 0}), + bool applyAlpha = false); //////////////////////////////////////////////////////////// /// \brief Change the color of a pixel @@ -272,7 +276,6 @@ public: void flipVertically(); private: - //////////////////////////////////////////////////////////// // Member data //////////////////////////////////////////////////////////// diff --git a/include/SFML/Graphics/PrimitiveType.hpp b/include/SFML/Graphics/PrimitiveType.hpp index e9ca29e92..ce2f63e2c 100644 --- a/include/SFML/Graphics/PrimitiveType.hpp +++ b/include/SFML/Graphics/PrimitiveType.hpp @@ -43,7 +43,7 @@ enum PrimitiveType LineStrip, //!< List of connected lines, a point uses the previous point to form a line Triangles, //!< List of individual triangles TriangleStrip, //!< List of connected triangles, a point uses the two previous points to form a triangle - TriangleFan //!< List of connected triangles, a point uses the common center and the previous point to form a triangle + TriangleFan //!< List of connected triangles, a point uses the common center and the previous point to form a triangle }; } // namespace sf diff --git a/include/SFML/Graphics/Rect.hpp b/include/SFML/Graphics/Rect.hpp index b801aa74e..c4648b4af 100644 --- a/include/SFML/Graphics/Rect.hpp +++ b/include/SFML/Graphics/Rect.hpp @@ -29,6 +29,7 @@ // Headers //////////////////////////////////////////////////////////// #include + #include @@ -42,7 +43,6 @@ template class Rect { public: - //////////////////////////////////////////////////////////// /// \brief Default constructor /// @@ -147,7 +147,7 @@ public: /// //////////////////////////////////////////////////////////// template -[[nodiscard]] constexpr bool operator ==(const Rect& left, const Rect& right); +[[nodiscard]] constexpr bool operator==(const Rect& left, const Rect& right); //////////////////////////////////////////////////////////// /// \relates Rect @@ -162,12 +162,12 @@ template /// //////////////////////////////////////////////////////////// template -[[nodiscard]] constexpr bool operator !=(const Rect& left, const Rect& right); +[[nodiscard]] constexpr bool operator!=(const Rect& left, const Rect& right); #include // Create type aliases for the most common types -using IntRect = Rect; +using IntRect = Rect; using FloatRect = Rect; } // namespace sf diff --git a/include/SFML/Graphics/Rect.inl b/include/SFML/Graphics/Rect.inl index c34064f57..3b172d099 100644 --- a/include/SFML/Graphics/Rect.inl +++ b/include/SFML/Graphics/Rect.inl @@ -25,25 +25,19 @@ //////////////////////////////////////////////////////////// template -constexpr Rect::Rect() : -left (0), -top (0), -width (0), -height(0) +constexpr Rect::Rect() : left(0), top(0), width(0), height(0) { - } //////////////////////////////////////////////////////////// template constexpr Rect::Rect(const Vector2& position, const Vector2& size) : -left (position.x), -top (position.y), -width (size.x), +left(position.x), +top(position.y), +width(size.x), height(size.y) { - } @@ -51,9 +45,9 @@ height(size.y) template template constexpr Rect::Rect(const Rect& rectangle) : -left (static_cast(rectangle.left)), -top (static_cast(rectangle.top)), -width (static_cast(rectangle.width)), +left(static_cast(rectangle.left)), +top(static_cast(rectangle.top)), +width(static_cast(rectangle.width)), height(static_cast(rectangle.height)) { } @@ -64,8 +58,8 @@ template constexpr bool Rect::contains(const Vector2& point) const { // Not using 'std::min' and 'std::max' to avoid depending on '' - const auto min = [](T a, T b){ return (a < b) ? a : b; }; - const auto max = [](T a, T b){ return (a < b) ? b : a; }; + const auto min = [](T a, T b) { return (a < b) ? a : b; }; + const auto max = [](T a, T b) { return (a < b) ? b : a; }; // Rectangles with negative dimensions are allowed, so we must handle them correctly @@ -84,8 +78,8 @@ template constexpr std::optional> Rect::findIntersection(const Rect& rectangle) const { // Not using 'std::min' and 'std::max' to avoid depending on '' - const auto min = [](T a, T b){ return (a < b) ? a : b; }; - const auto max = [](T a, T b){ return (a < b) ? b : a; }; + const auto min = [](T a, T b) { return (a < b) ? a : b; }; + const auto max = [](T a, T b) { return (a < b) ? b : a; }; // Rectangles with negative dimensions are allowed, so we must handle them correctly @@ -137,16 +131,16 @@ constexpr Vector2 Rect::getSize() const //////////////////////////////////////////////////////////// template -constexpr bool operator ==(const Rect& left, const Rect& right) +constexpr bool operator==(const Rect& left, const Rect& right) { - return (left.left == right.left) && (left.width == right.width) && - (left.top == right.top) && (left.height == right.height); + return (left.left == right.left) && (left.width == right.width) && (left.top == right.top) && + (left.height == right.height); } //////////////////////////////////////////////////////////// template -constexpr bool operator !=(const Rect& left, const Rect& right) +constexpr bool operator!=(const Rect& left, const Rect& right) { return !(left == right); } diff --git a/include/SFML/Graphics/RectangleShape.hpp b/include/SFML/Graphics/RectangleShape.hpp index b29c76fd7..908109801 100644 --- a/include/SFML/Graphics/RectangleShape.hpp +++ b/include/SFML/Graphics/RectangleShape.hpp @@ -29,6 +29,7 @@ // Headers //////////////////////////////////////////////////////////// #include + #include @@ -41,7 +42,6 @@ namespace sf class SFML_GRAPHICS_API RectangleShape : public Shape { public: - //////////////////////////////////////////////////////////// /// \brief Default constructor /// @@ -95,7 +95,6 @@ public: Vector2f getPoint(std::size_t index) const override; private: - //////////////////////////////////////////////////////////// // Member data //////////////////////////////////////////////////////////// diff --git a/include/SFML/Graphics/RenderStates.hpp b/include/SFML/Graphics/RenderStates.hpp index db7a9edc2..ab8021c93 100644 --- a/include/SFML/Graphics/RenderStates.hpp +++ b/include/SFML/Graphics/RenderStates.hpp @@ -29,6 +29,7 @@ // Headers //////////////////////////////////////////////////////////// #include + #include #include @@ -45,7 +46,6 @@ class Texture; class SFML_GRAPHICS_API RenderStates { public: - //////////////////////////////////////////////////////////// /// \brief Default constructor /// @@ -101,8 +101,7 @@ public: /// \param theShader Shader to use /// //////////////////////////////////////////////////////////// - RenderStates(const BlendMode& theBlendMode, const Transform& theTransform, - const Texture* theTexture, const Shader* theShader); + RenderStates(const BlendMode& theBlendMode, const Transform& theTransform, const Texture* theTexture, const Shader* theShader); //////////////////////////////////////////////////////////// // Static member data diff --git a/include/SFML/Graphics/RenderTarget.hpp b/include/SFML/Graphics/RenderTarget.hpp index a38f04507..d8515b29b 100644 --- a/include/SFML/Graphics/RenderTarget.hpp +++ b/include/SFML/Graphics/RenderTarget.hpp @@ -29,13 +29,15 @@ // Headers //////////////////////////////////////////////////////////// #include -#include -#include -#include + #include -#include +#include #include +#include +#include #include +#include + #include @@ -52,7 +54,6 @@ class Transform; class SFML_GRAPHICS_API RenderTarget { public: - //////////////////////////////////////////////////////////// /// \brief Destructor /// @@ -257,8 +258,10 @@ public: /// \param states Render states to use for drawing /// //////////////////////////////////////////////////////////// - void draw(const Vertex* vertices, std::size_t vertexCount, - PrimitiveType type, const RenderStates& states = RenderStates::Default); + void draw(const Vertex* vertices, + std::size_t vertexCount, + PrimitiveType type, + const RenderStates& states = RenderStates::Default); //////////////////////////////////////////////////////////// /// \brief Draw primitives defined by a vertex buffer @@ -278,7 +281,10 @@ public: /// \param states Render states to use for drawing /// //////////////////////////////////////////////////////////// - void draw(const VertexBuffer& vertexBuffer, std::size_t firstVertex, std::size_t vertexCount, const RenderStates& states = RenderStates::Default); + void draw(const VertexBuffer& vertexBuffer, + std::size_t firstVertex, + std::size_t vertexCount, + const RenderStates& states = RenderStates::Default); //////////////////////////////////////////////////////////// /// \brief Return the size of the rendering region of the target @@ -387,7 +393,6 @@ public: void resetGLStates(); protected: - //////////////////////////////////////////////////////////// /// \brief Default constructor /// @@ -404,7 +409,6 @@ protected: void initialize(); private: - //////////////////////////////////////////////////////////// /// \brief Apply the current view /// @@ -476,15 +480,18 @@ private: //////////////////////////////////////////////////////////// struct StatesCache { - enum {VertexCacheSize = 4}; + enum + { + VertexCacheSize = 4 + }; - bool enable; //!< Is the cache enabled? - bool glStatesSet; //!< Are our internal GL states set yet? - bool viewChanged; //!< Has the current view changed since last draw? - BlendMode lastBlendMode; //!< Cached blending mode - Uint64 lastTextureId; //!< Cached texture - bool texCoordsArrayEnabled; //!< Is GL_TEXTURE_COORD_ARRAY client state enabled? - bool useVertexCache; //!< Did we previously use the vertex cache? + bool enable; //!< Is the cache enabled? + bool glStatesSet; //!< Are our internal GL states set yet? + bool viewChanged; //!< Has the current view changed since last draw? + BlendMode lastBlendMode; //!< Cached blending mode + Uint64 lastTextureId; //!< Cached texture + bool texCoordsArrayEnabled; //!< Is GL_TEXTURE_COORD_ARRAY client state enabled? + bool useVertexCache; //!< Did we previously use the vertex cache? Vertex vertexCache[VertexCacheSize]; //!< Pre-transformed vertices cache }; diff --git a/include/SFML/Graphics/RenderTexture.hpp b/include/SFML/Graphics/RenderTexture.hpp index d5e778616..de72ddc64 100644 --- a/include/SFML/Graphics/RenderTexture.hpp +++ b/include/SFML/Graphics/RenderTexture.hpp @@ -29,9 +29,11 @@ // Headers //////////////////////////////////////////////////////////// #include -#include + #include +#include #include + #include @@ -39,7 +41,7 @@ namespace sf { namespace priv { - class RenderTextureImpl; +class RenderTextureImpl; } //////////////////////////////////////////////////////////// @@ -49,7 +51,6 @@ namespace priv class SFML_GRAPHICS_API RenderTexture : public RenderTarget { public: - //////////////////////////////////////////////////////////// /// \brief Default constructor /// @@ -224,7 +225,6 @@ public: const Texture& getTexture() const; private: - //////////////////////////////////////////////////////////// // Member data //////////////////////////////////////////////////////////// diff --git a/include/SFML/Graphics/RenderWindow.hpp b/include/SFML/Graphics/RenderWindow.hpp index 5112556b5..cda7749fa 100644 --- a/include/SFML/Graphics/RenderWindow.hpp +++ b/include/SFML/Graphics/RenderWindow.hpp @@ -29,6 +29,7 @@ // Headers //////////////////////////////////////////////////////////// #include + #include #include @@ -42,7 +43,6 @@ namespace sf class SFML_GRAPHICS_API RenderWindow : public Window, public RenderTarget { public: - //////////////////////////////////////////////////////////// /// \brief Default constructor /// @@ -71,7 +71,10 @@ public: /// \param settings Additional settings for the underlying OpenGL context /// //////////////////////////////////////////////////////////// - RenderWindow(VideoMode mode, const String& title, Uint32 style = Style::Default, const ContextSettings& settings = ContextSettings()); + RenderWindow(VideoMode mode, + const String& title, + Uint32 style = Style::Default, + const ContextSettings& settings = ContextSettings()); //////////////////////////////////////////////////////////// /// \brief Construct the window from an existing control @@ -140,7 +143,6 @@ public: [[nodiscard]] bool setActive(bool active = true) override; protected: - //////////////////////////////////////////////////////////// /// \brief Function called after the window has been created /// @@ -161,7 +163,6 @@ protected: void onResize() override; private: - //////////////////////////////////////////////////////////// // Member data //////////////////////////////////////////////////////////// diff --git a/include/SFML/Graphics/Shader.hpp b/include/SFML/Graphics/Shader.hpp index ac71301f9..ac9453360 100644 --- a/include/SFML/Graphics/Shader.hpp +++ b/include/SFML/Graphics/Shader.hpp @@ -29,10 +29,12 @@ // Headers //////////////////////////////////////////////////////////// #include + #include -#include #include #include +#include + #include #include #include @@ -52,7 +54,6 @@ class Transform; class SFML_GRAPHICS_API Shader : GlResource { public: - //////////////////////////////////////////////////////////// /// \brief Types of shaders /// @@ -71,7 +72,9 @@ public: /// \see setUniform(const std::string&, CurrentTextureType) /// //////////////////////////////////////////////////////////// - struct CurrentTextureType {}; + struct CurrentTextureType + { + }; //////////////////////////////////////////////////////////// /// \brief Represents the texture of the object being drawn @@ -82,7 +85,6 @@ public: static CurrentTextureType CurrentTexture; public: - //////////////////////////////////////////////////////////// /// \brief Default constructor /// @@ -149,7 +151,8 @@ public: /// \see loadFromMemory, loadFromStream /// //////////////////////////////////////////////////////////// - [[nodiscard]] bool loadFromFile(const std::filesystem::path& vertexShaderFilename, const std::filesystem::path& fragmentShaderFilename); + [[nodiscard]] bool loadFromFile(const std::filesystem::path& vertexShaderFilename, + const std::filesystem::path& fragmentShaderFilename); //////////////////////////////////////////////////////////// /// \brief Load the vertex, geometry and fragment shaders from files @@ -171,7 +174,9 @@ public: /// \see loadFromMemory, loadFromStream /// //////////////////////////////////////////////////////////// - [[nodiscard]] bool loadFromFile(const std::filesystem::path& vertexShaderFilename, const std::filesystem::path& geometryShaderFilename, const std::filesystem::path& fragmentShaderFilename); + [[nodiscard]] bool loadFromFile(const std::filesystem::path& vertexShaderFilename, + const std::filesystem::path& geometryShaderFilename, + const std::filesystem::path& fragmentShaderFilename); //////////////////////////////////////////////////////////// /// \brief Load the vertex, geometry or fragment shader from a source code in memory @@ -234,7 +239,9 @@ public: /// \see loadFromFile, loadFromStream /// //////////////////////////////////////////////////////////// - [[nodiscard]] bool loadFromMemory(const std::string& vertexShader, const std::string& geometryShader, const std::string& fragmentShader); + [[nodiscard]] bool loadFromMemory(const std::string& vertexShader, + const std::string& geometryShader, + const std::string& fragmentShader); //////////////////////////////////////////////////////////// /// \brief Load the vertex, geometry or fragment shader from a custom stream @@ -297,7 +304,9 @@ public: /// \see loadFromFile, loadFromMemory /// //////////////////////////////////////////////////////////// - [[nodiscard]] bool loadFromStream(InputStream& vertexShaderStream, InputStream& geometryShaderStream, InputStream& fragmentShaderStream); + [[nodiscard]] bool loadFromStream(InputStream& vertexShaderStream, + InputStream& geometryShaderStream, + InputStream& fragmentShaderStream); //////////////////////////////////////////////////////////// /// \brief Specify value for \p float uniform @@ -624,7 +633,6 @@ public: static bool isGeometryAvailable(); private: - //////////////////////////////////////////////////////////// /// \brief Compile the shader(s) and create the program /// @@ -671,7 +679,7 @@ private: //////////////////////////////////////////////////////////// // Types //////////////////////////////////////////////////////////// - using TextureTable = std::unordered_map; + using TextureTable = std::unordered_map; using UniformTable = std::unordered_map; //////////////////////////////////////////////////////////// diff --git a/include/SFML/Graphics/Shape.hpp b/include/SFML/Graphics/Shape.hpp index 961208f0e..d034a8f1b 100644 --- a/include/SFML/Graphics/Shape.hpp +++ b/include/SFML/Graphics/Shape.hpp @@ -29,6 +29,7 @@ // Headers //////////////////////////////////////////////////////////// #include + #include #include #include @@ -46,7 +47,6 @@ class Texture; class SFML_GRAPHICS_API Shape : public Drawable, public Transformable { public: - //////////////////////////////////////////////////////////// /// \brief Virtual destructor /// @@ -250,7 +250,6 @@ public: FloatRect getGlobalBounds() const; protected: - //////////////////////////////////////////////////////////// /// \brief Default constructor /// @@ -268,7 +267,6 @@ protected: void update(); private: - //////////////////////////////////////////////////////////// /// \brief Draw the shape to a render target /// @@ -303,7 +301,6 @@ private: void updateOutlineColors(); private: - //////////////////////////////////////////////////////////// // Member data //////////////////////////////////////////////////////////// diff --git a/include/SFML/Graphics/Sprite.hpp b/include/SFML/Graphics/Sprite.hpp index 2b4881813..ba89b033d 100644 --- a/include/SFML/Graphics/Sprite.hpp +++ b/include/SFML/Graphics/Sprite.hpp @@ -29,10 +29,11 @@ // Headers //////////////////////////////////////////////////////////// #include + #include +#include #include #include -#include namespace sf @@ -47,7 +48,6 @@ class Texture; class SFML_GRAPHICS_API Sprite : public Drawable, public Transformable { public: - //////////////////////////////////////////////////////////// /// \brief Default constructor /// @@ -190,7 +190,6 @@ public: FloatRect getGlobalBounds() const; private: - //////////////////////////////////////////////////////////// /// \brief Draw the sprite to a render target /// diff --git a/include/SFML/Graphics/Text.hpp b/include/SFML/Graphics/Text.hpp index 19b6e480a..20ed716b3 100644 --- a/include/SFML/Graphics/Text.hpp +++ b/include/SFML/Graphics/Text.hpp @@ -29,11 +29,13 @@ // Headers //////////////////////////////////////////////////////////// #include + #include -#include #include +#include #include #include + #include #include @@ -49,7 +51,6 @@ class Font; class SFML_GRAPHICS_API Text : public Drawable, public Transformable { public: - //////////////////////////////////////////////////////////// /// \brief Enumeration of the string drawing styles /// @@ -406,7 +407,6 @@ public: FloatRect getGlobalBounds() const; private: - //////////////////////////////////////////////////////////// /// \brief Draw the text to a render target /// diff --git a/include/SFML/Graphics/Texture.hpp b/include/SFML/Graphics/Texture.hpp index 24b80d45a..13a52486c 100644 --- a/include/SFML/Graphics/Texture.hpp +++ b/include/SFML/Graphics/Texture.hpp @@ -29,8 +29,10 @@ // Headers //////////////////////////////////////////////////////////// #include -#include + #include +#include + #include @@ -50,7 +52,6 @@ class Image; class SFML_GRAPHICS_API Texture : GlResource { public: - //////////////////////////////////////////////////////////// /// \brief Types of texture coordinates that can be used for rendering /// @@ -62,7 +63,6 @@ public: }; public: - //////////////////////////////////////////////////////////// /// \brief Default constructor /// @@ -512,7 +512,7 @@ public: /// \return Reference to self /// //////////////////////////////////////////////////////////// - Texture& operator =(const Texture& right); + Texture& operator=(const Texture& right); //////////////////////////////////////////////////////////// /// \brief Swap the contents of this texture with those of another @@ -580,7 +580,6 @@ public: static unsigned int getMaximumSize(); private: - friend class Text; friend class RenderTexture; friend class RenderTarget; diff --git a/include/SFML/Graphics/Transform.hpp b/include/SFML/Graphics/Transform.hpp index 5ab46b413..150950a89 100644 --- a/include/SFML/Graphics/Transform.hpp +++ b/include/SFML/Graphics/Transform.hpp @@ -29,6 +29,7 @@ // Headers //////////////////////////////////////////////////////////// #include + #include #include @@ -44,7 +45,6 @@ class Angle; class Transform { public: - //////////////////////////////////////////////////////////// /// \brief Default constructor /// @@ -67,9 +67,7 @@ public: /// \param a22 Element (2, 2) of the matrix /// //////////////////////////////////////////////////////////// - constexpr Transform(float a00, float a01, float a02, - float a10, float a11, float a12, - float a20, float a21, float a22); + constexpr Transform(float a00, float a01, float a02, float a10, float a11, float a12, float a20, float a21, float a22); //////////////////////////////////////////////////////////// /// \brief Return the transform as a 4x4 matrix @@ -264,7 +262,6 @@ public: static const Transform Identity; //!< The identity transform (does nothing) private: - //////////////////////////////////////////////////////////// // Member data //////////////////////////////////////////////////////////// @@ -283,7 +280,7 @@ private: /// \return New combined transform /// //////////////////////////////////////////////////////////// -constexpr Transform operator *(const Transform& left, const Transform& right); +constexpr Transform operator*(const Transform& left, const Transform& right); //////////////////////////////////////////////////////////// /// \relates sf::Transform @@ -297,7 +294,7 @@ constexpr Transform operator *(const Transform& left, const Transform& right); /// \return The combined transform /// //////////////////////////////////////////////////////////// -constexpr Transform& operator *=(Transform& left, const Transform& right); +constexpr Transform& operator*=(Transform& left, const Transform& right); //////////////////////////////////////////////////////////// /// \relates sf::Transform @@ -311,7 +308,7 @@ constexpr Transform& operator *=(Transform& left, const Transform& right); /// \return New transformed point /// //////////////////////////////////////////////////////////// -constexpr Vector2f operator *(const Transform& left, const Vector2f& right); +constexpr Vector2f operator*(const Transform& left, const Vector2f& right); //////////////////////////////////////////////////////////// /// \relates sf::Transform @@ -326,7 +323,7 @@ constexpr Vector2f operator *(const Transform& left, const Vector2f& right); /// \return true if the transforms are equal, false otherwise /// //////////////////////////////////////////////////////////// -[[nodiscard]] constexpr bool operator ==(const Transform& left, const Transform& right); +[[nodiscard]] constexpr bool operator==(const Transform& left, const Transform& right); //////////////////////////////////////////////////////////// /// \relates sf::Transform @@ -340,7 +337,7 @@ constexpr Vector2f operator *(const Transform& left, const Vector2f& right); /// \return true if the transforms are not equal, false otherwise /// //////////////////////////////////////////////////////////// -[[nodiscard]] constexpr bool operator !=(const Transform& left, const Transform& right); +[[nodiscard]] constexpr bool operator!=(const Transform& left, const Transform& right); #include diff --git a/include/SFML/Graphics/Transform.inl b/include/SFML/Graphics/Transform.inl index 14b906f91..712df2844 100644 --- a/include/SFML/Graphics/Transform.inl +++ b/include/SFML/Graphics/Transform.inl @@ -102,18 +102,15 @@ constexpr Vector2f Transform::transformPoint(const Vector2f& point) const constexpr FloatRect Transform::transformRect(const FloatRect& rectangle) const { // Transform the 4 corners of the rectangle - const Vector2f points[] = - { - transformPoint({rectangle.left, rectangle.top}), - transformPoint({rectangle.left, rectangle.top + rectangle.height}), - transformPoint({rectangle.left + rectangle.width, rectangle.top}), - transformPoint({rectangle.left + rectangle.width, rectangle.top + rectangle.height}) - }; + const Vector2f points[] = {transformPoint({rectangle.left, rectangle.top}), + transformPoint({rectangle.left, rectangle.top + rectangle.height}), + transformPoint({rectangle.left + rectangle.width, rectangle.top}), + transformPoint({rectangle.left + rectangle.width, rectangle.top + rectangle.height})}; // Compute the bounding rectangle of the transformed points - float left = points[0].x; - float top = points[0].y; - float right = points[0].x; + float left = points[0].x; + float top = points[0].y; + float right = points[0].x; float bottom = points[0].y; for (int i = 1; i < 4; ++i) @@ -193,28 +190,28 @@ constexpr Transform& Transform::scale(const Vector2f& factors, const Vector2f& c //////////////////////////////////////////////////////////// -constexpr Transform operator *(const Transform& left, const Transform& right) +constexpr Transform operator*(const Transform& left, const Transform& right) { return Transform(left).combine(right); } //////////////////////////////////////////////////////////// -constexpr Transform& operator *=(Transform& left, const Transform& right) +constexpr Transform& operator*=(Transform& left, const Transform& right) { return left.combine(right); } //////////////////////////////////////////////////////////// -constexpr Vector2f operator *(const Transform& left, const Vector2f& right) +constexpr Vector2f operator*(const Transform& left, const Vector2f& right) { return left.transformPoint(right); } //////////////////////////////////////////////////////////// -constexpr bool operator ==(const Transform& left, const Transform& right) +constexpr bool operator==(const Transform& left, const Transform& right) { const float* a = left.getMatrix(); const float* b = right.getMatrix(); @@ -228,7 +225,7 @@ constexpr bool operator ==(const Transform& left, const Transform& right) //////////////////////////////////////////////////////////// -constexpr bool operator !=(const Transform& left, const Transform& right) +constexpr bool operator!=(const Transform& left, const Transform& right) { return !(left == right); } diff --git a/include/SFML/Graphics/Transformable.hpp b/include/SFML/Graphics/Transformable.hpp index d4e89b3a8..d07e226cb 100644 --- a/include/SFML/Graphics/Transformable.hpp +++ b/include/SFML/Graphics/Transformable.hpp @@ -29,6 +29,7 @@ // Headers //////////////////////////////////////////////////////////// #include + #include #include @@ -42,7 +43,6 @@ namespace sf class SFML_GRAPHICS_API Transformable { public: - //////////////////////////////////////////////////////////// /// \brief Default constructor /// @@ -227,7 +227,6 @@ public: const Transform& getInverseTransform() const; private: - //////////////////////////////////////////////////////////// // Member data //////////////////////////////////////////////////////////// diff --git a/include/SFML/Graphics/Vertex.hpp b/include/SFML/Graphics/Vertex.hpp index 66e62336e..e1d20fba8 100644 --- a/include/SFML/Graphics/Vertex.hpp +++ b/include/SFML/Graphics/Vertex.hpp @@ -41,7 +41,6 @@ namespace sf class Vertex { public: - //////////////////////////////////////////////////////////// /// \brief Default constructor /// @@ -93,9 +92,9 @@ public: //////////////////////////////////////////////////////////// // Member data //////////////////////////////////////////////////////////// - Vector2f position; //!< 2D position of the vertex - Color color; //!< Color of the vertex - Vector2f texCoords; //!< Coordinates of the texture's pixel to map to the vertex + Vector2f position; //!< 2D position of the vertex + Color color; //!< Color of the vertex + Vector2f texCoords; //!< Coordinates of the texture's pixel to map to the vertex }; #include diff --git a/include/SFML/Graphics/Vertex.inl b/include/SFML/Graphics/Vertex.inl index 9bd87900e..ca46592f3 100644 --- a/include/SFML/Graphics/Vertex.inl +++ b/include/SFML/Graphics/Vertex.inl @@ -24,27 +24,21 @@ //////////////////////////////////////////////////////////// -constexpr Vertex::Vertex() : -position (0, 0), -color (255, 255, 255), -texCoords(0, 0) +constexpr Vertex::Vertex() : position(0, 0), color(255, 255, 255), texCoords(0, 0) { } //////////////////////////////////////////////////////////// -constexpr Vertex::Vertex(const Vector2f& thePosition) : -position (thePosition), -color (255, 255, 255), -texCoords(0, 0) +constexpr Vertex::Vertex(const Vector2f& thePosition) : position(thePosition), color(255, 255, 255), texCoords(0, 0) { } //////////////////////////////////////////////////////////// constexpr Vertex::Vertex(const Vector2f& thePosition, const Color& theColor) : -position (thePosition), -color (theColor), +position(thePosition), +color(theColor), texCoords(0, 0) { } @@ -52,8 +46,8 @@ texCoords(0, 0) //////////////////////////////////////////////////////////// constexpr Vertex::Vertex(const Vector2f& thePosition, const Vector2f& theTexCoords) : -position (thePosition), -color (255, 255, 255), +position(thePosition), +color(255, 255, 255), texCoords(theTexCoords) { } @@ -61,8 +55,8 @@ texCoords(theTexCoords) //////////////////////////////////////////////////////////// constexpr Vertex::Vertex(const Vector2f& thePosition, const Color& theColor, const Vector2f& theTexCoords) : -position (thePosition), -color (theColor), +position(thePosition), +color(theColor), texCoords(theTexCoords) { } diff --git a/include/SFML/Graphics/VertexArray.hpp b/include/SFML/Graphics/VertexArray.hpp index 96effac10..a33b1cd43 100644 --- a/include/SFML/Graphics/VertexArray.hpp +++ b/include/SFML/Graphics/VertexArray.hpp @@ -29,10 +29,12 @@ // Headers //////////////////////////////////////////////////////////// #include -#include + +#include #include #include -#include +#include + #include @@ -45,7 +47,6 @@ namespace sf class SFML_GRAPHICS_API VertexArray : public Drawable { public: - //////////////////////////////////////////////////////////// /// \brief Default constructor /// @@ -85,7 +86,7 @@ public: /// \see getVertexCount /// //////////////////////////////////////////////////////////// - Vertex& operator [](std::size_t index); + Vertex& operator[](std::size_t index); //////////////////////////////////////////////////////////// /// \brief Get a read-only access to a vertex by its index @@ -101,7 +102,7 @@ public: /// \see getVertexCount /// //////////////////////////////////////////////////////////// - const Vertex& operator [](std::size_t index) const; + const Vertex& operator[](std::size_t index) const; //////////////////////////////////////////////////////////// /// \brief Clear the vertex array @@ -171,7 +172,6 @@ public: FloatRect getBounds() const; private: - //////////////////////////////////////////////////////////// /// \brief Draw the vertex array to a render target /// @@ -182,7 +182,6 @@ private: void draw(RenderTarget& target, const RenderStates& states) const override; private: - //////////////////////////////////////////////////////////// // Member data //////////////////////////////////////////////////////////// diff --git a/include/SFML/Graphics/VertexBuffer.hpp b/include/SFML/Graphics/VertexBuffer.hpp index 61c5ba177..21d6d2dd3 100644 --- a/include/SFML/Graphics/VertexBuffer.hpp +++ b/include/SFML/Graphics/VertexBuffer.hpp @@ -29,9 +29,11 @@ // Headers //////////////////////////////////////////////////////////// #include -#include + #include +#include #include + #include @@ -47,7 +49,6 @@ class Vertex; class SFML_GRAPHICS_API VertexBuffer : public Drawable, private GlResource { public: - //////////////////////////////////////////////////////////// /// \brief Usage specifiers /// @@ -216,7 +217,7 @@ public: /// \return Reference to self /// //////////////////////////////////////////////////////////// - VertexBuffer& operator =(const VertexBuffer& right); + VertexBuffer& operator=(const VertexBuffer& right); //////////////////////////////////////////////////////////// /// \brief Swap the contents of this vertex buffer with those of another @@ -320,7 +321,6 @@ public: static bool isAvailable(); private: - //////////////////////////////////////////////////////////// /// \brief Draw the vertex buffer to a render target /// @@ -331,7 +331,6 @@ private: void draw(RenderTarget& target, const RenderStates& states) const override; private: - //////////////////////////////////////////////////////////// // Member data //////////////////////////////////////////////////////////// diff --git a/include/SFML/Graphics/View.hpp b/include/SFML/Graphics/View.hpp index 1c35fe58d..15b5abaf9 100644 --- a/include/SFML/Graphics/View.hpp +++ b/include/SFML/Graphics/View.hpp @@ -29,6 +29,7 @@ // Headers //////////////////////////////////////////////////////////// #include + #include #include #include @@ -44,7 +45,6 @@ namespace sf class SFML_GRAPHICS_API View { public: - //////////////////////////////////////////////////////////// /// \brief Default constructor /// @@ -233,7 +233,6 @@ public: const Transform& getInverseTransform() const; private: - //////////////////////////////////////////////////////////// // Member data //////////////////////////////////////////////////////////// diff --git a/include/SFML/Main.hpp b/include/SFML/Main.hpp index 81744153e..f4aa8e8fe 100644 --- a/include/SFML/Main.hpp +++ b/include/SFML/Main.hpp @@ -33,9 +33,9 @@ #if defined(SFML_SYSTEM_IOS) - // On iOS, we have no choice but to have our own main, - // so we need to rename the user one and call it later - #define main sfmlMain +// On iOS, we have no choice but to have our own main, +// so we need to rename the user one and call it later +#define main sfmlMain #endif diff --git a/include/SFML/Network.hpp b/include/SFML/Network.hpp index e83c81a37..580f73fcb 100644 --- a/include/SFML/Network.hpp +++ b/include/SFML/Network.hpp @@ -29,7 +29,6 @@ // Headers //////////////////////////////////////////////////////////// -#include #include #include #include @@ -40,6 +39,7 @@ #include #include #include +#include #endif // SFML_NETWORK_HPP diff --git a/include/SFML/Network/Export.hpp b/include/SFML/Network/Export.hpp index ba79ddb32..00d289e8d 100644 --- a/include/SFML/Network/Export.hpp +++ b/include/SFML/Network/Export.hpp @@ -36,11 +36,11 @@ //////////////////////////////////////////////////////////// #if defined(SFML_NETWORK_EXPORTS) - #define SFML_NETWORK_API SFML_API_EXPORT +#define SFML_NETWORK_API SFML_API_EXPORT #else - #define SFML_NETWORK_API SFML_API_IMPORT +#define SFML_NETWORK_API SFML_API_IMPORT #endif diff --git a/include/SFML/Network/Ftp.hpp b/include/SFML/Network/Ftp.hpp index 0c8a0b08e..8da99f81b 100644 --- a/include/SFML/Network/Ftp.hpp +++ b/include/SFML/Network/Ftp.hpp @@ -29,8 +29,10 @@ // Headers //////////////////////////////////////////////////////////// #include + #include #include + #include #include #include @@ -47,7 +49,6 @@ class IpAddress; class SFML_NETWORK_API Ftp { public: - //////////////////////////////////////////////////////////// /// \brief Enumeration of transfer modes /// @@ -66,7 +67,6 @@ public: class SFML_NETWORK_API Response { public: - //////////////////////////////////////////////////////////// /// \brief Status codes possibly returned by a FTP response /// @@ -81,13 +81,13 @@ public: OpeningDataConnection = 150, //!< File status ok, about to open data connection // 2xx: the requested action has been successfully completed - Ok = 200, //!< Command ok - PointlessCommand = 202, //!< Command not implemented - SystemStatus = 211, //!< System status, or system help reply - DirectoryStatus = 212, //!< Directory status - FileStatus = 213, //!< File status - HelpMessage = 214, //!< Help message - SystemType = 215, //!< NAME system type, where NAME is an official system name from the list in the Assigned Numbers document + Ok = 200, //!< Command ok + PointlessCommand = 202, //!< Command not implemented + SystemStatus = 211, //!< System status, or system help reply + DirectoryStatus = 212, //!< Directory status + FileStatus = 213, //!< File status + HelpMessage = 214, //!< Help message + SystemType = 215, //!< NAME system type, where NAME is an official system name from the list in the Assigned Numbers document ServiceReady = 220, //!< Service ready for new user ClosingConnection = 221, //!< Service closing control connection DataConnectionOpened = 225, //!< Data connection open, no transfer in progress @@ -110,7 +110,7 @@ public: TransferAborted = 426, //!< Connection closed, transfer aborted FileActionAborted = 450, //!< Requested file action not taken LocalError = 451, //!< Requested action aborted, local error in processing - InsufficientStorageSpace = 452, //!< Requested action not taken; insufficient storage space in system, file unavailable + InsufficientStorageSpace = 452, //!< Requested action not taken; insufficient storage space in system, file unavailable // 5xx: the command was not accepted and // the requested action did not take place @@ -127,10 +127,10 @@ public: FilenameNotAllowed = 553, //!< Requested action not taken, file name not allowed // 10xx: SFML custom codes - InvalidResponse = 1000, //!< Not part of the FTP standard, generated by SFML when a received response cannot be parsed + InvalidResponse = 1000, //!< Not part of the FTP standard, generated by SFML when a received response cannot be parsed ConnectionFailed = 1001, //!< Not part of the FTP standard, generated by SFML when the low-level socket connection with the server fails ConnectionClosed = 1002, //!< Not part of the FTP standard, generated by SFML when the low-level socket connection is unexpectedly closed - InvalidFile = 1003 //!< Not part of the FTP standard, generated by SFML when a local file cannot be read or written + InvalidFile = 1003 //!< Not part of the FTP standard, generated by SFML when a local file cannot be read or written }; //////////////////////////////////////////////////////////// @@ -173,7 +173,6 @@ public: const std::string& getMessage() const; private: - //////////////////////////////////////////////////////////// // Member data //////////////////////////////////////////////////////////// @@ -188,7 +187,6 @@ public: class SFML_NETWORK_API DirectoryResponse : public Response { public: - //////////////////////////////////////////////////////////// /// \brief Default constructor /// @@ -206,7 +204,6 @@ public: const std::filesystem::path& getDirectory() const; private: - //////////////////////////////////////////////////////////// // Member data //////////////////////////////////////////////////////////// @@ -221,7 +218,6 @@ public: class SFML_NETWORK_API ListingResponse : public Response { public: - //////////////////////////////////////////////////////////// /// \brief Default constructor /// @@ -240,7 +236,6 @@ public: const std::vector& getListing() const; private: - //////////////////////////////////////////////////////////// // Member data //////////////////////////////////////////////////////////// @@ -482,7 +477,9 @@ public: /// \see upload /// //////////////////////////////////////////////////////////// - [[nodiscard]] Response download(const std::filesystem::path& remoteFile, const std::filesystem::path& localPath, TransferMode mode = Binary); + [[nodiscard]] Response download(const std::filesystem::path& remoteFile, + const std::filesystem::path& localPath, + TransferMode mode = Binary); //////////////////////////////////////////////////////////// /// \brief Upload a file to the server @@ -505,7 +502,10 @@ public: /// \see download /// //////////////////////////////////////////////////////////// - [[nodiscard]] Response upload(const std::string& localFile, const std::string& remotePath, TransferMode mode = Binary, bool append = false); + [[nodiscard]] Response upload(const std::string& localFile, + const std::string& remotePath, + TransferMode mode = Binary, + bool append = false); //////////////////////////////////////////////////////////// /// \brief Send a command to the FTP server @@ -526,7 +526,6 @@ public: [[nodiscard]] Response sendCommand(const std::string& command, const std::string& parameter = ""); private: - //////////////////////////////////////////////////////////// /// \brief Receive a response from the server /// diff --git a/include/SFML/Network/Http.hpp b/include/SFML/Network/Http.hpp index dbfe1ddef..66d25d143 100644 --- a/include/SFML/Network/Http.hpp +++ b/include/SFML/Network/Http.hpp @@ -29,9 +29,11 @@ // Headers //////////////////////////////////////////////////////////// #include + #include #include #include + #include #include #include @@ -46,7 +48,6 @@ namespace sf class SFML_NETWORK_API Http { public: - //////////////////////////////////////////////////////////// /// \brief Define a HTTP request /// @@ -54,7 +55,6 @@ public: class SFML_NETWORK_API Request { public: - //////////////////////////////////////////////////////////// /// \brief Enumerate the available HTTP methods for a request /// @@ -144,7 +144,6 @@ public: void setBody(const std::string& body); private: - friend class Http; //////////////////////////////////////////////////////////// @@ -193,7 +192,6 @@ public: class SFML_NETWORK_API Response { public: - //////////////////////////////////////////////////////////// /// \brief Enumerate all the valid status codes for a response /// @@ -201,18 +199,18 @@ public: enum Status { // 2xx: success - Ok = 200, //!< Most common code returned when operation was successful - Created = 201, //!< The resource has successfully been created - Accepted = 202, //!< The request has been accepted, but will be processed later by the server - NoContent = 204, //!< The server didn't send any data in return - ResetContent = 205, //!< The server informs the client that it should clear the view (form) that caused the request to be sent + Ok = 200, //!< Most common code returned when operation was successful + Created = 201, //!< The resource has successfully been created + Accepted = 202, //!< The request has been accepted, but will be processed later by the server + NoContent = 204, //!< The server didn't send any data in return + ResetContent = 205, //!< The server informs the client that it should clear the view (form) that caused the request to be sent PartialContent = 206, //!< The server has sent a part of the resource, as a response to a partial GET request // 3xx: redirection MultipleChoices = 300, //!< The requested page can be accessed from several locations MovedPermanently = 301, //!< The requested page has permanently moved to a new location MovedTemporarily = 302, //!< The requested page has temporarily moved to a new location - NotModified = 304, //!< For conditional requests, means the requested page hasn't changed and doesn't need to be refreshed + NotModified = 304, //!< For conditional requests, means the requested page hasn't changed and doesn't need to be refreshed // 4xx: client error BadRequest = 400, //!< The server couldn't understand the request (syntax error) @@ -304,7 +302,6 @@ public: const std::string& getBody() const; private: - friend class Http; //////////////////////////////////////////////////////////// @@ -328,7 +325,7 @@ public: /// \param in String stream containing the header values /// //////////////////////////////////////////////////////////// - void parseFields(std::istream &in); + void parseFields(std::istream& in); //////////////////////////////////////////////////////////// // Types @@ -417,7 +414,6 @@ public: [[nodiscard]] Response sendRequest(const Request& request, Time timeout = Time::Zero); private: - //////////////////////////////////////////////////////////// // Member data //////////////////////////////////////////////////////////// diff --git a/include/SFML/Network/IpAddress.hpp b/include/SFML/Network/IpAddress.hpp index 76245e49b..d8a7fa0f7 100644 --- a/include/SFML/Network/IpAddress.hpp +++ b/include/SFML/Network/IpAddress.hpp @@ -29,11 +29,13 @@ // Headers //////////////////////////////////////////////////////////// #include + #include + #include #include -#include #include +#include namespace sf @@ -164,8 +166,7 @@ public: static const IpAddress Broadcast; //!< The "broadcast" address (for sending UDP messages to everyone on a local network) private: - - friend SFML_NETWORK_API bool operator <(const IpAddress& left, const IpAddress& right); + friend SFML_NETWORK_API bool operator<(const IpAddress& left, const IpAddress& right); //////////////////////////////////////////////////////////// // Member data @@ -182,7 +183,7 @@ private: /// \return True if both addresses are equal /// //////////////////////////////////////////////////////////// -SFML_NETWORK_API bool operator ==(const IpAddress& left, const IpAddress& right); +SFML_NETWORK_API bool operator==(const IpAddress& left, const IpAddress& right); //////////////////////////////////////////////////////////// /// \brief Overload of != operator to compare two IP addresses @@ -193,7 +194,7 @@ SFML_NETWORK_API bool operator ==(const IpAddress& left, const IpAddress& right) /// \return True if both addresses are different /// //////////////////////////////////////////////////////////// -SFML_NETWORK_API bool operator !=(const IpAddress& left, const IpAddress& right); +SFML_NETWORK_API bool operator!=(const IpAddress& left, const IpAddress& right); //////////////////////////////////////////////////////////// /// \brief Overload of < operator to compare two IP addresses @@ -204,7 +205,7 @@ SFML_NETWORK_API bool operator !=(const IpAddress& left, const IpAddress& right) /// \return True if \a left is lesser than \a right /// //////////////////////////////////////////////////////////// -SFML_NETWORK_API bool operator <(const IpAddress& left, const IpAddress& right); +SFML_NETWORK_API bool operator<(const IpAddress& left, const IpAddress& right); //////////////////////////////////////////////////////////// /// \brief Overload of > operator to compare two IP addresses @@ -215,7 +216,7 @@ SFML_NETWORK_API bool operator <(const IpAddress& left, const IpAddress& right); /// \return True if \a left is greater than \a right /// //////////////////////////////////////////////////////////// -SFML_NETWORK_API bool operator >(const IpAddress& left, const IpAddress& right); +SFML_NETWORK_API bool operator>(const IpAddress& left, const IpAddress& right); //////////////////////////////////////////////////////////// /// \brief Overload of <= operator to compare two IP addresses @@ -226,7 +227,7 @@ SFML_NETWORK_API bool operator >(const IpAddress& left, const IpAddress& right); /// \return True if \a left is lesser or equal than \a right /// //////////////////////////////////////////////////////////// -SFML_NETWORK_API bool operator <=(const IpAddress& left, const IpAddress& right); +SFML_NETWORK_API bool operator<=(const IpAddress& left, const IpAddress& right); //////////////////////////////////////////////////////////// /// \brief Overload of >= operator to compare two IP addresses @@ -237,7 +238,7 @@ SFML_NETWORK_API bool operator <=(const IpAddress& left, const IpAddress& right) /// \return True if \a left is greater or equal than \a right /// //////////////////////////////////////////////////////////// -SFML_NETWORK_API bool operator >=(const IpAddress& left, const IpAddress& right); +SFML_NETWORK_API bool operator>=(const IpAddress& left, const IpAddress& right); //////////////////////////////////////////////////////////// /// \brief Overload of >> operator to extract an IP address from an input stream @@ -248,7 +249,7 @@ SFML_NETWORK_API bool operator >=(const IpAddress& left, const IpAddress& right) /// \return Reference to the input stream /// //////////////////////////////////////////////////////////// -SFML_NETWORK_API std::istream& operator >>(std::istream& stream, std::optional& address); +SFML_NETWORK_API std::istream& operator>>(std::istream& stream, std::optional& address); //////////////////////////////////////////////////////////// /// \brief Overload of << operator to print an IP address to an output stream @@ -259,7 +260,7 @@ SFML_NETWORK_API std::istream& operator >>(std::istream& stream, std::optional + +#include #include #include -#include namespace sf @@ -48,7 +49,6 @@ class UdpSocket; class SFML_NETWORK_API Packet { public: - //////////////////////////////////////////////////////////// /// \brief Default constructor /// @@ -164,7 +164,6 @@ public: bool endOfPacket() const; public: - //////////////////////////////////////////////////////////// /// \brief Test the validity of the packet, for reading /// @@ -209,166 +208,165 @@ public: /// Overload of operator >> to read data from the packet /// //////////////////////////////////////////////////////////// - Packet& operator >>(bool& data); + Packet& operator>>(bool& data); //////////////////////////////////////////////////////////// /// \overload //////////////////////////////////////////////////////////// - Packet& operator >>(Int8& data); + Packet& operator>>(Int8& data); //////////////////////////////////////////////////////////// /// \overload //////////////////////////////////////////////////////////// - Packet& operator >>(Uint8& data); + Packet& operator>>(Uint8& data); //////////////////////////////////////////////////////////// /// \overload //////////////////////////////////////////////////////////// - Packet& operator >>(Int16& data); + Packet& operator>>(Int16& data); //////////////////////////////////////////////////////////// /// \overload //////////////////////////////////////////////////////////// - Packet& operator >>(Uint16& data); + Packet& operator>>(Uint16& data); //////////////////////////////////////////////////////////// /// \overload //////////////////////////////////////////////////////////// - Packet& operator >>(Int32& data); + Packet& operator>>(Int32& data); //////////////////////////////////////////////////////////// /// \overload //////////////////////////////////////////////////////////// - Packet& operator >>(Uint32& data); + Packet& operator>>(Uint32& data); //////////////////////////////////////////////////////////// /// \overload //////////////////////////////////////////////////////////// - Packet& operator >>(Int64& data); + Packet& operator>>(Int64& data); //////////////////////////////////////////////////////////// /// \overload //////////////////////////////////////////////////////////// - Packet& operator >>(Uint64& data); + Packet& operator>>(Uint64& data); //////////////////////////////////////////////////////////// /// \overload //////////////////////////////////////////////////////////// - Packet& operator >>(float& data); + Packet& operator>>(float& data); //////////////////////////////////////////////////////////// /// \overload //////////////////////////////////////////////////////////// - Packet& operator >>(double& data); + Packet& operator>>(double& data); //////////////////////////////////////////////////////////// /// \overload //////////////////////////////////////////////////////////// - Packet& operator >>(char* data); + Packet& operator>>(char* data); //////////////////////////////////////////////////////////// /// \overload //////////////////////////////////////////////////////////// - Packet& operator >>(std::string& data); + Packet& operator>>(std::string& data); //////////////////////////////////////////////////////////// /// \overload //////////////////////////////////////////////////////////// - Packet& operator >>(wchar_t* data); + Packet& operator>>(wchar_t* data); //////////////////////////////////////////////////////////// /// \overload //////////////////////////////////////////////////////////// - Packet& operator >>(std::wstring& data); + Packet& operator>>(std::wstring& data); //////////////////////////////////////////////////////////// /// \overload //////////////////////////////////////////////////////////// - Packet& operator >>(String& data); + Packet& operator>>(String& data); //////////////////////////////////////////////////////////// /// Overload of operator << to write data into the packet /// //////////////////////////////////////////////////////////// - Packet& operator <<(bool data); + Packet& operator<<(bool data); //////////////////////////////////////////////////////////// /// \overload //////////////////////////////////////////////////////////// - Packet& operator <<(Int8 data); + Packet& operator<<(Int8 data); //////////////////////////////////////////////////////////// /// \overload //////////////////////////////////////////////////////////// - Packet& operator <<(Uint8 data); + Packet& operator<<(Uint8 data); //////////////////////////////////////////////////////////// /// \overload //////////////////////////////////////////////////////////// - Packet& operator <<(Int16 data); + Packet& operator<<(Int16 data); //////////////////////////////////////////////////////////// /// \overload //////////////////////////////////////////////////////////// - Packet& operator <<(Uint16 data); + Packet& operator<<(Uint16 data); //////////////////////////////////////////////////////////// /// \overload //////////////////////////////////////////////////////////// - Packet& operator <<(Int32 data); + Packet& operator<<(Int32 data); //////////////////////////////////////////////////////////// /// \overload //////////////////////////////////////////////////////////// - Packet& operator <<(Uint32 data); + Packet& operator<<(Uint32 data); //////////////////////////////////////////////////////////// /// \overload //////////////////////////////////////////////////////////// - Packet& operator <<(Int64 data); + Packet& operator<<(Int64 data); //////////////////////////////////////////////////////////// /// \overload //////////////////////////////////////////////////////////// - Packet& operator <<(Uint64 data); + Packet& operator<<(Uint64 data); //////////////////////////////////////////////////////////// /// \overload //////////////////////////////////////////////////////////// - Packet& operator <<(float data); + Packet& operator<<(float data); //////////////////////////////////////////////////////////// /// \overload //////////////////////////////////////////////////////////// - Packet& operator <<(double data); + Packet& operator<<(double data); //////////////////////////////////////////////////////////// /// \overload //////////////////////////////////////////////////////////// - Packet& operator <<(const char* data); + Packet& operator<<(const char* data); //////////////////////////////////////////////////////////// /// \overload //////////////////////////////////////////////////////////// - Packet& operator <<(const std::string& data); + Packet& operator<<(const std::string& data); //////////////////////////////////////////////////////////// /// \overload //////////////////////////////////////////////////////////// - Packet& operator <<(const wchar_t* data); + Packet& operator<<(const wchar_t* data); //////////////////////////////////////////////////////////// /// \overload //////////////////////////////////////////////////////////// - Packet& operator <<(const std::wstring& data); + Packet& operator<<(const std::wstring& data); //////////////////////////////////////////////////////////// /// \overload //////////////////////////////////////////////////////////// - Packet& operator <<(const String& data); + Packet& operator<<(const String& data); protected: - friend class TcpSocket; friend class UdpSocket; @@ -412,13 +410,12 @@ protected: virtual void onReceive(const void* data, std::size_t size); private: - //////////////////////////////////////////////////////////// /// Disallow comparisons between packets /// //////////////////////////////////////////////////////////// - bool operator ==(const Packet& right) const; - bool operator !=(const Packet& right) const; + bool operator==(const Packet& right) const; + bool operator!=(const Packet& right) const; //////////////////////////////////////////////////////////// /// \brief Check if the packet can extract a given number of bytes diff --git a/include/SFML/Network/Socket.hpp b/include/SFML/Network/Socket.hpp index e300e7898..4e3881b3e 100644 --- a/include/SFML/Network/Socket.hpp +++ b/include/SFML/Network/Socket.hpp @@ -29,7 +29,9 @@ // Headers //////////////////////////////////////////////////////////// #include + #include + #include @@ -44,7 +46,6 @@ class SocketSelector; class SFML_NETWORK_API Socket { public: - //////////////////////////////////////////////////////////// /// \brief Status codes that may be returned by socket functions /// @@ -68,7 +69,6 @@ public: }; public: - //////////////////////////////////////////////////////////// /// \brief Destructor /// @@ -117,7 +117,6 @@ public: bool isBlocking() const; protected: - //////////////////////////////////////////////////////////// /// \brief Types of protocols that the socket can use /// @@ -178,7 +177,6 @@ protected: void close(); private: - friend class SocketSelector; //////////////////////////////////////////////////////////// diff --git a/include/SFML/Network/SocketHandle.hpp b/include/SFML/Network/SocketHandle.hpp index a23f17751..3d3384f51 100644 --- a/include/SFML/Network/SocketHandle.hpp +++ b/include/SFML/Network/SocketHandle.hpp @@ -31,7 +31,7 @@ #include #if defined(SFML_SYSTEM_WINDOWS) - #include +#include #endif @@ -43,11 +43,11 @@ namespace sf //////////////////////////////////////////////////////////// #if defined(SFML_SYSTEM_WINDOWS) - using SocketHandle = UINT_PTR; +using SocketHandle = UINT_PTR; #else - using SocketHandle = int; +using SocketHandle = int; #endif diff --git a/include/SFML/Network/SocketSelector.hpp b/include/SFML/Network/SocketSelector.hpp index 07f81d4f8..73e00fc27 100644 --- a/include/SFML/Network/SocketSelector.hpp +++ b/include/SFML/Network/SocketSelector.hpp @@ -29,7 +29,9 @@ // Headers //////////////////////////////////////////////////////////// #include + #include + #include @@ -44,7 +46,6 @@ class Socket; class SFML_NETWORK_API SocketSelector { public: - //////////////////////////////////////////////////////////// /// \brief Default constructor /// @@ -150,10 +151,9 @@ public: /// \return Reference to self /// //////////////////////////////////////////////////////////// - SocketSelector& operator =(const SocketSelector& right); + SocketSelector& operator=(const SocketSelector& right); private: - struct SocketSelectorImpl; //////////////////////////////////////////////////////////// diff --git a/include/SFML/Network/TcpListener.hpp b/include/SFML/Network/TcpListener.hpp index a8f9e90ea..46d8cf959 100644 --- a/include/SFML/Network/TcpListener.hpp +++ b/include/SFML/Network/TcpListener.hpp @@ -29,8 +29,9 @@ // Headers //////////////////////////////////////////////////////////// #include -#include + #include +#include namespace sf @@ -44,7 +45,6 @@ class TcpSocket; class SFML_NETWORK_API TcpListener : public Socket { public: - //////////////////////////////////////////////////////////// /// \brief Default constructor /// diff --git a/include/SFML/Network/TcpSocket.hpp b/include/SFML/Network/TcpSocket.hpp index de383e02c..1241a7cd6 100644 --- a/include/SFML/Network/TcpSocket.hpp +++ b/include/SFML/Network/TcpSocket.hpp @@ -29,8 +29,10 @@ // Headers //////////////////////////////////////////////////////////// #include + #include #include + #include @@ -47,7 +49,6 @@ class Packet; class SFML_NETWORK_API TcpSocket : public Socket { public: - //////////////////////////////////////////////////////////// /// \brief Default constructor /// @@ -210,7 +211,6 @@ public: [[nodiscard]] Status receive(Packet& packet); private: - friend class TcpListener; //////////////////////////////////////////////////////////// diff --git a/include/SFML/Network/UdpSocket.hpp b/include/SFML/Network/UdpSocket.hpp index 58a7b631c..462226ceb 100644 --- a/include/SFML/Network/UdpSocket.hpp +++ b/include/SFML/Network/UdpSocket.hpp @@ -29,8 +29,10 @@ // Headers //////////////////////////////////////////////////////////// #include -#include + #include +#include + #include #include @@ -46,7 +48,6 @@ class Packet; class SFML_NETWORK_API UdpSocket : public Socket { public: - //////////////////////////////////////////////////////////// // Constants //////////////////////////////////////////////////////////// @@ -153,7 +154,11 @@ public: /// \see send /// //////////////////////////////////////////////////////////// - [[nodiscard]] Status receive(void* data, std::size_t size, std::size_t& received, std::optional& remoteAddress, unsigned short& remotePort); + [[nodiscard]] Status receive(void* data, + std::size_t size, + std::size_t& received, + std::optional& remoteAddress, + unsigned short& remotePort); //////////////////////////////////////////////////////////// /// \brief Send a formatted packet of data to a remote peer @@ -191,7 +196,6 @@ public: [[nodiscard]] Status receive(Packet& packet, std::optional& remoteAddress, unsigned short& remotePort); private: - //////////////////////////////////////////////////////////// // Member data //////////////////////////////////////////////////////////// diff --git a/include/SFML/OpenGL.hpp b/include/SFML/OpenGL.hpp index 81f4ebf96..1a873661e 100644 --- a/include/SFML/OpenGL.hpp +++ b/include/SFML/OpenGL.hpp @@ -38,42 +38,43 @@ //////////////////////////////////////////////////////////// #if defined(SFML_SYSTEM_WINDOWS) - // The Visual C++ version of gl.h uses WINGDIAPI and APIENTRY but doesn't define them - #ifdef _MSC_VER - #ifndef WIN32_LEAN_AND_MEAN - #define WIN32_LEAN_AND_MEAN - #endif - #include - #endif +// The Visual C++ version of gl.h uses WINGDIAPI and APIENTRY but doesn't define them +#ifdef _MSC_VER +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#include +#endif - #include +#include -#elif defined(SFML_SYSTEM_LINUX) || defined(SFML_SYSTEM_FREEBSD) || defined(SFML_SYSTEM_OPENBSD) || defined(SFML_SYSTEM_NETBSD) +#elif defined(SFML_SYSTEM_LINUX) || defined(SFML_SYSTEM_FREEBSD) || defined(SFML_SYSTEM_OPENBSD) || \ + defined(SFML_SYSTEM_NETBSD) - #if defined(SFML_OPENGL_ES) - #include - #include - #else - #include - #endif +#if defined(SFML_OPENGL_ES) +#include +#include +#else +#include +#endif #elif defined(SFML_SYSTEM_MACOS) - #include +#include -#elif defined (SFML_SYSTEM_IOS) +#elif defined(SFML_SYSTEM_IOS) - #include - #include +#include +#include -#elif defined (SFML_SYSTEM_ANDROID) +#elif defined(SFML_SYSTEM_ANDROID) - #include - #include +#include +#include - // We're not using OpenGL ES 2+ yet, but we can use the sRGB extension - #include - #include +// We're not using OpenGL ES 2+ yet, but we can use the sRGB extension +#include +#include #endif diff --git a/include/SFML/System.hpp b/include/SFML/System.hpp index f63042ce9..cee6fa265 100644 --- a/include/SFML/System.hpp +++ b/include/SFML/System.hpp @@ -30,6 +30,7 @@ //////////////////////////////////////////////////////////// #include + #include #include #include diff --git a/include/SFML/System/Angle.hpp b/include/SFML/System/Angle.hpp index fa25be05f..8cfcf4fd0 100644 --- a/include/SFML/System/Angle.hpp +++ b/include/SFML/System/Angle.hpp @@ -29,6 +29,7 @@ // Headers //////////////////////////////////////////////////////////// #include + #include @@ -41,7 +42,6 @@ namespace sf class Angle { public: - //////////////////////////////////////////////////////////// /// \brief Default constructor /// @@ -142,7 +142,6 @@ public: static const Angle Zero; //!< Predefined 0 degree angle value private: - friend constexpr Angle degrees(float angle); friend constexpr Angle radians(float angle); @@ -158,7 +157,6 @@ private: constexpr explicit Angle(float degrees); private: - //////////////////////////////////////////////////////////// // Member data //////////////////////////////////////////////////////////// @@ -199,7 +197,7 @@ private: /// \return True if both angle values are equal /// //////////////////////////////////////////////////////////// -[[nodiscard]] constexpr bool operator ==(Angle left, Angle right); +[[nodiscard]] constexpr bool operator==(Angle left, Angle right); //////////////////////////////////////////////////////////// /// \relates Angle @@ -211,7 +209,7 @@ private: /// \return True if both angle values are different /// //////////////////////////////////////////////////////////// -[[nodiscard]] constexpr bool operator !=(Angle left, Angle right); +[[nodiscard]] constexpr bool operator!=(Angle left, Angle right); //////////////////////////////////////////////////////////// /// \relates Angle @@ -223,7 +221,7 @@ private: /// \return True if \a left is less than \a right /// //////////////////////////////////////////////////////////// -[[nodiscard]] constexpr bool operator <(Angle left, Angle right); +[[nodiscard]] constexpr bool operator<(Angle left, Angle right); //////////////////////////////////////////////////////////// /// \relates Angle @@ -235,7 +233,7 @@ private: /// \return True if \a left is greater than \a right /// //////////////////////////////////////////////////////////// -[[nodiscard]] constexpr bool operator >(Angle left, Angle right); +[[nodiscard]] constexpr bool operator>(Angle left, Angle right); //////////////////////////////////////////////////////////// /// \relates Angle @@ -247,7 +245,7 @@ private: /// \return True if \a left is less than or equal to \a right /// //////////////////////////////////////////////////////////// -[[nodiscard]] constexpr bool operator <=(Angle left, Angle right); +[[nodiscard]] constexpr bool operator<=(Angle left, Angle right); //////////////////////////////////////////////////////////// /// \relates Angle @@ -259,7 +257,7 @@ private: /// \return True if \a left is greater than or equal to \a right /// //////////////////////////////////////////////////////////// -[[nodiscard]] constexpr bool operator >=(Angle left, Angle right); +[[nodiscard]] constexpr bool operator>=(Angle left, Angle right); //////////////////////////////////////////////////////////// /// \relates Angle @@ -272,7 +270,7 @@ private: /// \return Negative of the angle value /// //////////////////////////////////////////////////////////// -[[nodiscard]] constexpr Angle operator -(Angle right); +[[nodiscard]] constexpr Angle operator-(Angle right); //////////////////////////////////////////////////////////// /// \relates Angle @@ -284,7 +282,7 @@ private: /// \return Sum of the two angle values /// //////////////////////////////////////////////////////////// -[[nodiscard]] constexpr Angle operator +(Angle left, Angle right); +[[nodiscard]] constexpr Angle operator+(Angle left, Angle right); //////////////////////////////////////////////////////////// /// \relates Angle @@ -296,7 +294,7 @@ private: /// \return Sum of the two angle values /// //////////////////////////////////////////////////////////// -constexpr Angle& operator +=(Angle& left, Angle right); +constexpr Angle& operator+=(Angle& left, Angle right); //////////////////////////////////////////////////////////// /// \relates Angle @@ -308,7 +306,7 @@ constexpr Angle& operator +=(Angle& left, Angle right); /// \return Difference of the two angle values /// //////////////////////////////////////////////////////////// -[[nodiscard]] constexpr Angle operator -(Angle left, Angle right); +[[nodiscard]] constexpr Angle operator-(Angle left, Angle right); //////////////////////////////////////////////////////////// /// \relates Angle @@ -320,7 +318,7 @@ constexpr Angle& operator +=(Angle& left, Angle right); /// \return Difference of the two angle values /// //////////////////////////////////////////////////////////// -constexpr Angle& operator -=(Angle& left, Angle right); +constexpr Angle& operator-=(Angle& left, Angle right); //////////////////////////////////////////////////////////// /// \relates Angle @@ -332,7 +330,7 @@ constexpr Angle& operator -=(Angle& left, Angle right); /// \return \a left multiplied by \a right /// //////////////////////////////////////////////////////////// -[[nodiscard]] constexpr Angle operator *(Angle left, float right); +[[nodiscard]] constexpr Angle operator*(Angle left, float right); //////////////////////////////////////////////////////////// /// \relates Angle @@ -344,7 +342,7 @@ constexpr Angle& operator -=(Angle& left, Angle right); /// \return \a left multiplied by \a right /// //////////////////////////////////////////////////////////// -[[nodiscard]] constexpr Angle operator *(float left, Angle right); +[[nodiscard]] constexpr Angle operator*(float left, Angle right); //////////////////////////////////////////////////////////// /// \relates Angle @@ -356,7 +354,7 @@ constexpr Angle& operator -=(Angle& left, Angle right); /// \return \a left multiplied by \a right /// //////////////////////////////////////////////////////////// -constexpr Angle& operator *=(Angle& left, float right); +constexpr Angle& operator*=(Angle& left, float right); //////////////////////////////////////////////////////////// /// \relates Angle @@ -368,7 +366,7 @@ constexpr Angle& operator *=(Angle& left, float right); /// \return \a left divided by \a right /// //////////////////////////////////////////////////////////// -[[nodiscard]] constexpr Angle operator /(Angle left, float right); +[[nodiscard]] constexpr Angle operator/(Angle left, float right); //////////////////////////////////////////////////////////// /// \relates Angle @@ -380,7 +378,7 @@ constexpr Angle& operator *=(Angle& left, float right); /// \return \a left divided by \a right /// //////////////////////////////////////////////////////////// -constexpr Angle& operator /=(Angle& left, float right); +constexpr Angle& operator/=(Angle& left, float right); //////////////////////////////////////////////////////////// /// \relates Angle @@ -392,7 +390,7 @@ constexpr Angle& operator /=(Angle& left, float right); /// \return \a left divided by \a right /// //////////////////////////////////////////////////////////// -[[nodiscard]] constexpr float operator /(Angle left, Angle right); +[[nodiscard]] constexpr float operator/(Angle left, Angle right); //////////////////////////////////////////////////////////// /// \relates Angle @@ -412,7 +410,7 @@ constexpr Angle& operator /=(Angle& left, float right); /// \return \a left modulo \a right /// //////////////////////////////////////////////////////////// -[[nodiscard]] constexpr Angle operator %(Angle left, Angle right); +[[nodiscard]] constexpr Angle operator%(Angle left, Angle right); //////////////////////////////////////////////////////////// /// \relates Angle @@ -424,7 +422,7 @@ constexpr Angle& operator /=(Angle& left, float right); /// \return \a left modulo \a right /// //////////////////////////////////////////////////////////// -constexpr Angle& operator %=(Angle& left, Angle right); +constexpr Angle& operator%=(Angle& left, Angle right); namespace Literals { @@ -438,7 +436,7 @@ namespace Literals /// \return \a Angle /// //////////////////////////////////////////////////////////// -[[nodiscard]] constexpr Angle operator "" _deg(long double angle); +[[nodiscard]] constexpr Angle operator"" _deg(long double angle); //////////////////////////////////////////////////////////// /// \relates sf::Angle @@ -449,7 +447,7 @@ namespace Literals /// \return \a Angle /// //////////////////////////////////////////////////////////// -[[nodiscard]] constexpr Angle operator "" _deg(unsigned long long int angle); +[[nodiscard]] constexpr Angle operator"" _deg(unsigned long long int angle); //////////////////////////////////////////////////////////// /// \relates sf::Angle @@ -460,7 +458,7 @@ namespace Literals /// \return \a Angle /// //////////////////////////////////////////////////////////// -[[nodiscard]] constexpr Angle operator "" _rad(long double angle); +[[nodiscard]] constexpr Angle operator"" _rad(long double angle); //////////////////////////////////////////////////////////// /// \relates sf::Angle @@ -471,7 +469,7 @@ namespace Literals /// \return \a Angle /// //////////////////////////////////////////////////////////// -[[nodiscard]] constexpr Angle operator "" _rad(unsigned long long int angle); +[[nodiscard]] constexpr Angle operator"" _rad(unsigned long long int angle); } // namespace Literals diff --git a/include/SFML/System/Angle.inl b/include/SFML/System/Angle.inl index 447b0b2da..74a22acbc 100644 --- a/include/SFML/System/Angle.inl +++ b/include/SFML/System/Angle.inl @@ -24,23 +24,22 @@ namespace priv { - constexpr float pi = 3.141592654f; +constexpr float pi = 3.141592654f; - constexpr float positiveRemainder(float a, float b) - { - assert(b > 0.0f); - const float val = a - static_cast(static_cast(a / b)) * b; - if (val >= 0.f) - return val; - else - return val + b; - } +constexpr float positiveRemainder(float a, float b) +{ + assert(b > 0.0f); + const float val = a - static_cast(static_cast(a / b)) * b; + if (val >= 0.f) + return val; + else + return val + b; } +} // namespace priv //////////////////////////////////////////////////////////// -constexpr Angle::Angle() : -m_degrees(0.0f) +constexpr Angle::Angle() : m_degrees(0.0f) { } @@ -74,8 +73,7 @@ constexpr Angle Angle::wrapUnsigned() const //////////////////////////////////////////////////////////// -constexpr Angle::Angle(float degrees) : -m_degrees(degrees) +constexpr Angle::Angle(float degrees) : m_degrees(degrees) { } @@ -95,133 +93,133 @@ constexpr Angle radians(float angle) //////////////////////////////////////////////////////////// -constexpr bool operator ==(Angle left, Angle right) +constexpr bool operator==(Angle left, Angle right) { return left.asDegrees() == right.asDegrees(); } //////////////////////////////////////////////////////////// -constexpr bool operator !=(Angle left, Angle right) +constexpr bool operator!=(Angle left, Angle right) { return left.asDegrees() != right.asDegrees(); } //////////////////////////////////////////////////////////// -constexpr bool operator <(Angle left, Angle right) +constexpr bool operator<(Angle left, Angle right) { return left.asDegrees() < right.asDegrees(); } //////////////////////////////////////////////////////////// -constexpr bool operator >(Angle left, Angle right) +constexpr bool operator>(Angle left, Angle right) { return left.asDegrees() > right.asDegrees(); } //////////////////////////////////////////////////////////// -constexpr bool operator <=(Angle left, Angle right) +constexpr bool operator<=(Angle left, Angle right) { return left.asDegrees() <= right.asDegrees(); } //////////////////////////////////////////////////////////// -constexpr bool operator >=(Angle left, Angle right) +constexpr bool operator>=(Angle left, Angle right) { return left.asDegrees() >= right.asDegrees(); } //////////////////////////////////////////////////////////// -constexpr Angle operator -(Angle right) +constexpr Angle operator-(Angle right) { return degrees(-right.asDegrees()); } //////////////////////////////////////////////////////////// -constexpr Angle operator +(Angle left, Angle right) +constexpr Angle operator+(Angle left, Angle right) { return degrees(left.asDegrees() + right.asDegrees()); } //////////////////////////////////////////////////////////// -constexpr Angle& operator +=(Angle& left, Angle right) +constexpr Angle& operator+=(Angle& left, Angle right) { return left = left + right; } //////////////////////////////////////////////////////////// -constexpr Angle operator -(Angle left, Angle right) +constexpr Angle operator-(Angle left, Angle right) { return degrees(left.asDegrees() - right.asDegrees()); } //////////////////////////////////////////////////////////// -constexpr Angle& operator -=(Angle& left, Angle right) +constexpr Angle& operator-=(Angle& left, Angle right) { return left = left - right; } //////////////////////////////////////////////////////////// -constexpr Angle operator *(Angle left, float right) +constexpr Angle operator*(Angle left, float right) { return degrees(left.asDegrees() * right); } //////////////////////////////////////////////////////////// -constexpr Angle operator *(float left, Angle right) +constexpr Angle operator*(float left, Angle right) { return right * left; } //////////////////////////////////////////////////////////// -constexpr Angle& operator *=(Angle& left, float right) +constexpr Angle& operator*=(Angle& left, float right) { return left = left * right; } //////////////////////////////////////////////////////////// -constexpr Angle operator /(Angle left, float right) +constexpr Angle operator/(Angle left, float right) { return degrees(left.asDegrees() / right); } //////////////////////////////////////////////////////////// -constexpr Angle& operator /=(Angle& left, float right) +constexpr Angle& operator/=(Angle& left, float right) { return left = left / right; } //////////////////////////////////////////////////////////// -constexpr float operator /(Angle left, Angle right) +constexpr float operator/(Angle left, Angle right) { return left.asDegrees() / right.asDegrees(); } //////////////////////////////////////////////////////////// -constexpr Angle operator %(Angle left, Angle right) +constexpr Angle operator%(Angle left, Angle right) { return degrees(priv::positiveRemainder(left.asDegrees(), right.asDegrees())); } //////////////////////////////////////////////////////////// -constexpr Angle& operator %=(Angle& left, Angle right) +constexpr Angle& operator%=(Angle& left, Angle right) { return left = left % right; } @@ -230,28 +228,28 @@ namespace Literals { //////////////////////////////////////////////////////////// -constexpr Angle operator "" _deg(long double angle) +constexpr Angle operator"" _deg(long double angle) { return degrees(static_cast(angle)); } //////////////////////////////////////////////////////////// -constexpr Angle operator "" _deg(unsigned long long angle) +constexpr Angle operator"" _deg(unsigned long long angle) { return degrees(static_cast(angle)); } //////////////////////////////////////////////////////////// -constexpr Angle operator "" _rad(long double angle) +constexpr Angle operator"" _rad(long double angle) { return radians(static_cast(angle)); } //////////////////////////////////////////////////////////// -constexpr Angle operator "" _rad(unsigned long long angle) +constexpr Angle operator"" _rad(unsigned long long angle) { return radians(static_cast(angle)); } diff --git a/include/SFML/System/Clock.hpp b/include/SFML/System/Clock.hpp index df5d029f1..a99f849a6 100644 --- a/include/SFML/System/Clock.hpp +++ b/include/SFML/System/Clock.hpp @@ -29,6 +29,7 @@ // Headers //////////////////////////////////////////////////////////// #include + #include #include #include @@ -69,12 +70,11 @@ namespace priv /// //////////////////////////////////////////////////////////// #if defined(SFML_SYSTEM_ANDROID) && defined(SFML_ANDROID_USE_SUSPEND_AWARE_CLOCK) - using MostSuitableClock = SuspendAwareClock; +using MostSuitableClock = SuspendAwareClock; #else - using MostSuitableClock = std::conditional_t< - std::chrono::high_resolution_clock::is_steady, - std::chrono::high_resolution_clock, - std::chrono::steady_clock>; +using MostSuitableClock = std::conditional_t; #endif } // namespace priv @@ -88,7 +88,6 @@ class Time; class SFML_SYSTEM_API Clock { public: - //////////////////////////////////////////////////////////// /// \brief Default constructor /// @@ -123,10 +122,9 @@ public: private: using ClockImpl = priv::MostSuitableClock; - static_assert(ClockImpl::is_steady, - "Provided implementation is not a monotonic clock"); + static_assert(ClockImpl::is_steady, "Provided implementation is not a monotonic clock"); static_assert(std::ratio_less_equal::value, - "Clock resolution is too low. Expecting at least a microsecond precision"); + "Clock resolution is too low. Expecting at least a microsecond precision"); //////////////////////////////////////////////////////////// /// \brief Convert clock duration to Time diff --git a/include/SFML/System/Err.hpp b/include/SFML/System/Err.hpp index b7f4eae67..a02b54509 100644 --- a/include/SFML/System/Err.hpp +++ b/include/SFML/System/Err.hpp @@ -29,6 +29,7 @@ // Headers //////////////////////////////////////////////////////////// #include + #include diff --git a/include/SFML/System/Export.hpp b/include/SFML/System/Export.hpp index 013feb4b2..4deccce7a 100644 --- a/include/SFML/System/Export.hpp +++ b/include/SFML/System/Export.hpp @@ -36,11 +36,11 @@ //////////////////////////////////////////////////////////// #if defined(SFML_SYSTEM_EXPORTS) - #define SFML_SYSTEM_API SFML_API_EXPORT +#define SFML_SYSTEM_API SFML_API_EXPORT #else - #define SFML_SYSTEM_API SFML_API_IMPORT +#define SFML_SYSTEM_API SFML_API_IMPORT #endif diff --git a/include/SFML/System/FileInputStream.hpp b/include/SFML/System/FileInputStream.hpp index 9fe74543c..f704efa5d 100644 --- a/include/SFML/System/FileInputStream.hpp +++ b/include/SFML/System/FileInputStream.hpp @@ -29,12 +29,15 @@ // Headers //////////////////////////////////////////////////////////// #include + #include + #include -#include -#include + #include #include +#include +#include #ifdef SFML_SYSTEM_ANDROID namespace sf::priv @@ -140,7 +143,6 @@ public: Int64 getSize() override; private: - //////////////////////////////////////////////////////////// // Member data //////////////////////////////////////////////////////////// diff --git a/include/SFML/System/InputStream.hpp b/include/SFML/System/InputStream.hpp index cd1691706..74997d7a2 100644 --- a/include/SFML/System/InputStream.hpp +++ b/include/SFML/System/InputStream.hpp @@ -29,6 +29,7 @@ // Headers //////////////////////////////////////////////////////////// #include + #include @@ -41,12 +42,13 @@ namespace sf class SFML_SYSTEM_API InputStream { public: - //////////////////////////////////////////////////////////// /// \brief Virtual destructor /// //////////////////////////////////////////////////////////// - virtual ~InputStream() {} + virtual ~InputStream() + { + } //////////////////////////////////////////////////////////// /// \brief Read data from the stream diff --git a/include/SFML/System/MemoryInputStream.hpp b/include/SFML/System/MemoryInputStream.hpp index 4b9b92870..4dd0df5ea 100644 --- a/include/SFML/System/MemoryInputStream.hpp +++ b/include/SFML/System/MemoryInputStream.hpp @@ -29,8 +29,11 @@ // Headers //////////////////////////////////////////////////////////// #include -#include + #include + +#include + #include @@ -43,7 +46,6 @@ namespace sf class SFML_SYSTEM_API MemoryInputStream : public InputStream { public: - //////////////////////////////////////////////////////////// /// \brief Default constructor /// @@ -100,7 +102,6 @@ public: Int64 getSize() override; private: - //////////////////////////////////////////////////////////// // Member data //////////////////////////////////////////////////////////// diff --git a/include/SFML/System/String.hpp b/include/SFML/System/String.hpp index 48ab40d2b..6b1c5eeb8 100644 --- a/include/SFML/System/String.hpp +++ b/include/SFML/System/String.hpp @@ -29,7 +29,9 @@ // Headers //////////////////////////////////////////////////////////// #include + #include + #include #include #include @@ -45,11 +47,10 @@ namespace sf class SFML_SYSTEM_API String { public: - //////////////////////////////////////////////////////////// // Types //////////////////////////////////////////////////////////// - using Iterator = std::basic_string::iterator; //!< Iterator type + using Iterator = std::basic_string::iterator; //!< Iterator type using ConstIterator = std::basic_string::const_iterator; //!< Read-only iterator type //////////////////////////////////////////////////////////// @@ -318,7 +319,7 @@ public: /// \return Reference to self /// //////////////////////////////////////////////////////////// - String& operator =(const String& right); + String& operator=(const String& right); //////////////////////////////////////////////////////////// /// \brief Overload of += operator to append an UTF-32 string @@ -328,7 +329,7 @@ public: /// \return Reference to self /// //////////////////////////////////////////////////////////// - String& operator +=(const String& right); + String& operator+=(const String& right); //////////////////////////////////////////////////////////// /// \brief Overload of [] operator to access a character by its position @@ -341,7 +342,7 @@ public: /// \return Character at position \a index /// //////////////////////////////////////////////////////////// - Uint32 operator [](std::size_t index) const; + Uint32 operator[](std::size_t index) const; //////////////////////////////////////////////////////////// /// \brief Overload of [] operator to access a character by its position @@ -354,7 +355,7 @@ public: /// \return Reference to the character at position \a index /// //////////////////////////////////////////////////////////// - Uint32& operator [](std::size_t index); + Uint32& operator[](std::size_t index); //////////////////////////////////////////////////////////// /// \brief Clear the string @@ -529,9 +530,8 @@ public: ConstIterator end() const; private: - - friend SFML_SYSTEM_API bool operator ==(const String& left, const String& right); - friend SFML_SYSTEM_API bool operator <(const String& left, const String& right); + friend SFML_SYSTEM_API bool operator==(const String& left, const String& right); + friend SFML_SYSTEM_API bool operator<(const String& left, const String& right); //////////////////////////////////////////////////////////// // Member data @@ -549,7 +549,7 @@ private: /// \return True if both strings are equal /// //////////////////////////////////////////////////////////// -SFML_SYSTEM_API bool operator ==(const String& left, const String& right); +SFML_SYSTEM_API bool operator==(const String& left, const String& right); //////////////////////////////////////////////////////////// /// \relates String @@ -561,7 +561,7 @@ SFML_SYSTEM_API bool operator ==(const String& left, const String& right); /// \return True if both strings are different /// //////////////////////////////////////////////////////////// -SFML_SYSTEM_API bool operator !=(const String& left, const String& right); +SFML_SYSTEM_API bool operator!=(const String& left, const String& right); //////////////////////////////////////////////////////////// /// \relates String @@ -573,7 +573,7 @@ SFML_SYSTEM_API bool operator !=(const String& left, const String& right); /// \return True if \a left is lexicographically before \a right /// //////////////////////////////////////////////////////////// -SFML_SYSTEM_API bool operator <(const String& left, const String& right); +SFML_SYSTEM_API bool operator<(const String& left, const String& right); //////////////////////////////////////////////////////////// /// \relates String @@ -585,7 +585,7 @@ SFML_SYSTEM_API bool operator <(const String& left, const String& right); /// \return True if \a left is lexicographically after \a right /// //////////////////////////////////////////////////////////// -SFML_SYSTEM_API bool operator >(const String& left, const String& right); +SFML_SYSTEM_API bool operator>(const String& left, const String& right); //////////////////////////////////////////////////////////// /// \relates String @@ -597,7 +597,7 @@ SFML_SYSTEM_API bool operator >(const String& left, const String& right); /// \return True if \a left is lexicographically before or equivalent to \a right /// //////////////////////////////////////////////////////////// -SFML_SYSTEM_API bool operator <=(const String& left, const String& right); +SFML_SYSTEM_API bool operator<=(const String& left, const String& right); //////////////////////////////////////////////////////////// /// \relates String @@ -609,7 +609,7 @@ SFML_SYSTEM_API bool operator <=(const String& left, const String& right); /// \return True if \a left is lexicographically after or equivalent to \a right /// //////////////////////////////////////////////////////////// -SFML_SYSTEM_API bool operator >=(const String& left, const String& right); +SFML_SYSTEM_API bool operator>=(const String& left, const String& right); //////////////////////////////////////////////////////////// /// \relates String @@ -621,7 +621,7 @@ SFML_SYSTEM_API bool operator >=(const String& left, const String& right); /// \return Concatenated string /// //////////////////////////////////////////////////////////// -SFML_SYSTEM_API String operator +(const String& left, const String& right); +SFML_SYSTEM_API String operator+(const String& left, const String& right); #include diff --git a/include/SFML/System/SuspendAwareClock.hpp b/include/SFML/System/SuspendAwareClock.hpp index 38d13a293..79dc2ce8f 100644 --- a/include/SFML/System/SuspendAwareClock.hpp +++ b/include/SFML/System/SuspendAwareClock.hpp @@ -30,6 +30,7 @@ // Headers //////////////////////////////////////////////////////////// #include + #include @@ -64,9 +65,9 @@ public: /// https://en.cppreference.com/w/cpp/chrono/is_clock /// //////////////////////////////////////////////////////////// - using duration = std::chrono::nanoseconds; - using rep = duration::rep; - using period = duration::period; + using duration = std::chrono::nanoseconds; + using rep = duration::rep; + using period = duration::period; using time_point = std::chrono::time_point; static constexpr bool is_steady = true; diff --git a/include/SFML/System/Time.hpp b/include/SFML/System/Time.hpp index cf7ddef24..79bc3c760 100644 --- a/include/SFML/System/Time.hpp +++ b/include/SFML/System/Time.hpp @@ -40,7 +40,6 @@ namespace sf class Time { public: - //////////////////////////////////////////////////////////// /// \brief Default constructor /// @@ -85,7 +84,6 @@ public: static const Time Zero; //!< Predefined "zero" time value private: - friend constexpr Time seconds(float); friend constexpr Time milliseconds(Int32); friend constexpr Time microseconds(Int64); @@ -102,7 +100,6 @@ private: constexpr explicit Time(Int64 microseconds); private: - //////////////////////////////////////////////////////////// // Member data //////////////////////////////////////////////////////////// @@ -158,7 +155,7 @@ constexpr Time microseconds(Int64 amount); /// \return True if both time values are equal /// //////////////////////////////////////////////////////////// -[[nodiscard]] constexpr bool operator ==(Time left, Time right); +[[nodiscard]] constexpr bool operator==(Time left, Time right); //////////////////////////////////////////////////////////// /// \relates Time @@ -170,7 +167,7 @@ constexpr Time microseconds(Int64 amount); /// \return True if both time values are different /// //////////////////////////////////////////////////////////// -[[nodiscard]] constexpr bool operator !=(Time left, Time right); +[[nodiscard]] constexpr bool operator!=(Time left, Time right); //////////////////////////////////////////////////////////// /// \relates Time @@ -182,7 +179,7 @@ constexpr Time microseconds(Int64 amount); /// \return True if \a left is lesser than \a right /// //////////////////////////////////////////////////////////// -[[nodiscard]] constexpr bool operator <(Time left, Time right); +[[nodiscard]] constexpr bool operator<(Time left, Time right); //////////////////////////////////////////////////////////// /// \relates Time @@ -194,7 +191,7 @@ constexpr Time microseconds(Int64 amount); /// \return True if \a left is greater than \a right /// //////////////////////////////////////////////////////////// -[[nodiscard]] constexpr bool operator >(Time left, Time right); +[[nodiscard]] constexpr bool operator>(Time left, Time right); //////////////////////////////////////////////////////////// /// \relates Time @@ -206,7 +203,7 @@ constexpr Time microseconds(Int64 amount); /// \return True if \a left is lesser or equal than \a right /// //////////////////////////////////////////////////////////// -[[nodiscard]] constexpr bool operator <=(Time left, Time right); +[[nodiscard]] constexpr bool operator<=(Time left, Time right); //////////////////////////////////////////////////////////// /// \relates Time @@ -218,7 +215,7 @@ constexpr Time microseconds(Int64 amount); /// \return True if \a left is greater or equal than \a right /// //////////////////////////////////////////////////////////// -[[nodiscard]] constexpr bool operator >=(Time left, Time right); +[[nodiscard]] constexpr bool operator>=(Time left, Time right); //////////////////////////////////////////////////////////// /// \relates Time @@ -229,7 +226,7 @@ constexpr Time microseconds(Int64 amount); /// \return Opposite of the time value /// //////////////////////////////////////////////////////////// -[[nodiscard]] constexpr Time operator -(Time right); +[[nodiscard]] constexpr Time operator-(Time right); //////////////////////////////////////////////////////////// /// \relates Time @@ -241,7 +238,7 @@ constexpr Time microseconds(Int64 amount); /// \return Sum of the two times values /// //////////////////////////////////////////////////////////// -[[nodiscard]] constexpr Time operator +(Time left, Time right); +[[nodiscard]] constexpr Time operator+(Time left, Time right); //////////////////////////////////////////////////////////// /// \relates Time @@ -253,7 +250,7 @@ constexpr Time microseconds(Int64 amount); /// \return Sum of the two times values /// //////////////////////////////////////////////////////////// -constexpr Time& operator +=(Time& left, Time right); +constexpr Time& operator+=(Time& left, Time right); //////////////////////////////////////////////////////////// /// \relates Time @@ -265,7 +262,7 @@ constexpr Time& operator +=(Time& left, Time right); /// \return Difference of the two times values /// //////////////////////////////////////////////////////////// -[[nodiscard]] constexpr Time operator -(Time left, Time right); +[[nodiscard]] constexpr Time operator-(Time left, Time right); //////////////////////////////////////////////////////////// /// \relates Time @@ -277,7 +274,7 @@ constexpr Time& operator +=(Time& left, Time right); /// \return Difference of the two times values /// //////////////////////////////////////////////////////////// -constexpr Time& operator -=(Time& left, Time right); +constexpr Time& operator-=(Time& left, Time right); //////////////////////////////////////////////////////////// /// \relates Time @@ -289,7 +286,7 @@ constexpr Time& operator -=(Time& left, Time right); /// \return \a left multiplied by \a right /// //////////////////////////////////////////////////////////// -[[nodiscard]] constexpr Time operator *(Time left, float right); +[[nodiscard]] constexpr Time operator*(Time left, float right); //////////////////////////////////////////////////////////// /// \relates Time @@ -301,7 +298,7 @@ constexpr Time& operator -=(Time& left, Time right); /// \return \a left multiplied by \a right /// //////////////////////////////////////////////////////////// -[[nodiscard]] constexpr Time operator *(Time left, Int64 right); +[[nodiscard]] constexpr Time operator*(Time left, Int64 right); //////////////////////////////////////////////////////////// /// \relates Time @@ -313,7 +310,7 @@ constexpr Time& operator -=(Time& left, Time right); /// \return \a left multiplied by \a right /// //////////////////////////////////////////////////////////// -[[nodiscard]] constexpr Time operator *(float left, Time right); +[[nodiscard]] constexpr Time operator*(float left, Time right); //////////////////////////////////////////////////////////// /// \relates Time @@ -325,7 +322,7 @@ constexpr Time& operator -=(Time& left, Time right); /// \return \a left multiplied by \a right /// //////////////////////////////////////////////////////////// -[[nodiscard]] constexpr Time operator *(Int64 left, Time right); +[[nodiscard]] constexpr Time operator*(Int64 left, Time right); //////////////////////////////////////////////////////////// /// \relates Time @@ -337,7 +334,7 @@ constexpr Time& operator -=(Time& left, Time right); /// \return \a left multiplied by \a right /// //////////////////////////////////////////////////////////// -constexpr Time& operator *=(Time& left, float right); +constexpr Time& operator*=(Time& left, float right); //////////////////////////////////////////////////////////// /// \relates Time @@ -349,7 +346,7 @@ constexpr Time& operator *=(Time& left, float right); /// \return \a left multiplied by \a right /// //////////////////////////////////////////////////////////// -constexpr Time& operator *=(Time& left, Int64 right); +constexpr Time& operator*=(Time& left, Int64 right); //////////////////////////////////////////////////////////// /// \relates Time @@ -361,7 +358,7 @@ constexpr Time& operator *=(Time& left, Int64 right); /// \return \a left divided by \a right /// //////////////////////////////////////////////////////////// -[[nodiscard]] constexpr Time operator /(Time left, float right); +[[nodiscard]] constexpr Time operator/(Time left, float right); //////////////////////////////////////////////////////////// /// \relates Time @@ -373,7 +370,7 @@ constexpr Time& operator *=(Time& left, Int64 right); /// \return \a left divided by \a right /// //////////////////////////////////////////////////////////// -[[nodiscard]] constexpr Time operator /(Time left, Int64 right); +[[nodiscard]] constexpr Time operator/(Time left, Int64 right); //////////////////////////////////////////////////////////// /// \relates Time @@ -385,7 +382,7 @@ constexpr Time& operator *=(Time& left, Int64 right); /// \return \a left divided by \a right /// //////////////////////////////////////////////////////////// -constexpr Time& operator /=(Time& left, float right); +constexpr Time& operator/=(Time& left, float right); //////////////////////////////////////////////////////////// /// \relates Time @@ -397,7 +394,7 @@ constexpr Time& operator /=(Time& left, float right); /// \return \a left divided by \a right /// //////////////////////////////////////////////////////////// -constexpr Time& operator /=(Time& left, Int64 right); +constexpr Time& operator/=(Time& left, Int64 right); //////////////////////////////////////////////////////////// /// \relates Time @@ -409,7 +406,7 @@ constexpr Time& operator /=(Time& left, Int64 right); /// \return \a left divided by \a right /// //////////////////////////////////////////////////////////// -[[nodiscard]] constexpr float operator /(Time left, Time right); +[[nodiscard]] constexpr float operator/(Time left, Time right); //////////////////////////////////////////////////////////// /// \relates Time @@ -421,7 +418,7 @@ constexpr Time& operator /=(Time& left, Int64 right); /// \return \a left modulo \a right /// //////////////////////////////////////////////////////////// -[[nodiscard]] constexpr Time operator %(Time left, Time right); +[[nodiscard]] constexpr Time operator%(Time left, Time right); //////////////////////////////////////////////////////////// /// \relates Time @@ -433,7 +430,7 @@ constexpr Time& operator /=(Time& left, Int64 right); /// \return \a left modulo \a right /// //////////////////////////////////////////////////////////// -constexpr Time& operator %=(Time& left, Time right); +constexpr Time& operator%=(Time& left, Time right); #include diff --git a/include/SFML/System/Time.inl b/include/SFML/System/Time.inl index 892cd72da..39fdb5ce1 100644 --- a/include/SFML/System/Time.inl +++ b/include/SFML/System/Time.inl @@ -24,8 +24,7 @@ //////////////////////////////////////////////////////////// -constexpr Time::Time() : -m_microseconds(0) +constexpr Time::Time() : m_microseconds(0) { } @@ -52,8 +51,7 @@ constexpr Int64 Time::asMicroseconds() const //////////////////////////////////////////////////////////// -constexpr Time::Time(Int64 microseconds) : -m_microseconds(microseconds) +constexpr Time::Time(Int64 microseconds) : m_microseconds(microseconds) { } @@ -80,168 +78,168 @@ constexpr Time microseconds(Int64 amount) //////////////////////////////////////////////////////////// -constexpr bool operator ==(Time left, Time right) +constexpr bool operator==(Time left, Time right) { return left.asMicroseconds() == right.asMicroseconds(); } //////////////////////////////////////////////////////////// -constexpr bool operator !=(Time left, Time right) +constexpr bool operator!=(Time left, Time right) { return left.asMicroseconds() != right.asMicroseconds(); } //////////////////////////////////////////////////////////// -constexpr bool operator <(Time left, Time right) +constexpr bool operator<(Time left, Time right) { return left.asMicroseconds() < right.asMicroseconds(); } //////////////////////////////////////////////////////////// -constexpr bool operator >(Time left, Time right) +constexpr bool operator>(Time left, Time right) { return left.asMicroseconds() > right.asMicroseconds(); } //////////////////////////////////////////////////////////// -constexpr bool operator <=(Time left, Time right) +constexpr bool operator<=(Time left, Time right) { return left.asMicroseconds() <= right.asMicroseconds(); } //////////////////////////////////////////////////////////// -constexpr bool operator >=(Time left, Time right) +constexpr bool operator>=(Time left, Time right) { return left.asMicroseconds() >= right.asMicroseconds(); } //////////////////////////////////////////////////////////// -constexpr Time operator -(Time right) +constexpr Time operator-(Time right) { return microseconds(-right.asMicroseconds()); } //////////////////////////////////////////////////////////// -constexpr Time operator +(Time left, Time right) +constexpr Time operator+(Time left, Time right) { return microseconds(left.asMicroseconds() + right.asMicroseconds()); } //////////////////////////////////////////////////////////// -constexpr Time& operator +=(Time& left, Time right) +constexpr Time& operator+=(Time& left, Time right) { return left = left + right; } //////////////////////////////////////////////////////////// -constexpr Time operator -(Time left, Time right) +constexpr Time operator-(Time left, Time right) { return microseconds(left.asMicroseconds() - right.asMicroseconds()); } //////////////////////////////////////////////////////////// -constexpr Time& operator -=(Time& left, Time right) +constexpr Time& operator-=(Time& left, Time right) { return left = left - right; } //////////////////////////////////////////////////////////// -constexpr Time operator *(Time left, float right) +constexpr Time operator*(Time left, float right) { return seconds(left.asSeconds() * right); } //////////////////////////////////////////////////////////// -constexpr Time operator *(Time left, Int64 right) +constexpr Time operator*(Time left, Int64 right) { return microseconds(left.asMicroseconds() * right); } //////////////////////////////////////////////////////////// -constexpr Time operator *(float left, Time right) +constexpr Time operator*(float left, Time right) { return right * left; } //////////////////////////////////////////////////////////// -constexpr Time operator *(Int64 left, Time right) +constexpr Time operator*(Int64 left, Time right) { return right * left; } //////////////////////////////////////////////////////////// -constexpr Time& operator *=(Time& left, float right) +constexpr Time& operator*=(Time& left, float right) { return left = left * right; } //////////////////////////////////////////////////////////// -constexpr Time& operator *=(Time& left, Int64 right) +constexpr Time& operator*=(Time& left, Int64 right) { return left = left * right; } //////////////////////////////////////////////////////////// -constexpr Time operator /(Time left, float right) +constexpr Time operator/(Time left, float right) { return seconds(left.asSeconds() / right); } //////////////////////////////////////////////////////////// -constexpr Time operator /(Time left, Int64 right) +constexpr Time operator/(Time left, Int64 right) { return microseconds(left.asMicroseconds() / right); } //////////////////////////////////////////////////////////// -constexpr Time& operator /=(Time& left, float right) +constexpr Time& operator/=(Time& left, float right) { return left = left / right; } //////////////////////////////////////////////////////////// -constexpr Time& operator /=(Time& left, Int64 right) +constexpr Time& operator/=(Time& left, Int64 right) { return left = left / right; } //////////////////////////////////////////////////////////// -constexpr float operator /(Time left, Time right) +constexpr float operator/(Time left, Time right) { return left.asSeconds() / right.asSeconds(); } //////////////////////////////////////////////////////////// -constexpr Time operator %(Time left, Time right) +constexpr Time operator%(Time left, Time right) { return microseconds(left.asMicroseconds() % right.asMicroseconds()); } //////////////////////////////////////////////////////////// -constexpr Time& operator %=(Time& left, Time right) +constexpr Time& operator%=(Time& left, Time right) { return left = left % right; } diff --git a/include/SFML/System/Utf.hpp b/include/SFML/System/Utf.hpp index 8f6294751..f2fde20d8 100644 --- a/include/SFML/System/Utf.hpp +++ b/include/SFML/System/Utf.hpp @@ -29,18 +29,19 @@ // Headers //////////////////////////////////////////////////////////// #include + +#include #include #include #include -#include namespace sf { namespace priv { - template - OutputIt copy(InputIt first, InputIt last, OutputIt d_first); +template +OutputIt copy(InputIt first, InputIt last, OutputIt d_first); } template @@ -54,7 +55,6 @@ template <> class Utf<8> { public: - //////////////////////////////////////////////////////////// /// \brief Decode a single UTF-8 character /// @@ -261,7 +261,6 @@ template <> class Utf<16> { public: - //////////////////////////////////////////////////////////// /// \brief Decode a single UTF-16 character /// @@ -468,7 +467,6 @@ template <> class Utf<32> { public: - //////////////////////////////////////////////////////////// /// \brief Decode a single UTF-32 character /// @@ -737,7 +735,7 @@ public: #include // Make type aliases to get rid of the template syntax -using Utf8 = Utf<8>; +using Utf8 = Utf<8>; using Utf16 = Utf<16>; using Utf32 = Utf<32>; diff --git a/include/SFML/System/Utf.inl b/include/SFML/System/Utf.inl index da400c8dd..e3bd5a2d3 100644 --- a/include/SFML/System/Utf.inl +++ b/include/SFML/System/Utf.inl @@ -90,7 +90,7 @@ In Utf<8>::decode(In begin, In end, Uint32& output, Uint32 replacement) else { // Incomplete character - begin = end; + begin = end; output = replacement; } @@ -103,10 +103,7 @@ template Out Utf<8>::encode(Uint32 input, Out output, Uint8 replacement) { // Some useful precomputed data - static constexpr Uint8 firstBytes[7] = - { - 0x00, 0x00, 0xC0, 0xE0, 0xF0, 0xF8, 0xFC - }; + static constexpr Uint8 firstBytes[7] = {0x00, 0x00, 0xC0, 0xE0, 0xF0, 0xF8, 0xFC}; // encode the character if ((input > 0x0010FFFF) || ((input >= 0xD800) && (input <= 0xDBFF))) @@ -181,7 +178,7 @@ Out Utf<8>::fromAnsi(In begin, In end, Out output, const std::locale& locale) while (begin < end) { Uint32 codepoint = Utf<32>::decodeAnsi(*begin++, locale); - output = encode(codepoint, output); + output = encode(codepoint, output); } return output; @@ -195,7 +192,7 @@ Out Utf<8>::fromWide(In begin, In end, Out output) while (begin < end) { Uint32 codepoint = Utf<32>::decodeWide(*begin++); - output = encode(codepoint, output); + output = encode(codepoint, output); } return output; @@ -222,7 +219,7 @@ Out Utf<8>::toAnsi(In begin, In end, Out output, char replacement, const std::lo while (begin < end) { Uint32 codepoint; - begin = decode(begin, end, codepoint); + begin = decode(begin, end, codepoint); output = Utf<32>::encodeAnsi(codepoint, output, replacement, locale); } @@ -237,7 +234,7 @@ Out Utf<8>::toWide(In begin, In end, Out output, wchar_t replacement) while (begin < end) { Uint32 codepoint; - begin = decode(begin, end, codepoint); + begin = decode(begin, end, codepoint); output = Utf<32>::encodeWide(codepoint, output, replacement); } @@ -254,7 +251,7 @@ Out Utf<8>::toLatin1(In begin, In end, Out output, char replacement) while (begin < end) { Uint32 codepoint; - begin = decode(begin, end, codepoint); + begin = decode(begin, end, codepoint); *output++ = codepoint < 256 ? static_cast(codepoint) : replacement; } @@ -277,7 +274,7 @@ Out Utf<8>::toUtf16(In begin, In end, Out output) while (begin < end) { Uint32 codepoint; - begin = decode(begin, end, codepoint); + begin = decode(begin, end, codepoint); output = Utf<16>::encode(codepoint, output); } @@ -292,7 +289,7 @@ Out Utf<8>::toUtf32(In begin, In end, Out output) while (begin < end) { Uint32 codepoint; - begin = decode(begin, end, codepoint); + begin = decode(begin, end, codepoint); *output++ = codepoint; } @@ -326,7 +323,7 @@ In Utf<16>::decode(In begin, In end, Uint32& output, Uint32 replacement) else { // Invalid character - begin = end; + begin = end; output = replacement; } } @@ -369,7 +366,7 @@ Out Utf<16>::encode(Uint32 input, Out output, Uint16 replacement) { // The input character will be converted to two UTF-16 elements input -= 0x0010000; - *output++ = static_cast((input >> 10) + 0xD800); + *output++ = static_cast((input >> 10) + 0xD800); *output++ = static_cast((input & 0x3FFUL) + 0xDC00); } @@ -408,7 +405,7 @@ Out Utf<16>::fromAnsi(In begin, In end, Out output, const std::locale& locale) while (begin < end) { Uint32 codepoint = Utf<32>::decodeAnsi(*begin++, locale); - output = encode(codepoint, output); + output = encode(codepoint, output); } return output; @@ -422,7 +419,7 @@ Out Utf<16>::fromWide(In begin, In end, Out output) while (begin < end) { Uint32 codepoint = Utf<32>::decodeWide(*begin++); - output = encode(codepoint, output); + output = encode(codepoint, output); } return output; @@ -446,7 +443,7 @@ Out Utf<16>::toAnsi(In begin, In end, Out output, char replacement, const std::l while (begin < end) { Uint32 codepoint; - begin = decode(begin, end, codepoint); + begin = decode(begin, end, codepoint); output = Utf<32>::encodeAnsi(codepoint, output, replacement, locale); } @@ -461,7 +458,7 @@ Out Utf<16>::toWide(In begin, In end, Out output, wchar_t replacement) while (begin < end) { Uint32 codepoint; - begin = decode(begin, end, codepoint); + begin = decode(begin, end, codepoint); output = Utf<32>::encodeWide(codepoint, output, replacement); } @@ -492,7 +489,7 @@ Out Utf<16>::toUtf8(In begin, In end, Out output) while (begin < end) { Uint32 codepoint; - begin = decode(begin, end, codepoint); + begin = decode(begin, end, codepoint); output = Utf<8>::encode(codepoint, output); } @@ -515,7 +512,7 @@ Out Utf<16>::toUtf32(In begin, In end, Out output) while (begin < end) { Uint32 codepoint; - begin = decode(begin, end, codepoint); + begin = decode(begin, end, codepoint); *output++ = codepoint; } @@ -665,23 +662,23 @@ Uint32 Utf<32>::decodeAnsi(In input, [[maybe_unused]] const std::locale& locale) // context we can only use the default locale and ignore // the one passed as parameter. - #if defined(SFML_SYSTEM_WINDOWS) && /* if Windows ... */ \ - (defined(__GLIBCPP__) || defined (__GLIBCXX__)) && /* ... and standard library is glibc++ ... */ \ - !(defined(__SGI_STL_PORT) || defined(_STLPORT_VERSION)) /* ... and STLPort is not used on top of it */ +#if defined(SFML_SYSTEM_WINDOWS) && /* if Windows ... */ \ + (defined(__GLIBCPP__) || defined(__GLIBCXX__)) && /* ... and standard library is glibc++ ... */ \ + !(defined(__SGI_STL_PORT) || defined(_STLPORT_VERSION)) /* ... and STLPort is not used on top of it */ - wchar_t character = 0; - mbtowc(&character, &input, 1); - return static_cast(character); + wchar_t character = 0; + mbtowc(&character, &input, 1); + return static_cast(character); - #else +#else - // Get the facet of the locale which deals with character conversion - const auto& facet = std::use_facet< std::ctype >(locale); + // Get the facet of the locale which deals with character conversion + const auto& facet = std::use_facet>(locale); - // Use the facet to convert each character of the input string - return static_cast(facet.widen(input)); + // Use the facet to convert each character of the input string + return static_cast(facet.widen(input)); - #endif +#endif } @@ -708,29 +705,29 @@ Out Utf<32>::encodeAnsi(Uint32 codepoint, Out output, char replacement, [[maybe_ // context we can only use the default locale and ignore // the one passed as parameter. - #if defined(SFML_SYSTEM_WINDOWS) && /* if Windows ... */ \ - (defined(__GLIBCPP__) || defined (__GLIBCXX__)) && /* ... and standard library is glibc++ ... */ \ - !(defined(__SGI_STL_PORT) || defined(_STLPORT_VERSION)) /* ... and STLPort is not used on top of it */ +#if defined(SFML_SYSTEM_WINDOWS) && /* if Windows ... */ \ + (defined(__GLIBCPP__) || defined(__GLIBCXX__)) && /* ... and standard library is glibc++ ... */ \ + !(defined(__SGI_STL_PORT) || defined(_STLPORT_VERSION)) /* ... and STLPort is not used on top of it */ - char character = 0; - if (wctomb(&character, static_cast(codepoint)) >= 0) - *output++ = character; - else if (replacement) - *output++ = replacement; + char character = 0; + if (wctomb(&character, static_cast(codepoint)) >= 0) + *output++ = character; + else if (replacement) + *output++ = replacement; - return output; + return output; - #else +#else - // Get the facet of the locale which deals with character conversion - const auto& facet = std::use_facet< std::ctype >(locale); + // Get the facet of the locale which deals with character conversion + const auto& facet = std::use_facet>(locale); - // Use the facet to convert each character of the input string - *output++ = facet.narrow(static_cast(codepoint), replacement); + // Use the facet to convert each character of the input string + *output++ = facet.narrow(static_cast(codepoint), replacement); - return output; + return output; - #endif +#endif } diff --git a/include/SFML/System/Vector2.hpp b/include/SFML/System/Vector2.hpp index c6be58f65..9374a394b 100644 --- a/include/SFML/System/Vector2.hpp +++ b/include/SFML/System/Vector2.hpp @@ -25,8 +25,10 @@ #ifndef SFML_VECTOR2_HPP #define SFML_VECTOR2_HPP -#include #include + +#include + #include @@ -41,7 +43,6 @@ template class Vector2 { public: - //////////////////////////////////////////////////////////// /// \brief Default constructor /// @@ -235,7 +236,7 @@ using Vector2f = Vector2; /// //////////////////////////////////////////////////////////// template -[[nodiscard]] constexpr Vector2 operator -(const Vector2& right); +[[nodiscard]] constexpr Vector2 operator-(const Vector2& right); //////////////////////////////////////////////////////////// /// \relates Vector2 @@ -251,7 +252,7 @@ template /// //////////////////////////////////////////////////////////// template -constexpr Vector2& operator +=(Vector2& left, const Vector2& right); +constexpr Vector2& operator+=(Vector2& left, const Vector2& right); //////////////////////////////////////////////////////////// /// \relates Vector2 @@ -267,7 +268,7 @@ constexpr Vector2& operator +=(Vector2& left, const Vector2& right); /// //////////////////////////////////////////////////////////// template -constexpr Vector2& operator -=(Vector2& left, const Vector2& right); +constexpr Vector2& operator-=(Vector2& left, const Vector2& right); //////////////////////////////////////////////////////////// /// \relates Vector2 @@ -280,7 +281,7 @@ constexpr Vector2& operator -=(Vector2& left, const Vector2& right); /// //////////////////////////////////////////////////////////// template -[[nodiscard]] constexpr Vector2 operator +(const Vector2& left, const Vector2& right); +[[nodiscard]] constexpr Vector2 operator+(const Vector2& left, const Vector2& right); //////////////////////////////////////////////////////////// /// \relates Vector2 @@ -293,7 +294,7 @@ template /// //////////////////////////////////////////////////////////// template -[[nodiscard]] constexpr Vector2 operator -(const Vector2& left, const Vector2& right); +[[nodiscard]] constexpr Vector2 operator-(const Vector2& left, const Vector2& right); //////////////////////////////////////////////////////////// /// \relates Vector2 @@ -306,7 +307,7 @@ template /// //////////////////////////////////////////////////////////// template -[[nodiscard]] constexpr Vector2 operator *(const Vector2& left, T right); +[[nodiscard]] constexpr Vector2 operator*(const Vector2& left, T right); //////////////////////////////////////////////////////////// /// \relates Vector2 @@ -319,7 +320,7 @@ template /// //////////////////////////////////////////////////////////// template -[[nodiscard]] constexpr Vector2 operator *(T left, const Vector2& right); +[[nodiscard]] constexpr Vector2 operator*(T left, const Vector2& right); //////////////////////////////////////////////////////////// /// \relates Vector2 @@ -335,7 +336,7 @@ template /// //////////////////////////////////////////////////////////// template -constexpr Vector2& operator *=(Vector2& left, T right); +constexpr Vector2& operator*=(Vector2& left, T right); //////////////////////////////////////////////////////////// /// \relates Vector2 @@ -348,7 +349,7 @@ constexpr Vector2& operator *=(Vector2& left, T right); /// //////////////////////////////////////////////////////////// template -[[nodiscard]] constexpr Vector2 operator /(const Vector2& left, T right); +[[nodiscard]] constexpr Vector2 operator/(const Vector2& left, T right); //////////////////////////////////////////////////////////// /// \relates Vector2 @@ -364,7 +365,7 @@ template /// //////////////////////////////////////////////////////////// template -constexpr Vector2& operator /=(Vector2& left, T right); +constexpr Vector2& operator/=(Vector2& left, T right); //////////////////////////////////////////////////////////// /// \relates Vector2 @@ -379,7 +380,7 @@ constexpr Vector2& operator /=(Vector2& left, T right); /// //////////////////////////////////////////////////////////// template -[[nodiscard]] constexpr bool operator ==(const Vector2& left, const Vector2& right); +[[nodiscard]] constexpr bool operator==(const Vector2& left, const Vector2& right); //////////////////////////////////////////////////////////// /// \relates Vector2 @@ -394,7 +395,7 @@ template /// //////////////////////////////////////////////////////////// template -[[nodiscard]] constexpr bool operator !=(const Vector2& left, const Vector2& right); +[[nodiscard]] constexpr bool operator!=(const Vector2& left, const Vector2& right); #include diff --git a/include/SFML/System/Vector2.inl b/include/SFML/System/Vector2.inl index e29b3967f..b0e78378a 100644 --- a/include/SFML/System/Vector2.inl +++ b/include/SFML/System/Vector2.inl @@ -25,30 +25,22 @@ //////////////////////////////////////////////////////////// template -constexpr Vector2::Vector2() : -x(0), -y(0) +constexpr Vector2::Vector2() : x(0), y(0) { - } //////////////////////////////////////////////////////////// template -constexpr Vector2::Vector2(T X, T Y) : -x(X), -y(Y) +constexpr Vector2::Vector2(T X, T Y) : x(X), y(Y) { - } //////////////////////////////////////////////////////////// template template -constexpr Vector2::Vector2(const Vector2& vector) : -x(static_cast(vector.x)), -y(static_cast(vector.y)) +constexpr Vector2::Vector2(const Vector2& vector) : x(static_cast(vector.x)), y(static_cast(vector.y)) { } @@ -105,7 +97,7 @@ constexpr Vector2 Vector2::cwiseDiv(const Vector2& rhs) const //////////////////////////////////////////////////////////// template -constexpr Vector2 operator -(const Vector2& right) +constexpr Vector2 operator-(const Vector2& right) { return Vector2(-right.x, -right.y); } @@ -113,7 +105,7 @@ constexpr Vector2 operator -(const Vector2& right) //////////////////////////////////////////////////////////// template -constexpr Vector2& operator +=(Vector2& left, const Vector2& right) +constexpr Vector2& operator+=(Vector2& left, const Vector2& right) { left.x += right.x; left.y += right.y; @@ -124,7 +116,7 @@ constexpr Vector2& operator +=(Vector2& left, const Vector2& right) //////////////////////////////////////////////////////////// template -constexpr Vector2& operator -=(Vector2& left, const Vector2& right) +constexpr Vector2& operator-=(Vector2& left, const Vector2& right) { left.x -= right.x; left.y -= right.y; @@ -135,7 +127,7 @@ constexpr Vector2& operator -=(Vector2& left, const Vector2& right) //////////////////////////////////////////////////////////// template -constexpr Vector2 operator +(const Vector2& left, const Vector2& right) +constexpr Vector2 operator+(const Vector2& left, const Vector2& right) { return Vector2(left.x + right.x, left.y + right.y); } @@ -143,7 +135,7 @@ constexpr Vector2 operator +(const Vector2& left, const Vector2& right) //////////////////////////////////////////////////////////// template -constexpr Vector2 operator -(const Vector2& left, const Vector2& right) +constexpr Vector2 operator-(const Vector2& left, const Vector2& right) { return Vector2(left.x - right.x, left.y - right.y); } @@ -151,7 +143,7 @@ constexpr Vector2 operator -(const Vector2& left, const Vector2& right) //////////////////////////////////////////////////////////// template -constexpr Vector2 operator *(const Vector2& left, T right) +constexpr Vector2 operator*(const Vector2& left, T right) { return Vector2(left.x * right, left.y * right); } @@ -159,7 +151,7 @@ constexpr Vector2 operator *(const Vector2& left, T right) //////////////////////////////////////////////////////////// template -constexpr Vector2 operator *(T left, const Vector2& right) +constexpr Vector2 operator*(T left, const Vector2& right) { return Vector2(right.x * left, right.y * left); } @@ -167,7 +159,7 @@ constexpr Vector2 operator *(T left, const Vector2& right) //////////////////////////////////////////////////////////// template -constexpr Vector2& operator *=(Vector2& left, T right) +constexpr Vector2& operator*=(Vector2& left, T right) { left.x *= right; left.y *= right; @@ -178,7 +170,7 @@ constexpr Vector2& operator *=(Vector2& left, T right) //////////////////////////////////////////////////////////// template -constexpr Vector2 operator /(const Vector2& left, T right) +constexpr Vector2 operator/(const Vector2& left, T right) { return Vector2(left.x / right, left.y / right); } @@ -186,7 +178,7 @@ constexpr Vector2 operator /(const Vector2& left, T right) //////////////////////////////////////////////////////////// template -constexpr Vector2& operator /=(Vector2& left, T right) +constexpr Vector2& operator/=(Vector2& left, T right) { left.x /= right; left.y /= right; @@ -197,7 +189,7 @@ constexpr Vector2& operator /=(Vector2& left, T right) //////////////////////////////////////////////////////////// template -constexpr bool operator ==(const Vector2& left, const Vector2& right) +constexpr bool operator==(const Vector2& left, const Vector2& right) { return (left.x == right.x) && (left.y == right.y); } @@ -205,7 +197,7 @@ constexpr bool operator ==(const Vector2& left, const Vector2& right) //////////////////////////////////////////////////////////// template -constexpr bool operator !=(const Vector2& left, const Vector2& right) +constexpr bool operator!=(const Vector2& left, const Vector2& right) { return (left.x != right.x) || (left.y != right.y); } diff --git a/include/SFML/System/Vector3.hpp b/include/SFML/System/Vector3.hpp index a6ff96bf6..a296c7027 100644 --- a/include/SFML/System/Vector3.hpp +++ b/include/SFML/System/Vector3.hpp @@ -26,6 +26,7 @@ #define SFML_VECTOR3_HPP #include + #include namespace sf @@ -39,7 +40,6 @@ template class Vector3 { public: - //////////////////////////////////////////////////////////// /// \brief Default constructor /// @@ -149,7 +149,7 @@ public: /// //////////////////////////////////////////////////////////// template -[[nodiscard]] constexpr Vector3 operator -(const Vector3& left); +[[nodiscard]] constexpr Vector3 operator-(const Vector3& left); //////////////////////////////////////////////////////////// /// \relates Vector3 @@ -165,7 +165,7 @@ template /// //////////////////////////////////////////////////////////// template -constexpr Vector3& operator +=(Vector3& left, const Vector3& right); +constexpr Vector3& operator+=(Vector3& left, const Vector3& right); //////////////////////////////////////////////////////////// /// \relates Vector3 @@ -181,7 +181,7 @@ constexpr Vector3& operator +=(Vector3& left, const Vector3& right); /// //////////////////////////////////////////////////////////// template -constexpr Vector3& operator -=(Vector3& left, const Vector3& right); +constexpr Vector3& operator-=(Vector3& left, const Vector3& right); //////////////////////////////////////////////////////////// /// \relates Vector3 @@ -194,7 +194,7 @@ constexpr Vector3& operator -=(Vector3& left, const Vector3& right); /// //////////////////////////////////////////////////////////// template -[[nodiscard]] constexpr Vector3 operator +(const Vector3& left, const Vector3& right); +[[nodiscard]] constexpr Vector3 operator+(const Vector3& left, const Vector3& right); //////////////////////////////////////////////////////////// /// \relates Vector3 @@ -207,7 +207,7 @@ template /// //////////////////////////////////////////////////////////// template -[[nodiscard]] constexpr Vector3 operator -(const Vector3& left, const Vector3& right); +[[nodiscard]] constexpr Vector3 operator-(const Vector3& left, const Vector3& right); //////////////////////////////////////////////////////////// /// \relates Vector3 @@ -220,7 +220,7 @@ template /// //////////////////////////////////////////////////////////// template -[[nodiscard]] constexpr Vector3 operator *(const Vector3& left, T right); +[[nodiscard]] constexpr Vector3 operator*(const Vector3& left, T right); //////////////////////////////////////////////////////////// /// \relates Vector3 @@ -233,7 +233,7 @@ template /// //////////////////////////////////////////////////////////// template -[[nodiscard]] constexpr Vector3 operator *(T left, const Vector3& right); +[[nodiscard]] constexpr Vector3 operator*(T left, const Vector3& right); //////////////////////////////////////////////////////////// /// \relates Vector3 @@ -249,7 +249,7 @@ template /// //////////////////////////////////////////////////////////// template -constexpr Vector3& operator *=(Vector3& left, T right); +constexpr Vector3& operator*=(Vector3& left, T right); //////////////////////////////////////////////////////////// /// \relates Vector3 @@ -262,7 +262,7 @@ constexpr Vector3& operator *=(Vector3& left, T right); /// //////////////////////////////////////////////////////////// template -[[nodiscard]] constexpr Vector3 operator /(const Vector3& left, T right); +[[nodiscard]] constexpr Vector3 operator/(const Vector3& left, T right); //////////////////////////////////////////////////////////// /// \relates Vector3 @@ -278,7 +278,7 @@ template /// //////////////////////////////////////////////////////////// template -constexpr Vector3& operator /=(Vector3& left, T right); +constexpr Vector3& operator/=(Vector3& left, T right); //////////////////////////////////////////////////////////// /// \relates Vector3 @@ -293,7 +293,7 @@ constexpr Vector3& operator /=(Vector3& left, T right); /// //////////////////////////////////////////////////////////// template -[[nodiscard]] constexpr bool operator ==(const Vector3& left, const Vector3& right); +[[nodiscard]] constexpr bool operator==(const Vector3& left, const Vector3& right); //////////////////////////////////////////////////////////// /// \relates Vector3 @@ -308,7 +308,7 @@ template /// //////////////////////////////////////////////////////////// template -[[nodiscard]] constexpr bool operator !=(const Vector3& left, const Vector3& right); +[[nodiscard]] constexpr bool operator!=(const Vector3& left, const Vector3& right); #include diff --git a/include/SFML/System/Vector3.inl b/include/SFML/System/Vector3.inl index 077a4c434..c406a6964 100644 --- a/include/SFML/System/Vector3.inl +++ b/include/SFML/System/Vector3.inl @@ -25,23 +25,15 @@ //////////////////////////////////////////////////////////// template -constexpr Vector3::Vector3() : -x(0), -y(0), -z(0) +constexpr Vector3::Vector3() : x(0), y(0), z(0) { - } //////////////////////////////////////////////////////////// template -constexpr Vector3::Vector3(T X, T Y, T Z) : -x(X), -y(Y), -z(Z) +constexpr Vector3::Vector3(T X, T Y, T Z) : x(X), y(Y), z(Z) { - } @@ -56,7 +48,6 @@ z(static_cast(vector.z)) } - //////////////////////////////////////////////////////////// template constexpr T Vector3::lengthSq() const @@ -77,11 +68,7 @@ constexpr T Vector3::dot(const Vector3& rhs) const template constexpr Vector3 Vector3::cross(const Vector3& rhs) const { - return Vector3( - (y * rhs.z) - (z * rhs.y), - (z * rhs.x) - (x * rhs.z), - (x * rhs.y) - (y * rhs.x) - ); + return Vector3((y * rhs.z) - (z * rhs.y), (z * rhs.x) - (x * rhs.z), (x * rhs.y) - (y * rhs.x)); } @@ -106,7 +93,7 @@ constexpr Vector3 Vector3::cwiseDiv(const Vector3& rhs) const //////////////////////////////////////////////////////////// template -constexpr Vector3 operator -(const Vector3& left) +constexpr Vector3 operator-(const Vector3& left) { return Vector3(-left.x, -left.y, -left.z); } @@ -114,7 +101,7 @@ constexpr Vector3 operator -(const Vector3& left) //////////////////////////////////////////////////////////// template -constexpr Vector3& operator +=(Vector3& left, const Vector3& right) +constexpr Vector3& operator+=(Vector3& left, const Vector3& right) { left.x += right.x; left.y += right.y; @@ -126,7 +113,7 @@ constexpr Vector3& operator +=(Vector3& left, const Vector3& right) //////////////////////////////////////////////////////////// template -constexpr Vector3& operator -=(Vector3& left, const Vector3& right) +constexpr Vector3& operator-=(Vector3& left, const Vector3& right) { left.x -= right.x; left.y -= right.y; @@ -138,7 +125,7 @@ constexpr Vector3& operator -=(Vector3& left, const Vector3& right) //////////////////////////////////////////////////////////// template -constexpr Vector3 operator +(const Vector3& left, const Vector3& right) +constexpr Vector3 operator+(const Vector3& left, const Vector3& right) { return Vector3(left.x + right.x, left.y + right.y, left.z + right.z); } @@ -146,7 +133,7 @@ constexpr Vector3 operator +(const Vector3& left, const Vector3& right) //////////////////////////////////////////////////////////// template -constexpr Vector3 operator -(const Vector3& left, const Vector3& right) +constexpr Vector3 operator-(const Vector3& left, const Vector3& right) { return Vector3(left.x - right.x, left.y - right.y, left.z - right.z); } @@ -154,7 +141,7 @@ constexpr Vector3 operator -(const Vector3& left, const Vector3& right) //////////////////////////////////////////////////////////// template -constexpr Vector3 operator *(const Vector3& left, T right) +constexpr Vector3 operator*(const Vector3& left, T right) { return Vector3(left.x * right, left.y * right, left.z * right); } @@ -162,7 +149,7 @@ constexpr Vector3 operator *(const Vector3& left, T right) //////////////////////////////////////////////////////////// template -constexpr Vector3 operator *(T left, const Vector3& right) +constexpr Vector3 operator*(T left, const Vector3& right) { return Vector3(right.x * left, right.y * left, right.z * left); } @@ -170,7 +157,7 @@ constexpr Vector3 operator *(T left, const Vector3& right) //////////////////////////////////////////////////////////// template -constexpr Vector3& operator *=(Vector3& left, T right) +constexpr Vector3& operator*=(Vector3& left, T right) { left.x *= right; left.y *= right; @@ -182,7 +169,7 @@ constexpr Vector3& operator *=(Vector3& left, T right) //////////////////////////////////////////////////////////// template -constexpr Vector3 operator /(const Vector3& left, T right) +constexpr Vector3 operator/(const Vector3& left, T right) { return Vector3(left.x / right, left.y / right, left.z / right); } @@ -190,7 +177,7 @@ constexpr Vector3 operator /(const Vector3& left, T right) //////////////////////////////////////////////////////////// template -constexpr Vector3& operator /=(Vector3& left, T right) +constexpr Vector3& operator/=(Vector3& left, T right) { left.x /= right; left.y /= right; @@ -202,7 +189,7 @@ constexpr Vector3& operator /=(Vector3& left, T right) //////////////////////////////////////////////////////////// template -constexpr bool operator ==(const Vector3& left, const Vector3& right) +constexpr bool operator==(const Vector3& left, const Vector3& right) { return (left.x == right.x) && (left.y == right.y) && (left.z == right.z); } @@ -210,7 +197,7 @@ constexpr bool operator ==(const Vector3& left, const Vector3& right) //////////////////////////////////////////////////////////// template -constexpr bool operator !=(const Vector3& left, const Vector3& right) +constexpr bool operator!=(const Vector3& left, const Vector3& right) { return (left.x != right.x) || (left.y != right.y) || (left.z != right.z); } diff --git a/include/SFML/Window.hpp b/include/SFML/Window.hpp index 072f71516..cfdcf894e 100644 --- a/include/SFML/Window.hpp +++ b/include/SFML/Window.hpp @@ -46,7 +46,6 @@ #include - #endif // SFML_SFML_WINDOW_HPP //////////////////////////////////////////////////////////// diff --git a/include/SFML/Window/Clipboard.hpp b/include/SFML/Window/Clipboard.hpp index d3d5d803d..59253e829 100644 --- a/include/SFML/Window/Clipboard.hpp +++ b/include/SFML/Window/Clipboard.hpp @@ -42,7 +42,6 @@ class String; class SFML_WINDOW_API Clipboard { public: - //////////////////////////////////////////////////////////// /// \brief Get the content of the clipboard as string data /// diff --git a/include/SFML/Window/Context.hpp b/include/SFML/Window/Context.hpp index bdc0f9318..001ae1121 100644 --- a/include/SFML/Window/Context.hpp +++ b/include/SFML/Window/Context.hpp @@ -29,8 +29,10 @@ // Headers //////////////////////////////////////////////////////////// #include -#include + #include +#include + #include @@ -38,7 +40,7 @@ namespace sf { namespace priv { - class GlContext; +class GlContext; } struct ContextSettings; @@ -52,7 +54,6 @@ using GlFunctionPointer = void (*)(); class SFML_WINDOW_API Context : GlResource { public: - //////////////////////////////////////////////////////////// /// \brief Default constructor /// @@ -160,7 +161,6 @@ public: Context(const ContextSettings& settings, const Vector2u& size); private: - //////////////////////////////////////////////////////////// // Member data //////////////////////////////////////////////////////////// diff --git a/include/SFML/Window/ContextSettings.hpp b/include/SFML/Window/ContextSettings.hpp index f3b6b5d35..8d6c20a50 100644 --- a/include/SFML/Window/ContextSettings.hpp +++ b/include/SFML/Window/ContextSettings.hpp @@ -59,14 +59,21 @@ struct ContextSettings /// \param sRgb sRGB capable framebuffer /// //////////////////////////////////////////////////////////// - constexpr explicit ContextSettings(unsigned int depth = 0, unsigned int stencil = 0, unsigned int antialiasing = 0, unsigned int major = 1, unsigned int minor = 1, unsigned int attributes = Default, bool sRgb = false) : - depthBits (depth), - stencilBits (stencil), + constexpr explicit ContextSettings( + unsigned int depth = 0, + unsigned int stencil = 0, + unsigned int antialiasing = 0, + unsigned int major = 1, + unsigned int minor = 1, + unsigned int attributes = Default, + bool sRgb = false) : + depthBits(depth), + stencilBits(stencil), antialiasingLevel(antialiasing), - majorVersion (major), - minorVersion (minor), - attributeFlags (attributes), - sRgbCapable (sRgb) + majorVersion(major), + minorVersion(minor), + attributeFlags(attributes), + sRgbCapable(sRgb) { } diff --git a/include/SFML/Window/Cursor.hpp b/include/SFML/Window/Cursor.hpp index 56af3f027..a74013d78 100644 --- a/include/SFML/Window/Cursor.hpp +++ b/include/SFML/Window/Cursor.hpp @@ -29,14 +29,16 @@ // Headers //////////////////////////////////////////////////////////// #include + #include + #include namespace sf { namespace priv { - class CursorImpl; +class CursorImpl; } //////////////////////////////////////////////////////////// @@ -46,7 +48,6 @@ namespace priv class SFML_WINDOW_API Cursor { public: - //////////////////////////////////////////////////////////// /// \brief Enumeration of the native system cursor types /// @@ -99,17 +100,16 @@ public: SizeTop, //!< Up arrow cursor on Linux, same as SizeVertical on other platforms SizeBottom, //!< Down arrow cursor on Linux, same as SizeVertical on other platforms SizeTopLeft, //!< Top-left arrow cursor on Linux, same as SizeTopLeftBottomRight on other platforms - SizeBottomRight, //!< Bottom-right arrow cursor on Linux, same as SizeTopLeftBottomRight on other platforms - SizeBottomLeft, //!< Bottom-left arrow cursor on Linux, same as SizeBottomLeftTopRight on other platforms - SizeTopRight, //!< Top-right arrow cursor on Linux, same as SizeBottomLeftTopRight on other platforms - SizeAll, //!< Combination of SizeHorizontal and SizeVertical - Cross, //!< Crosshair cursor - Help, //!< Help cursor - NotAllowed //!< Action not allowed cursor + SizeBottomRight, //!< Bottom-right arrow cursor on Linux, same as SizeTopLeftBottomRight on other platforms + SizeBottomLeft, //!< Bottom-left arrow cursor on Linux, same as SizeBottomLeftTopRight on other platforms + SizeTopRight, //!< Top-right arrow cursor on Linux, same as SizeBottomLeftTopRight on other platforms + SizeAll, //!< Combination of SizeHorizontal and SizeVertical + Cross, //!< Crosshair cursor + Help, //!< Help cursor + NotAllowed //!< Action not allowed cursor }; public: - //////////////////////////////////////////////////////////// /// \brief Default constructor /// @@ -191,7 +191,6 @@ public: [[nodiscard]] bool loadFromSystem(Type type); private: - friend class WindowBase; //////////////////////////////////////////////////////////// @@ -206,7 +205,6 @@ private: const priv::CursorImpl& getImpl() const; private: - //////////////////////////////////////////////////////////// // Member data //////////////////////////////////////////////////////////// diff --git a/include/SFML/Window/Event.hpp b/include/SFML/Window/Event.hpp index 913cc9e47..6decd2074 100644 --- a/include/SFML/Window/Event.hpp +++ b/include/SFML/Window/Event.hpp @@ -29,6 +29,7 @@ // Headers //////////////////////////////////////////////////////////// #include + #include #include #include @@ -44,7 +45,6 @@ namespace sf class Event { public: - //////////////////////////////////////////////////////////// /// \brief Size events parameters (Resized) /// @@ -107,8 +107,8 @@ public: { Mouse::Wheel wheel; //!< Which wheel (for mice with multiple ones) float delta; //!< Wheel offset (positive is up/left, negative is down/right). High-precision mice may use non-integral offsets. - int x; //!< X position of the mouse pointer, relative to the left of the owner window - int y; //!< Y position of the mouse pointer, relative to the top of the owner window + int x; //!< X position of the mouse pointer, relative to the left of the owner window + int y; //!< Y position of the mouse pointer, relative to the top of the owner window }; //////////////////////////////////////////////////////////// @@ -140,7 +140,7 @@ public: struct JoystickButtonEvent { unsigned int joystickId; //!< Index of the joystick (in range [0 .. Joystick::Count - 1]) - unsigned int button; //!< Index of the button that has been pressed (in range [0 .. Joystick::ButtonCount - 1]) + unsigned int button; //!< Index of the button that has been pressed (in range [0 .. Joystick::ButtonCount - 1]) }; //////////////////////////////////////////////////////////// @@ -150,8 +150,8 @@ public: struct TouchEvent { unsigned int finger; //!< Index of the finger in case of multi-touch events - int x; //!< X position of the touch, relative to the left of the owner window - int y; //!< Y position of the touch, relative to the top of the owner window + int x; //!< X position of the touch, relative to the left of the owner window + int y; //!< Y position of the touch, relative to the top of the owner window }; //////////////////////////////////////////////////////////// @@ -161,9 +161,9 @@ public: struct SensorEvent { Sensor::Type type; //!< Type of the sensor - float x; //!< Current value of the sensor on X axis - float y; //!< Current value of the sensor on Y axis - float z; //!< Current value of the sensor on Z axis + float x; //!< Current value of the sensor on X axis + float y; //!< Current value of the sensor on Y axis + float z; //!< Current value of the sensor on Z axis }; //////////////////////////////////////////////////////////// @@ -195,7 +195,7 @@ public: TouchEnded, //!< A touch event ended (data in event.touch) SensorChanged, //!< A sensor value changed (data in event.sensor) - Count //!< Keep last -- the total number of event types + Count //!< Keep last -- the total number of event types }; //////////////////////////////////////////////////////////// @@ -205,17 +205,17 @@ public: union { - SizeEvent size; //!< Size event parameters (Event::Resized) - KeyEvent key; //!< Key event parameters (Event::KeyPressed, Event::KeyReleased) - TextEvent text; //!< Text event parameters (Event::TextEntered) - MouseMoveEvent mouseMove; //!< Mouse move event parameters (Event::MouseMoved) - MouseButtonEvent mouseButton; //!< Mouse button event parameters (Event::MouseButtonPressed, Event::MouseButtonReleased) - MouseWheelScrollEvent mouseWheelScroll; //!< Mouse wheel event parameters (Event::MouseWheelScrolled) - JoystickMoveEvent joystickMove; //!< Joystick move event parameters (Event::JoystickMoved) - JoystickButtonEvent joystickButton; //!< Joystick button event parameters (Event::JoystickButtonPressed, Event::JoystickButtonReleased) - JoystickConnectEvent joystickConnect; //!< Joystick (dis)connect event parameters (Event::JoystickConnected, Event::JoystickDisconnected) - TouchEvent touch; //!< Touch events parameters (Event::TouchBegan, Event::TouchMoved, Event::TouchEnded) - SensorEvent sensor; //!< Sensor event parameters (Event::SensorChanged) + SizeEvent size; //!< Size event parameters (Event::Resized) + KeyEvent key; //!< Key event parameters (Event::KeyPressed, Event::KeyReleased) + TextEvent text; //!< Text event parameters (Event::TextEntered) + MouseMoveEvent mouseMove; //!< Mouse move event parameters (Event::MouseMoved) + MouseButtonEvent mouseButton; //!< Mouse button event parameters (Event::MouseButtonPressed, Event::MouseButtonReleased) + MouseWheelScrollEvent mouseWheelScroll; //!< Mouse wheel event parameters (Event::MouseWheelScrolled) + JoystickMoveEvent joystickMove; //!< Joystick move event parameters (Event::JoystickMoved) + JoystickButtonEvent joystickButton; //!< Joystick button event parameters (Event::JoystickButtonPressed, Event::JoystickButtonReleased) + JoystickConnectEvent joystickConnect; //!< Joystick (dis)connect event parameters (Event::JoystickConnected, Event::JoystickDisconnected) + TouchEvent touch; //!< Touch events parameters (Event::TouchBegan, Event::TouchMoved, Event::TouchEnded) + SensorEvent sensor; //!< Sensor event parameters (Event::SensorChanged) }; }; diff --git a/include/SFML/Window/Export.hpp b/include/SFML/Window/Export.hpp index acef93fc8..325f7b49e 100644 --- a/include/SFML/Window/Export.hpp +++ b/include/SFML/Window/Export.hpp @@ -36,11 +36,11 @@ //////////////////////////////////////////////////////////// #if defined(SFML_WINDOW_EXPORTS) - #define SFML_WINDOW_API SFML_API_EXPORT +#define SFML_WINDOW_API SFML_API_EXPORT #else - #define SFML_WINDOW_API SFML_API_IMPORT +#define SFML_WINDOW_API SFML_API_IMPORT #endif diff --git a/include/SFML/Window/GlResource.hpp b/include/SFML/Window/GlResource.hpp index 6a6e41084..e432099f2 100644 --- a/include/SFML/Window/GlResource.hpp +++ b/include/SFML/Window/GlResource.hpp @@ -36,7 +36,7 @@ namespace sf class Context; -using ContextDestroyCallback = void (*)(void *); +using ContextDestroyCallback = void (*)(void*); //////////////////////////////////////////////////////////// /// \brief Base class for classes that require an OpenGL context @@ -45,7 +45,6 @@ using ContextDestroyCallback = void (*)(void *); class SFML_WINDOW_API GlResource { protected: - //////////////////////////////////////////////////////////// /// \brief Default constructor /// diff --git a/include/SFML/Window/Joystick.hpp b/include/SFML/Window/Joystick.hpp index 8f3628bc1..debd1334d 100644 --- a/include/SFML/Window/Joystick.hpp +++ b/include/SFML/Window/Joystick.hpp @@ -29,6 +29,7 @@ // Headers //////////////////////////////////////////////////////////// #include + #include @@ -41,7 +42,6 @@ namespace sf class SFML_WINDOW_API Joystick { public: - //////////////////////////////////////////////////////////// /// \brief Constants related to joysticks capabilities /// diff --git a/include/SFML/Window/Keyboard.hpp b/include/SFML/Window/Keyboard.hpp index 1b1681030..d2b8759f7 100644 --- a/include/SFML/Window/Keyboard.hpp +++ b/include/SFML/Window/Keyboard.hpp @@ -40,7 +40,6 @@ namespace sf class SFML_WINDOW_API Keyboard { public: - //////////////////////////////////////////////////////////// /// \brief Key codes /// @@ -48,7 +47,7 @@ public: enum Key { Unknown = -1, //!< Unhandled key - A = 0, //!< The A key + A = 0, //!< The A key B, //!< The B key C, //!< The C key D, //!< The D key @@ -150,7 +149,7 @@ public: F15, //!< The F15 key Pause, //!< The Pause key - KeyCount //!< Keep last -- the total number of keyboard keys + KeyCount //!< Keep last -- the total number of keyboard keys }; //////////////////////////////////////////////////////////// diff --git a/include/SFML/Window/Mouse.hpp b/include/SFML/Window/Mouse.hpp index 10cfa5ff7..2e6fa2a0a 100644 --- a/include/SFML/Window/Mouse.hpp +++ b/include/SFML/Window/Mouse.hpp @@ -29,6 +29,7 @@ // Headers //////////////////////////////////////////////////////////// #include + #include @@ -43,18 +44,17 @@ class WindowBase; class SFML_WINDOW_API Mouse { public: - //////////////////////////////////////////////////////////// /// \brief Mouse buttons /// //////////////////////////////////////////////////////////// enum Button { - Left, //!< The left mouse button - Right, //!< The right mouse button - Middle, //!< The middle (wheel) mouse button - XButton1, //!< The first extra mouse button - XButton2, //!< The second extra mouse button + Left, //!< The left mouse button + Right, //!< The right mouse button + Middle, //!< The middle (wheel) mouse button + XButton1, //!< The first extra mouse button + XButton2, //!< The second extra mouse button ButtonCount //!< Keep last -- the total number of mouse buttons }; diff --git a/include/SFML/Window/Sensor.hpp b/include/SFML/Window/Sensor.hpp index 5fd7d8acb..0158890b9 100644 --- a/include/SFML/Window/Sensor.hpp +++ b/include/SFML/Window/Sensor.hpp @@ -29,6 +29,7 @@ // Headers //////////////////////////////////////////////////////////// #include + #include @@ -41,21 +42,20 @@ namespace sf class SFML_WINDOW_API Sensor { public: - //////////////////////////////////////////////////////////// /// \brief Sensor type /// //////////////////////////////////////////////////////////// enum Type { - Accelerometer, //!< Measures the raw acceleration (m/s^2) - Gyroscope, //!< Measures the raw rotation rates (degrees/s) - Magnetometer, //!< Measures the ambient magnetic field (micro-teslas) - Gravity, //!< Measures the direction and intensity of gravity, independent of device acceleration (m/s^2) + Accelerometer, //!< Measures the raw acceleration (m/s^2) + Gyroscope, //!< Measures the raw rotation rates (degrees/s) + Magnetometer, //!< Measures the ambient magnetic field (micro-teslas) + Gravity, //!< Measures the direction and intensity of gravity, independent of device acceleration (m/s^2) UserAcceleration, //!< Measures the direction and intensity of device acceleration, independent of the gravity (m/s^2) - Orientation, //!< Measures the absolute 3D orientation (degrees) + Orientation, //!< Measures the absolute 3D orientation (degrees) - Count //!< Keep last -- the total number of sensor types + Count //!< Keep last -- the total number of sensor types }; //////////////////////////////////////////////////////////// diff --git a/include/SFML/Window/Touch.hpp b/include/SFML/Window/Touch.hpp index 4ce69c668..60aa002c6 100644 --- a/include/SFML/Window/Touch.hpp +++ b/include/SFML/Window/Touch.hpp @@ -29,6 +29,7 @@ // Headers //////////////////////////////////////////////////////////// #include + #include @@ -43,7 +44,6 @@ class WindowBase; class SFML_WINDOW_API Touch { public: - //////////////////////////////////////////////////////////// /// \brief Check if a touch event is currently down /// diff --git a/include/SFML/Window/VideoMode.hpp b/include/SFML/Window/VideoMode.hpp index a4127fa4f..1b7ae307e 100644 --- a/include/SFML/Window/VideoMode.hpp +++ b/include/SFML/Window/VideoMode.hpp @@ -29,7 +29,9 @@ // Headers //////////////////////////////////////////////////////////// #include + #include + #include @@ -42,7 +44,6 @@ namespace sf class SFML_WINDOW_API VideoMode { public: - //////////////////////////////////////////////////////////// /// \brief Default constructor /// @@ -99,7 +100,7 @@ public: //////////////////////////////////////////////////////////// // Member data //////////////////////////////////////////////////////////// - Vector2u size; //!< Video mode width and height, in pixels + Vector2u size; //!< Video mode width and height, in pixels unsigned int bitsPerPixel; //!< Video mode pixel depth, in bits per pixels }; @@ -113,7 +114,7 @@ public: /// \return True if modes are equal /// //////////////////////////////////////////////////////////// -SFML_WINDOW_API bool operator ==(const VideoMode& left, const VideoMode& right); +SFML_WINDOW_API bool operator==(const VideoMode& left, const VideoMode& right); //////////////////////////////////////////////////////////// /// \relates VideoMode @@ -125,7 +126,7 @@ SFML_WINDOW_API bool operator ==(const VideoMode& left, const VideoMode& right); /// \return True if modes are different /// //////////////////////////////////////////////////////////// -SFML_WINDOW_API bool operator !=(const VideoMode& left, const VideoMode& right); +SFML_WINDOW_API bool operator!=(const VideoMode& left, const VideoMode& right); //////////////////////////////////////////////////////////// /// \relates VideoMode @@ -137,7 +138,7 @@ SFML_WINDOW_API bool operator !=(const VideoMode& left, const VideoMode& right); /// \return True if \a left is lesser than \a right /// //////////////////////////////////////////////////////////// -SFML_WINDOW_API bool operator <(const VideoMode& left, const VideoMode& right); +SFML_WINDOW_API bool operator<(const VideoMode& left, const VideoMode& right); //////////////////////////////////////////////////////////// /// \relates VideoMode @@ -149,7 +150,7 @@ SFML_WINDOW_API bool operator <(const VideoMode& left, const VideoMode& right); /// \return True if \a left is greater than \a right /// //////////////////////////////////////////////////////////// -SFML_WINDOW_API bool operator >(const VideoMode& left, const VideoMode& right); +SFML_WINDOW_API bool operator>(const VideoMode& left, const VideoMode& right); //////////////////////////////////////////////////////////// /// \relates VideoMode @@ -161,7 +162,7 @@ SFML_WINDOW_API bool operator >(const VideoMode& left, const VideoMode& right); /// \return True if \a left is lesser or equal than \a right /// //////////////////////////////////////////////////////////// -SFML_WINDOW_API bool operator <=(const VideoMode& left, const VideoMode& right); +SFML_WINDOW_API bool operator<=(const VideoMode& left, const VideoMode& right); //////////////////////////////////////////////////////////// /// \relates VideoMode @@ -173,7 +174,7 @@ SFML_WINDOW_API bool operator <=(const VideoMode& left, const VideoMode& right); /// \return True if \a left is greater or equal than \a right /// //////////////////////////////////////////////////////////// -SFML_WINDOW_API bool operator >=(const VideoMode& left, const VideoMode& right); +SFML_WINDOW_API bool operator>=(const VideoMode& left, const VideoMode& right); } // namespace sf diff --git a/include/SFML/Window/Vulkan.hpp b/include/SFML/Window/Vulkan.hpp index a4fd20535..5100c08e2 100644 --- a/include/SFML/Window/Vulkan.hpp +++ b/include/SFML/Window/Vulkan.hpp @@ -29,13 +29,15 @@ // Headers //////////////////////////////////////////////////////////// #include -#include + #include +#include using VkInstance = struct VkInstance_T*; -#if defined(__LP64__) || defined(_WIN64) || (defined(__x86_64__) && !defined(__ILP32__) ) || defined(_M_X64) || defined(__ia64) || defined (_M_IA64) || defined(__aarch64__) || defined(__powerpc64__) +#if defined(__LP64__) || defined(_WIN64) || (defined(__x86_64__) && !defined(__ILP32__)) || defined(_M_X64) || \ + defined(__ia64) || defined(_M_IA64) || defined(__aarch64__) || defined(__powerpc64__) using VkSurfaceKHR = struct VkSurfaceKHR_T*; @@ -60,7 +62,6 @@ using VulkanFunctionPointer = void (*)(); class SFML_WINDOW_API Vulkan { public: - //////////////////////////////////////////////////////////// /// \brief Tell whether or not the system supports Vulkan /// diff --git a/include/SFML/Window/Window.hpp b/include/SFML/Window/Window.hpp index 7536fcb6b..4af56acfc 100644 --- a/include/SFML/Window/Window.hpp +++ b/include/SFML/Window/Window.hpp @@ -28,11 +28,12 @@ //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// +#include +#include #include #include #include -#include -#include + #include @@ -40,7 +41,7 @@ namespace sf { namespace priv { - class GlContext; +class GlContext; } class Event; @@ -52,7 +53,6 @@ class Event; class SFML_WINDOW_API Window : public WindowBase, GlResource { public: - //////////////////////////////////////////////////////////// /// \brief Default constructor /// @@ -81,7 +81,10 @@ public: /// \param settings Additional settings for the underlying OpenGL context /// //////////////////////////////////////////////////////////// - Window(VideoMode mode, const String& title, Uint32 style = Style::Default, const ContextSettings& settings = ContextSettings()); + Window(VideoMode mode, + const String& title, + Uint32 style = Style::Default, + const ContextSettings& settings = ContextSettings()); //////////////////////////////////////////////////////////// /// \brief Construct the window from an existing control @@ -255,7 +258,6 @@ public: void display(); private: - //////////////////////////////////////////////////////////// /// \brief Processes an event before it is sent to the user /// diff --git a/include/SFML/Window/WindowBase.hpp b/include/SFML/Window/WindowBase.hpp index 17da8108c..545166c2e 100644 --- a/include/SFML/Window/WindowBase.hpp +++ b/include/SFML/Window/WindowBase.hpp @@ -29,10 +29,12 @@ // Headers //////////////////////////////////////////////////////////// #include + +#include #include #include #include -#include + #include @@ -44,7 +46,7 @@ class VideoMode; namespace priv { - class WindowImpl; +class WindowImpl; } class Event; @@ -56,7 +58,6 @@ class Event; class SFML_WINDOW_API WindowBase { public: - //////////////////////////////////////////////////////////// /// \brief Default constructor /// @@ -414,10 +415,11 @@ public: /// \return True if surface creation was successful, false otherwise /// //////////////////////////////////////////////////////////// - [[nodiscard]] bool createVulkanSurface(const VkInstance& instance, VkSurfaceKHR& surface, const VkAllocationCallbacks* allocator = nullptr); + [[nodiscard]] bool createVulkanSurface(const VkInstance& instance, + VkSurfaceKHR& surface, + const VkAllocationCallbacks* allocator = nullptr); protected: - //////////////////////////////////////////////////////////// /// \brief Function called after the window has been created /// @@ -438,7 +440,6 @@ protected: virtual void onResize(); private: - friend class Window; //////////////////////////////////////////////////////////// diff --git a/include/SFML/Window/WindowHandle.hpp b/include/SFML/Window/WindowHandle.hpp index a3e25dfd1..78ba1d4c5 100644 --- a/include/SFML/Window/WindowHandle.hpp +++ b/include/SFML/Window/WindowHandle.hpp @@ -32,40 +32,41 @@ // Windows' HWND is a type alias for struct HWND__* #if defined(SFML_SYSTEM_WINDOWS) - struct HWND__; +struct HWND__; #endif namespace sf { #if defined(SFML_SYSTEM_WINDOWS) - // Window handle is HWND (HWND__*) on Windows - using WindowHandle = HWND__ *; +// Window handle is HWND (HWND__*) on Windows +using WindowHandle = HWND__*; -#elif defined(SFML_SYSTEM_LINUX) || defined(SFML_SYSTEM_FREEBSD) || defined(SFML_SYSTEM_OPENBSD) || defined(SFML_SYSTEM_NETBSD) +#elif defined(SFML_SYSTEM_LINUX) || defined(SFML_SYSTEM_FREEBSD) || defined(SFML_SYSTEM_OPENBSD) || \ + defined(SFML_SYSTEM_NETBSD) - // Window handle is Window (unsigned long) on Unix - X11 - using WindowHandle = unsigned long; +// Window handle is Window (unsigned long) on Unix - X11 +using WindowHandle = unsigned long; #elif defined(SFML_SYSTEM_MACOS) - // Window handle is NSWindow or NSView (void*) on Mac OS X - Cocoa - using WindowHandle = void*; +// Window handle is NSWindow or NSView (void*) on Mac OS X - Cocoa +using WindowHandle = void*; #elif defined(SFML_SYSTEM_IOS) - // Window handle is UIWindow (void*) on iOS - UIKit - using WindowHandle = void*; +// Window handle is UIWindow (void*) on iOS - UIKit +using WindowHandle = void*; #elif defined(SFML_SYSTEM_ANDROID) - // Window handle is ANativeWindow* (void*) on Android - using WindowHandle = void*; +// Window handle is ANativeWindow* (void*) on Android +using WindowHandle = void*; #elif defined(SFML_DOXYGEN) - // Define type alias symbol so that Doxygen can attach some documentation to it - using WindowHandle = "platform-specific"; +// Define type alias symbol so that Doxygen can attach some documentation to it +using WindowHandle = "platform-specific"; #endif diff --git a/include/SFML/Window/WindowStyle.hpp b/include/SFML/Window/WindowStyle.hpp index 703d2f39e..4cea4d21a 100644 --- a/include/SFML/Window/WindowStyle.hpp +++ b/include/SFML/Window/WindowStyle.hpp @@ -30,22 +30,22 @@ namespace sf { namespace Style { - //////////////////////////////////////////////////////////// - /// \ingroup window - /// \brief Enumeration of the window styles - /// - //////////////////////////////////////////////////////////// - enum - { - None = 0, //!< No border / title bar (this flag and all others are mutually exclusive) - Titlebar = 1 << 0, //!< Title bar + fixed border - Resize = 1 << 1, //!< Title bar + resizable border + maximize button - Close = 1 << 2, //!< Title bar + close button - Fullscreen = 1 << 3, //!< Fullscreen mode (this flag and all others are mutually exclusive) +//////////////////////////////////////////////////////////// +/// \ingroup window +/// \brief Enumeration of the window styles +/// +//////////////////////////////////////////////////////////// +enum +{ + None = 0, //!< No border / title bar (this flag and all others are mutually exclusive) + Titlebar = 1 << 0, //!< Title bar + fixed border + Resize = 1 << 1, //!< Title bar + resizable border + maximize button + Close = 1 << 2, //!< Title bar + close button + Fullscreen = 1 << 3, //!< Fullscreen mode (this flag and all others are mutually exclusive) - Default = Titlebar | Resize | Close //!< Default window style - }; -} + Default = Titlebar | Resize | Close //!< Default window style +}; +} // namespace Style } // namespace sf diff --git a/src/SFML/Audio/ALCheck.cpp b/src/SFML/Audio/ALCheck.cpp index 551f5ab62..e4cf716ef 100644 --- a/src/SFML/Audio/ALCheck.cpp +++ b/src/SFML/Audio/ALCheck.cpp @@ -27,26 +27,27 @@ //////////////////////////////////////////////////////////// #include #include -#include + #include +#include #include #if defined(__APPLE__) - #if defined(__clang__) - #pragma clang diagnostic ignored "-Wdeprecated-declarations" - #elif defined(__GNUC__) - #pragma GCC diagnostic ignored "-Wdeprecated-declarations" - #endif +#if defined(__clang__) +#pragma clang diagnostic ignored "-Wdeprecated-declarations" +#elif defined(__GNUC__) +#pragma GCC diagnostic ignored "-Wdeprecated-declarations" +#endif #endif namespace { - // A nested named namespace is used here to allow unity builds of SFML. - namespace AlCheckImpl - { - thread_local ALenum lastError(AL_NO_ERROR); - } +// A nested named namespace is used here to allow unity builds of SFML. +namespace AlCheckImpl +{ +thread_local ALenum lastError(AL_NO_ERROR); } +} // namespace namespace sf { @@ -62,7 +63,7 @@ void alCheckError(const std::filesystem::path& file, unsigned int line, const ch { AlCheckImpl::lastError = errorCode; - std::string error = "Unknown error"; + std::string error = "Unknown error"; std::string description = "No description"; // Decode the error code @@ -70,45 +71,43 @@ void alCheckError(const std::filesystem::path& file, unsigned int line, const ch { case AL_INVALID_NAME: { - error = "AL_INVALID_NAME"; + error = "AL_INVALID_NAME"; description = "A bad name (ID) has been specified."; break; } case AL_INVALID_ENUM: { - error = "AL_INVALID_ENUM"; + error = "AL_INVALID_ENUM"; description = "An unacceptable value has been specified for an enumerated argument."; break; } case AL_INVALID_VALUE: { - error = "AL_INVALID_VALUE"; + error = "AL_INVALID_VALUE"; description = "A numeric argument is out of range."; break; } case AL_INVALID_OPERATION: { - error = "AL_INVALID_OPERATION"; + error = "AL_INVALID_OPERATION"; description = "The specified operation is not allowed in the current state."; break; } case AL_OUT_OF_MEMORY: { - error = "AL_OUT_OF_MEMORY"; + error = "AL_OUT_OF_MEMORY"; description = "There is not enough memory left to execute the command."; break; } } // Log the error - err() << "An internal OpenAL call failed in " - << file.filename() << "(" << line << ")." - << "\nExpression:\n " << expression - << "\nError description:\n " << error << "\n " << description << '\n' + err() << "An internal OpenAL call failed in " << file.filename() << "(" << line << ")." + << "\nExpression:\n " << expression << "\nError description:\n " << error << "\n " << description << '\n' << std::endl; } } diff --git a/src/SFML/Audio/ALCheck.hpp b/src/SFML/Audio/ALCheck.hpp index 6cb8cf320..371216c1c 100644 --- a/src/SFML/Audio/ALCheck.hpp +++ b/src/SFML/Audio/ALCheck.hpp @@ -29,16 +29,17 @@ // Headers //////////////////////////////////////////////////////////// #include + #include #if defined(__APPLE__) - #if defined(__clang__) - #pragma clang diagnostic push - #pragma clang diagnostic ignored "-Wdeprecated-declarations" - #elif defined(__GNUC__) - #pragma GCC diagnostic push - #pragma GCC diagnostic ignored "-Wdeprecated-declarations" - #endif +#if defined(__clang__) +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" +#elif defined(__GNUC__) +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wdeprecated-declarations" +#endif #endif #include @@ -53,16 +54,21 @@ namespace priv //////////////////////////////////////////////////////////// #ifdef SFML_DEBUG - // If in debug mode, perform a test on every call - // The do-while loop is needed so that alCheck can be used as a single statement in if/else branches - #define alCheck(expr) do { expr; sf::priv::alCheckError(__FILE__, __LINE__, #expr); } while (false) - #define alGetLastError sf::priv::alGetLastErrorImpl +// If in debug mode, perform a test on every call +// The do-while loop is needed so that alCheck can be used as a single statement in if/else branches +#define alCheck(expr) \ + do \ + { \ + expr; \ + sf::priv::alCheckError(__FILE__, __LINE__, #expr); \ + } while (false) +#define alGetLastError sf::priv::alGetLastErrorImpl #else - // Else, we don't add any overhead - #define alCheck(expr) (expr) - #define alGetLastError alGetError +// Else, we don't add any overhead +#define alCheck(expr) (expr) +#define alGetLastError alGetError #endif @@ -94,9 +100,9 @@ ALenum alGetLastErrorImpl(); #endif // SFML_ALCHECK_HPP #if defined(__APPLE__) - #if defined(__clang__) - #pragma clang diagnostic pop - #elif defined(__GNUC__) - #pragma GCC diagnostic pop - #endif +#if defined(__clang__) +#pragma clang diagnostic pop +#elif defined(__GNUC__) +#pragma GCC diagnostic pop +#endif #endif diff --git a/src/SFML/Audio/AlResource.cpp b/src/SFML/Audio/AlResource.cpp index c031e4cf8..1cc6386b4 100644 --- a/src/SFML/Audio/AlResource.cpp +++ b/src/SFML/Audio/AlResource.cpp @@ -27,21 +27,22 @@ //////////////////////////////////////////////////////////// #include #include + #include #include namespace { - // OpenAL resources counter and its mutex - unsigned int count = 0; - std::recursive_mutex mutex; +// OpenAL resources counter and its mutex +unsigned int count = 0; +std::recursive_mutex mutex; - // The audio device is instantiated on demand rather than at global startup, - // which solves a lot of weird crashes and errors. - // It is destroyed when it is no longer needed. - std::unique_ptr globalDevice; -} +// The audio device is instantiated on demand rather than at global startup, +// which solves a lot of weird crashes and errors. +// It is destroyed when it is no longer needed. +std::unique_ptr globalDevice; +} // namespace namespace sf diff --git a/src/SFML/Audio/AudioDevice.cpp b/src/SFML/Audio/AudioDevice.cpp index edf78c9af..e7d64981b 100644 --- a/src/SFML/Audio/AudioDevice.cpp +++ b/src/SFML/Audio/AudioDevice.cpp @@ -25,31 +25,32 @@ //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// -#include #include +#include #include #include + #include #include #if defined(__APPLE__) - #if defined(__clang__) - #pragma clang diagnostic ignored "-Wdeprecated-declarations" - #elif defined(__GNUC__) - #pragma GCC diagnostic ignored "-Wdeprecated-declarations" - #endif +#if defined(__clang__) +#pragma clang diagnostic ignored "-Wdeprecated-declarations" +#elif defined(__GNUC__) +#pragma GCC diagnostic ignored "-Wdeprecated-declarations" +#endif #endif namespace { - ALCdevice* audioDevice = nullptr; - ALCcontext* audioContext = nullptr; +ALCdevice* audioDevice = nullptr; +ALCcontext* audioContext = nullptr; - float listenerVolume = 100.f; - sf::Vector3f listenerPosition (0.f, 0.f, 0.f); - sf::Vector3f listenerDirection(0.f, 0.f, -1.f); - sf::Vector3f listenerUpVector (0.f, 1.f, 0.f); -} +float listenerVolume = 100.f; +sf::Vector3f listenerPosition(0.f, 0.f, 0.f); +sf::Vector3f listenerDirection(0.f, 0.f, -1.f); +sf::Vector3f listenerUpVector(0.f, 1.f, 0.f); +} // namespace namespace sf { @@ -200,7 +201,8 @@ void AudioDevice::setDirection(const Vector3f& direction) { if (audioContext) { - float orientation[] = {direction.x, direction.y, direction.z, listenerUpVector.x, listenerUpVector.y, listenerUpVector.z}; + float orientation[] = + {direction.x, direction.y, direction.z, listenerUpVector.x, listenerUpVector.y, listenerUpVector.z}; alCheck(alListenerfv(AL_ORIENTATION, orientation)); } @@ -220,7 +222,8 @@ void AudioDevice::setUpVector(const Vector3f& upVector) { if (audioContext) { - float orientation[] = {listenerDirection.x, listenerDirection.y, listenerDirection.z, upVector.x, upVector.y, upVector.z}; + float orientation[] = + {listenerDirection.x, listenerDirection.y, listenerDirection.z, upVector.x, upVector.y, upVector.z}; alCheck(alListenerfv(AL_ORIENTATION, orientation)); } diff --git a/src/SFML/Audio/AudioDevice.hpp b/src/SFML/Audio/AudioDevice.hpp index 4ae9db2eb..3e25aabe5 100644 --- a/src/SFML/Audio/AudioDevice.hpp +++ b/src/SFML/Audio/AudioDevice.hpp @@ -29,6 +29,7 @@ // Headers //////////////////////////////////////////////////////////// #include + #include @@ -45,7 +46,6 @@ namespace priv class AudioDevice { public: - //////////////////////////////////////////////////////////// /// \brief Default constructor /// diff --git a/src/SFML/Audio/InputSoundFile.cpp b/src/SFML/Audio/InputSoundFile.cpp index 3cb5a19b0..ce4b4fa85 100644 --- a/src/SFML/Audio/InputSoundFile.cpp +++ b/src/SFML/Audio/InputSoundFile.cpp @@ -26,13 +26,14 @@ // Headers //////////////////////////////////////////////////////////// #include -#include #include -#include -#include -#include +#include #include +#include +#include +#include #include + #include #include @@ -42,16 +43,13 @@ namespace sf //////////////////////////////////////////////////////////// InputSoundFile::StreamDeleter::StreamDeleter(bool theOwned) : owned{theOwned} { - } //////////////////////////////////////////////////////////// template -InputSoundFile::StreamDeleter::StreamDeleter(const std::default_delete&) -: owned{true} +InputSoundFile::StreamDeleter::StreamDeleter(const std::default_delete&) : owned{true} { - } @@ -65,12 +63,12 @@ void InputSoundFile::StreamDeleter::operator()(InputStream* ptr) const //////////////////////////////////////////////////////////// InputSoundFile::InputSoundFile() : -m_reader (), -m_stream (nullptr, false), +m_reader(), +m_stream(nullptr, false), m_sampleOffset(0), -m_sampleCount (0), +m_sampleCount(0), m_channelCount(0), -m_sampleRate (0) +m_sampleRate(0) { } @@ -111,9 +109,9 @@ bool InputSoundFile::openFromFile(const std::filesystem::path& filename) m_stream = std::move(file); // Retrieve the attributes of the open sound file - m_sampleCount = info.sampleCount; + m_sampleCount = info.sampleCount; m_channelCount = info.channelCount; - m_sampleRate = info.sampleRate; + m_sampleRate = info.sampleRate; return true; } @@ -146,9 +144,9 @@ bool InputSoundFile::openFromMemory(const void* data, std::size_t sizeInBytes) m_stream = std::move(memory); // Retrieve the attributes of the open sound file - m_sampleCount = info.sampleCount; + m_sampleCount = info.sampleCount; m_channelCount = info.channelCount; - m_sampleRate = info.sampleRate; + m_sampleRate = info.sampleRate; return true; } @@ -182,9 +180,9 @@ bool InputSoundFile::openFromStream(InputStream& stream) m_stream = {&stream, false}; // Retrieve the attributes of the open sound file - m_sampleCount = info.sampleCount; + m_sampleCount = info.sampleCount; m_channelCount = info.channelCount; - m_sampleRate = info.sampleRate; + m_sampleRate = info.sampleRate; return true; } @@ -218,7 +216,8 @@ Time InputSoundFile::getDuration() const if (m_channelCount == 0 || m_sampleRate == 0) return Time::Zero; - return seconds(static_cast(m_sampleCount) / static_cast(m_channelCount) / static_cast(m_sampleRate)); + return seconds( + static_cast(m_sampleCount) / static_cast(m_channelCount) / static_cast(m_sampleRate)); } @@ -229,7 +228,8 @@ Time InputSoundFile::getTimeOffset() const if (m_channelCount == 0 || m_sampleRate == 0) return Time::Zero; - return seconds(static_cast(m_sampleOffset) / static_cast(m_channelCount) / static_cast(m_sampleRate)); + return seconds( + static_cast(m_sampleOffset) / static_cast(m_channelCount) / static_cast(m_sampleRate)); } @@ -282,9 +282,9 @@ void InputSoundFile::close() // Reset the sound file attributes m_sampleOffset = 0; - m_sampleCount = 0; + m_sampleCount = 0; m_channelCount = 0; - m_sampleRate = 0; + m_sampleRate = 0; } } // namespace sf diff --git a/src/SFML/Audio/Listener.cpp b/src/SFML/Audio/Listener.cpp index ff55be303..bab54edf1 100644 --- a/src/SFML/Audio/Listener.cpp +++ b/src/SFML/Audio/Listener.cpp @@ -25,8 +25,8 @@ //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// -#include #include +#include namespace sf diff --git a/src/SFML/Audio/Music.cpp b/src/SFML/Audio/Music.cpp index 9570556c5..f1c9c5cbc 100644 --- a/src/SFML/Audio/Music.cpp +++ b/src/SFML/Audio/Music.cpp @@ -25,31 +25,29 @@ //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// -#include #include +#include #include #include -#include + #include +#include #include #include #if defined(__APPLE__) - #if defined(__clang__) - #pragma clang diagnostic ignored "-Wdeprecated-declarations" - #elif defined(__GNUC__) - #pragma GCC diagnostic ignored "-Wdeprecated-declarations" - #endif +#if defined(__clang__) +#pragma clang diagnostic ignored "-Wdeprecated-declarations" +#elif defined(__GNUC__) +#pragma GCC diagnostic ignored "-Wdeprecated-declarations" +#endif #endif namespace sf { //////////////////////////////////////////////////////////// -Music::Music() : -m_file (), -m_loopSpan (0, 0) +Music::Music() : m_file(), m_loopSpan(0, 0) { - } @@ -167,7 +165,7 @@ void Music::setLoopPoints(TimeSpan timePoints) // Get old playing status and position Status oldStatus = getStatus(); - Time oldPos = getPlayingOffset(); + Time oldPos = getPlayingOffset(); // Unload stop(); @@ -190,9 +188,9 @@ bool Music::onGetData(SoundStream::Chunk& data) { std::scoped_lock lock(m_mutex); - std::size_t toFill = m_samples.size(); - Uint64 currentOffset = m_file.getSampleOffset(); - Uint64 loopEnd = m_loopSpan.offset + m_loopSpan.length; + std::size_t toFill = m_samples.size(); + Uint64 currentOffset = m_file.getSampleOffset(); + Uint64 loopEnd = m_loopSpan.offset + m_loopSpan.length; // If the loop end is enabled and imminent, request less data. // This will trip an "onLoop()" call from the underlying SoundStream, @@ -201,12 +199,13 @@ bool Music::onGetData(SoundStream::Chunk& data) toFill = static_cast(loopEnd - currentOffset); // Fill the chunk parameters - data.samples = m_samples.data(); + data.samples = m_samples.data(); data.sampleCount = static_cast(m_file.read(m_samples.data(), toFill)); currentOffset += data.sampleCount; // Check if we have stopped obtaining samples or reached either the EOF or the loop end point - return (data.sampleCount != 0) && (currentOffset < m_file.getSampleCount()) && !(currentOffset == loopEnd && m_loopSpan.length != 0); + return (data.sampleCount != 0) && (currentOffset < m_file.getSampleCount()) && + !(currentOffset == loopEnd && m_loopSpan.length != 0); } @@ -223,7 +222,7 @@ Int64 Music::onLoop() { // Called by underlying SoundStream so we can determine where to loop. std::scoped_lock lock(m_mutex); - Uint64 currentOffset = m_file.getSampleOffset(); + Uint64 currentOffset = m_file.getSampleOffset(); if (getLoop() && (m_loopSpan.length != 0) && (currentOffset == m_loopSpan.offset + m_loopSpan.length)) { // Looping is enabled, and either we're at the loop end, or we're at the EOF diff --git a/src/SFML/Audio/OutputSoundFile.cpp b/src/SFML/Audio/OutputSoundFile.cpp index 67248a49e..62b522898 100644 --- a/src/SFML/Audio/OutputSoundFile.cpp +++ b/src/SFML/Audio/OutputSoundFile.cpp @@ -26,15 +26,14 @@ // Headers //////////////////////////////////////////////////////////// #include -#include #include +#include namespace sf { //////////////////////////////////////////////////////////// -OutputSoundFile::OutputSoundFile() : -m_writer(nullptr) +OutputSoundFile::OutputSoundFile() : m_writer(nullptr) { } diff --git a/src/SFML/Audio/Sound.cpp b/src/SFML/Audio/Sound.cpp index f6914ad3e..84451e273 100644 --- a/src/SFML/Audio/Sound.cpp +++ b/src/SFML/Audio/Sound.cpp @@ -25,39 +25,35 @@ //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// +#include #include #include -#include #if defined(__APPLE__) - #if defined(__clang__) - #pragma clang diagnostic ignored "-Wdeprecated-declarations" - #elif defined(__GNUC__) - #pragma GCC diagnostic ignored "-Wdeprecated-declarations" - #endif +#if defined(__clang__) +#pragma clang diagnostic ignored "-Wdeprecated-declarations" +#elif defined(__GNUC__) +#pragma GCC diagnostic ignored "-Wdeprecated-declarations" +#endif #endif namespace sf { //////////////////////////////////////////////////////////// -Sound::Sound() : -m_buffer(nullptr) +Sound::Sound() : m_buffer(nullptr) { } //////////////////////////////////////////////////////////// -Sound::Sound(const SoundBuffer& buffer) : -m_buffer(nullptr) +Sound::Sound(const SoundBuffer& buffer) : m_buffer(nullptr) { setBuffer(buffer); } //////////////////////////////////////////////////////////// -Sound::Sound(const Sound& copy) : -SoundSource(copy), -m_buffer (nullptr) +Sound::Sound(const Sound& copy) : SoundSource(copy), m_buffer(nullptr) { if (copy.m_buffer) setBuffer(*copy.m_buffer); @@ -161,7 +157,7 @@ Sound::Status Sound::getStatus() const //////////////////////////////////////////////////////////// -Sound& Sound::operator =(const Sound& right) +Sound& Sound::operator=(const Sound& right) { // Here we don't use the copy-and-swap idiom, because it would mess up // the list of sound instances contained in the buffers and unnecessarily diff --git a/src/SFML/Audio/SoundBuffer.cpp b/src/SFML/Audio/SoundBuffer.cpp index 63e5028a0..b66e38e5d 100644 --- a/src/SFML/Audio/SoundBuffer.cpp +++ b/src/SFML/Audio/SoundBuffer.cpp @@ -25,31 +25,30 @@ //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// -#include +#include +#include #include #include #include -#include -#include +#include #include #include + #include #include #if defined(__APPLE__) - #if defined(__clang__) - #pragma clang diagnostic ignored "-Wdeprecated-declarations" - #elif defined(__GNUC__) - #pragma GCC diagnostic ignored "-Wdeprecated-declarations" - #endif +#if defined(__clang__) +#pragma clang diagnostic ignored "-Wdeprecated-declarations" +#elif defined(__GNUC__) +#pragma GCC diagnostic ignored "-Wdeprecated-declarations" +#endif #endif namespace sf { //////////////////////////////////////////////////////////// -SoundBuffer::SoundBuffer() : -m_buffer (0), -m_duration() +SoundBuffer::SoundBuffer() : m_buffer(0), m_duration() { // Create the buffer alCheck(alGenBuffers(1, &m_buffer)); @@ -58,10 +57,10 @@ m_duration() //////////////////////////////////////////////////////////// SoundBuffer::SoundBuffer(const SoundBuffer& copy) : -m_buffer (0), -m_samples (copy.m_samples), +m_buffer(0), +m_samples(copy.m_samples), m_duration(copy.m_duration), -m_sounds () // don't copy the attached sounds +m_sounds() // don't copy the attached sounds { // Create the buffer alCheck(alGenBuffers(1, &m_buffer)); @@ -139,11 +138,10 @@ bool SoundBuffer::loadFromSamples(const Int16* samples, Uint64 sampleCount, unsi { // Error... err() << "Failed to load sound buffer from samples (" - << "array: " << samples << ", " - << "count: " << sampleCount << ", " - << "channels: " << channelCount << ", " - << "samplerate: " << sampleRate << ")" - << std::endl; + << "array: " << samples << ", " + << "count: " << sampleCount << ", " + << "channels: " << channelCount << ", " + << "samplerate: " << sampleRate << ")" << std::endl; return false; } @@ -211,14 +209,14 @@ Time SoundBuffer::getDuration() const //////////////////////////////////////////////////////////// -SoundBuffer& SoundBuffer::operator =(const SoundBuffer& right) +SoundBuffer& SoundBuffer::operator=(const SoundBuffer& right) { SoundBuffer temp(right); - std::swap(m_samples, temp.m_samples); - std::swap(m_buffer, temp.m_buffer); + std::swap(m_samples, temp.m_samples); + std::swap(m_buffer, temp.m_buffer); std::swap(m_duration, temp.m_duration); - std::swap(m_sounds, temp.m_sounds); // swap sounds too, so that they are detached when temp is destroyed + std::swap(m_sounds, temp.m_sounds); // swap sounds too, so that they are detached when temp is destroyed return *this; } @@ -275,7 +273,8 @@ bool SoundBuffer::update(unsigned int channelCount, unsigned int sampleRate) alCheck(alBufferData(m_buffer, format, m_samples.data(), size, static_cast(sampleRate))); // Compute the duration - m_duration = seconds(static_cast(m_samples.size()) / static_cast(sampleRate) / static_cast(channelCount)); + m_duration = seconds( + static_cast(m_samples.size()) / static_cast(sampleRate) / static_cast(channelCount)); // Now reattach the buffer to the sounds that use it for (Sound* soundPtr : sounds) diff --git a/src/SFML/Audio/SoundBufferRecorder.cpp b/src/SFML/Audio/SoundBufferRecorder.cpp index c7bc4e799..df038cefc 100644 --- a/src/SFML/Audio/SoundBufferRecorder.cpp +++ b/src/SFML/Audio/SoundBufferRecorder.cpp @@ -27,6 +27,7 @@ //////////////////////////////////////////////////////////// #include #include + #include #include #include diff --git a/src/SFML/Audio/SoundFileFactory.cpp b/src/SFML/Audio/SoundFileFactory.cpp index 91e1e0426..e3efae17f 100644 --- a/src/SFML/Audio/SoundFileFactory.cpp +++ b/src/SFML/Audio/SoundFileFactory.cpp @@ -27,38 +27,39 @@ //////////////////////////////////////////////////////////// #include #include -#include #include #include -#include #include +#include +#include #include +#include #include #include -#include #include + #include namespace { - // Register all the built-in readers and writers if not already done - void ensureDefaultReadersWritersRegistered() +// Register all the built-in readers and writers if not already done +void ensureDefaultReadersWritersRegistered() +{ + static bool registered = false; + if (!registered) { - static bool registered = false; - if (!registered) - { - sf::SoundFileFactory::registerReader(); - sf::SoundFileFactory::registerWriter(); - sf::SoundFileFactory::registerReader(); - sf::SoundFileFactory::registerReader(); - sf::SoundFileFactory::registerWriter(); - sf::SoundFileFactory::registerReader(); - sf::SoundFileFactory::registerWriter(); - registered = true; - } + sf::SoundFileFactory::registerReader(); + sf::SoundFileFactory::registerWriter(); + sf::SoundFileFactory::registerReader(); + sf::SoundFileFactory::registerReader(); + sf::SoundFileFactory::registerWriter(); + sf::SoundFileFactory::registerReader(); + sf::SoundFileFactory::registerWriter(); + registered = true; } } +} // namespace namespace sf { @@ -74,7 +75,8 @@ std::unique_ptr SoundFileFactory::createReaderFromFilename(cons // Wrap the input file into a file stream FileInputStream stream; - if (!stream.open(filename)) { + if (!stream.open(filename)) + { err() << "Failed to open sound file (couldn't open stream)\n" << formatDebugPathInfo(filename) << std::endl; return nullptr; } diff --git a/src/SFML/Audio/SoundFileReaderFlac.cpp b/src/SFML/Audio/SoundFileReaderFlac.cpp index f5e73037e..ef36c7595 100644 --- a/src/SFML/Audio/SoundFileReaderFlac.cpp +++ b/src/SFML/Audio/SoundFileReaderFlac.cpp @@ -26,156 +26,160 @@ // Headers //////////////////////////////////////////////////////////// #include -#include #include +#include + #include #include namespace { - FLAC__StreamDecoderReadStatus streamRead(const FLAC__StreamDecoder*, FLAC__byte buffer[], std::size_t* bytes, void* clientData) - { - auto* data = static_cast(clientData); +FLAC__StreamDecoderReadStatus streamRead(const FLAC__StreamDecoder*, FLAC__byte buffer[], std::size_t* bytes, void* clientData) +{ + auto* data = static_cast(clientData); - sf::Int64 count = data->stream->read(buffer, static_cast(*bytes)); - if (count > 0) - { - *bytes = static_cast(count); - return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE; - } - else if (count == 0) - { - return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM; - } - else - { - return FLAC__STREAM_DECODER_READ_STATUS_ABORT; - } + sf::Int64 count = data->stream->read(buffer, static_cast(*bytes)); + if (count > 0) + { + *bytes = static_cast(count); + return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE; } - - FLAC__StreamDecoderSeekStatus streamSeek(const FLAC__StreamDecoder*, FLAC__uint64 absoluteByteOffset, void* clientData) + else if (count == 0) { - auto* data = static_cast(clientData); - - sf::Int64 position = data->stream->seek(static_cast(absoluteByteOffset)); - if (position >= 0) - return FLAC__STREAM_DECODER_SEEK_STATUS_OK; - else - return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR; + return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM; } - - FLAC__StreamDecoderTellStatus streamTell(const FLAC__StreamDecoder*, FLAC__uint64* absoluteByteOffset, void* clientData) + else { - auto* data = static_cast(clientData); - - sf::Int64 position = data->stream->tell(); - if (position >= 0) - { - *absoluteByteOffset = static_cast(position); - return FLAC__STREAM_DECODER_TELL_STATUS_OK; - } - else - { - return FLAC__STREAM_DECODER_TELL_STATUS_ERROR; - } - } - - FLAC__StreamDecoderLengthStatus streamLength(const FLAC__StreamDecoder*, FLAC__uint64* streamLength, void* clientData) - { - auto* data = static_cast(clientData); - - sf::Int64 count = data->stream->getSize(); - if (count >= 0) - { - *streamLength = static_cast(count); - return FLAC__STREAM_DECODER_LENGTH_STATUS_OK; - } - else - { - return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR; - } - } - - FLAC__bool streamEof(const FLAC__StreamDecoder*, void* clientData) - { - auto* data = static_cast(clientData); - - return data->stream->tell() == data->stream->getSize(); - } - - FLAC__StreamDecoderWriteStatus streamWrite(const FLAC__StreamDecoder*, const FLAC__Frame* frame, const FLAC__int32* const buffer[], void* clientData) - { - auto* data = static_cast(clientData); - - // Reserve memory if we're going to use the leftovers buffer - unsigned int frameSamples = frame->header.blocksize * frame->header.channels; - if (data->remaining < frameSamples) - data->leftovers.reserve(static_cast(frameSamples - data->remaining)); - - // Decode the samples - for (unsigned i = 0; i < frame->header.blocksize; ++i) - { - for (unsigned int j = 0; j < frame->header.channels; ++j) - { - // Decode the current sample - sf::Int16 sample = 0; - switch (frame->header.bits_per_sample) - { - case 8: - sample = static_cast(buffer[j][i] << 8); - break; - case 16: - sample = static_cast(buffer[j][i]); - break; - case 24: - sample = static_cast(buffer[j][i] >> 8); - break; - case 32: - sample = static_cast(buffer[j][i] >> 16); - break; - default: - assert(false); - break; - } - - if (data->buffer && data->remaining > 0) - { - // If there's room in the output buffer, copy the sample there - *data->buffer++ = sample; - --data->remaining; - } - else - { - // We are either seeking (null buffer) or have decoded all the requested samples during a - // normal read (0 remaining), so we put the sample in a temporary buffer until next call - data->leftovers.push_back(sample); - } - } - } - - return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE; - } - - void streamMetadata(const FLAC__StreamDecoder*, const FLAC__StreamMetadata* meta, void* clientData) - { - auto* data = static_cast(clientData); - - if (meta->type == FLAC__METADATA_TYPE_STREAMINFO) - { - data->info.sampleCount = meta->data.stream_info.total_samples * meta->data.stream_info.channels; - data->info.sampleRate = meta->data.stream_info.sample_rate; - data->info.channelCount = meta->data.stream_info.channels; - } - } - - void streamError(const FLAC__StreamDecoder*, FLAC__StreamDecoderErrorStatus, void* clientData) - { - auto* data = static_cast(clientData); - data->error = true; + return FLAC__STREAM_DECODER_READ_STATUS_ABORT; } } +FLAC__StreamDecoderSeekStatus streamSeek(const FLAC__StreamDecoder*, FLAC__uint64 absoluteByteOffset, void* clientData) +{ + auto* data = static_cast(clientData); + + sf::Int64 position = data->stream->seek(static_cast(absoluteByteOffset)); + if (position >= 0) + return FLAC__STREAM_DECODER_SEEK_STATUS_OK; + else + return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR; +} + +FLAC__StreamDecoderTellStatus streamTell(const FLAC__StreamDecoder*, FLAC__uint64* absoluteByteOffset, void* clientData) +{ + auto* data = static_cast(clientData); + + sf::Int64 position = data->stream->tell(); + if (position >= 0) + { + *absoluteByteOffset = static_cast(position); + return FLAC__STREAM_DECODER_TELL_STATUS_OK; + } + else + { + return FLAC__STREAM_DECODER_TELL_STATUS_ERROR; + } +} + +FLAC__StreamDecoderLengthStatus streamLength(const FLAC__StreamDecoder*, FLAC__uint64* streamLength, void* clientData) +{ + auto* data = static_cast(clientData); + + sf::Int64 count = data->stream->getSize(); + if (count >= 0) + { + *streamLength = static_cast(count); + return FLAC__STREAM_DECODER_LENGTH_STATUS_OK; + } + else + { + return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR; + } +} + +FLAC__bool streamEof(const FLAC__StreamDecoder*, void* clientData) +{ + auto* data = static_cast(clientData); + + return data->stream->tell() == data->stream->getSize(); +} + +FLAC__StreamDecoderWriteStatus streamWrite(const FLAC__StreamDecoder*, + const FLAC__Frame* frame, + const FLAC__int32* const buffer[], + void* clientData) +{ + auto* data = static_cast(clientData); + + // Reserve memory if we're going to use the leftovers buffer + unsigned int frameSamples = frame->header.blocksize * frame->header.channels; + if (data->remaining < frameSamples) + data->leftovers.reserve(static_cast(frameSamples - data->remaining)); + + // Decode the samples + for (unsigned i = 0; i < frame->header.blocksize; ++i) + { + for (unsigned int j = 0; j < frame->header.channels; ++j) + { + // Decode the current sample + sf::Int16 sample = 0; + switch (frame->header.bits_per_sample) + { + case 8: + sample = static_cast(buffer[j][i] << 8); + break; + case 16: + sample = static_cast(buffer[j][i]); + break; + case 24: + sample = static_cast(buffer[j][i] >> 8); + break; + case 32: + sample = static_cast(buffer[j][i] >> 16); + break; + default: + assert(false); + break; + } + + if (data->buffer && data->remaining > 0) + { + // If there's room in the output buffer, copy the sample there + *data->buffer++ = sample; + --data->remaining; + } + else + { + // We are either seeking (null buffer) or have decoded all the requested samples during a + // normal read (0 remaining), so we put the sample in a temporary buffer until next call + data->leftovers.push_back(sample); + } + } + } + + return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE; +} + +void streamMetadata(const FLAC__StreamDecoder*, const FLAC__StreamMetadata* meta, void* clientData) +{ + auto* data = static_cast(clientData); + + if (meta->type == FLAC__METADATA_TYPE_STREAMINFO) + { + data->info.sampleCount = meta->data.stream_info.total_samples * meta->data.stream_info.channels; + data->info.sampleRate = meta->data.stream_info.sample_rate; + data->info.channelCount = meta->data.stream_info.channels; + } +} + +void streamError(const FLAC__StreamDecoder*, FLAC__StreamDecoderErrorStatus, void* clientData) +{ + auto* data = static_cast(clientData); + data->error = true; +} +} // namespace + namespace sf { namespace priv @@ -191,8 +195,17 @@ bool SoundFileReaderFlac::check(InputStream& stream) // Initialize the decoder with our callbacks ClientData data; data.stream = &stream; - data.error = false; - FLAC__stream_decoder_init_stream(decoder, &streamRead, &streamSeek, &streamTell, &streamLength, &streamEof, &streamWrite, nullptr, &streamError, &data); + data.error = false; + FLAC__stream_decoder_init_stream(decoder, + &streamRead, + &streamSeek, + &streamTell, + &streamLength, + &streamEof, + &streamWrite, + nullptr, + &streamError, + &data); // Read the header bool valid = FLAC__stream_decoder_process_until_end_of_metadata(decoder) != 0; @@ -206,9 +219,7 @@ bool SoundFileReaderFlac::check(InputStream& stream) //////////////////////////////////////////////////////////// -SoundFileReaderFlac::SoundFileReaderFlac() : -m_decoder(nullptr), -m_clientData() +SoundFileReaderFlac::SoundFileReaderFlac() : m_decoder(nullptr), m_clientData() { } @@ -233,7 +244,16 @@ bool SoundFileReaderFlac::open(InputStream& stream, Info& info) // Initialize the decoder with our callbacks m_clientData.stream = &stream; - FLAC__stream_decoder_init_stream(m_decoder, &streamRead, &streamSeek, &streamTell, &streamLength, &streamEof, &streamWrite, &streamMetadata, &streamError, &m_clientData); + FLAC__stream_decoder_init_stream(m_decoder, + &streamRead, + &streamSeek, + &streamTell, + &streamLength, + &streamEof, + &streamWrite, + &streamMetadata, + &streamError, + &m_clientData); // Read the header if (!FLAC__stream_decoder_process_until_end_of_metadata(m_decoder)) @@ -256,7 +276,7 @@ void SoundFileReaderFlac::seek(Uint64 sampleOffset) assert(m_decoder); // Reset the callback data (the "write" callback will be called) - m_clientData.buffer = nullptr; + m_clientData.buffer = nullptr; m_clientData.remaining = 0; m_clientData.leftovers.clear(); @@ -291,8 +311,12 @@ Uint64 SoundFileReaderFlac::read(Int16* samples, Uint64 maxCount) if (left > maxCount) { // There are more leftovers than needed - std::copy(m_clientData.leftovers.begin(), m_clientData.leftovers.begin() + static_cast::difference_type>(maxCount), samples); - std::vector leftovers(m_clientData.leftovers.begin() + static_cast::difference_type>(maxCount), m_clientData.leftovers.end()); + std::copy(m_clientData.leftovers.begin(), + m_clientData.leftovers.begin() + static_cast::difference_type>(maxCount), + samples); + std::vector leftovers(m_clientData.leftovers.begin() + + static_cast::difference_type>(maxCount), + m_clientData.leftovers.end()); m_clientData.leftovers.swap(leftovers); return maxCount; } @@ -304,7 +328,7 @@ Uint64 SoundFileReaderFlac::read(Int16* samples, Uint64 maxCount) } // Reset the data that will be used in the callback - m_clientData.buffer = samples + left; + m_clientData.buffer = samples + left; m_clientData.remaining = maxCount - left; m_clientData.leftovers.clear(); diff --git a/src/SFML/Audio/SoundFileReaderFlac.hpp b/src/SFML/Audio/SoundFileReaderFlac.hpp index f7732bd23..be0ff1aa4 100644 --- a/src/SFML/Audio/SoundFileReaderFlac.hpp +++ b/src/SFML/Audio/SoundFileReaderFlac.hpp @@ -29,6 +29,7 @@ // Headers //////////////////////////////////////////////////////////// #include + #include #include @@ -44,7 +45,6 @@ namespace priv class SoundFileReaderFlac : public SoundFileReader { public: - //////////////////////////////////////////////////////////// /// \brief Check if this reader can handle a file given by an input stream /// @@ -56,7 +56,6 @@ public: [[nodiscard]] static bool check(InputStream& stream); public: - //////////////////////////////////////////////////////////// /// \brief Default constructor /// @@ -105,7 +104,6 @@ public: [[nodiscard]] Uint64 read(Int16* samples, Uint64 maxCount) override; public: - //////////////////////////////////////////////////////////// /// \brief Hold the state that is passed to the decoder callbacks /// @@ -121,7 +119,6 @@ public: }; private: - //////////////////////////////////////////////////////////// /// \brief Close the open FLAC file /// diff --git a/src/SFML/Audio/SoundFileReaderMp3.cpp b/src/SFML/Audio/SoundFileReaderMp3.cpp index 78401c6e6..48c75f807 100644 --- a/src/SFML/Audio/SoundFileReaderMp3.cpp +++ b/src/SFML/Audio/SoundFileReaderMp3.cpp @@ -27,9 +27,9 @@ //////////////////////////////////////////////////////////// #define MINIMP3_IMPLEMENTATION // Minimp3 control define, places implementation in this file. #ifndef NOMINMAX -#define NOMINMAX // To avoid windows.h and std::min issue +#define NOMINMAX // To avoid windows.h and std::min issue #endif -#define MINIMP3_NO_STDIO // Minimp3 control define, eliminate file manipulation code which is useless here +#define MINIMP3_NO_STDIO // Minimp3 control define, eliminate file manipulation code which is useless here #ifdef _MSC_VER #pragma warning(push) @@ -47,6 +47,7 @@ #include #include + #include #include @@ -61,16 +62,17 @@ std::size_t readCallback(void* ptr, std::size_t size, void* data) int seekCallback(std::uint64_t offset, void* data) { - sf::InputStream* stream = static_cast(data); - sf::Int64 position = stream->seek(static_cast(offset)); + sf::InputStream* stream = static_cast(data); + sf::Int64 position = stream->seek(static_cast(offset)); return position < 0 ? -1 : 0; } bool hasValidId3Tag(const sf::Uint8* header) { - return std::memcmp(header, "ID3", 3) == 0 && !((header[5] & 15) || (header[6] & 0x80) || (header[7] & 0x80) || (header[8] & 0x80) || (header[9] & 0x80)); -} + return std::memcmp(header, "ID3", 3) == 0 && + !((header[5] & 15) || (header[6] & 0x80) || (header[7] & 0x80) || (header[8] & 0x80) || (header[9] & 0x80)); } +} // namespace namespace sf { @@ -95,9 +97,7 @@ bool SoundFileReaderMp3::check(InputStream& stream) //////////////////////////////////////////////////////////// -SoundFileReaderMp3::SoundFileReaderMp3() : -m_numSamples(0), -m_position(0) +SoundFileReaderMp3::SoundFileReaderMp3() : m_numSamples(0), m_position(0) { std::memset(&m_io, 0, sizeof(m_io)); std::memset(&m_decoder, 0, sizeof(m_decoder)); @@ -130,7 +130,7 @@ bool SoundFileReaderMp3::open(InputStream& stream, Info& info) info.sampleRate = static_cast(m_decoder.info.hz); info.sampleCount = m_decoder.samples; - m_numSamples = info.sampleCount; + m_numSamples = info.sampleCount; return true; } @@ -147,7 +147,7 @@ void SoundFileReaderMp3::seek(Uint64 sampleOffset) Uint64 SoundFileReaderMp3::read(Int16* samples, Uint64 maxCount) { Uint64 toRead = std::min(maxCount, m_numSamples - m_position); - toRead = static_cast(mp3dec_ex_read(&m_decoder, samples, static_cast(toRead))); + toRead = static_cast(mp3dec_ex_read(&m_decoder, samples, static_cast(toRead))); m_position += toRead; return toRead; } diff --git a/src/SFML/Audio/SoundFileReaderMp3.hpp b/src/SFML/Audio/SoundFileReaderMp3.hpp index a9591135c..67055b0f4 100644 --- a/src/SFML/Audio/SoundFileReaderMp3.hpp +++ b/src/SFML/Audio/SoundFileReaderMp3.hpp @@ -29,9 +29,9 @@ // Headers //////////////////////////////////////////////////////////// #ifndef NOMINMAX -#define NOMINMAX // To avoid windows.h and std::min issue +#define NOMINMAX // To avoid windows.h and std::min issue #endif -#define MINIMP3_NO_STDIO // Minimp3 control define, eliminate file manipulation code which is useless here +#define MINIMP3_NO_STDIO // Minimp3 control define, eliminate file manipulation code which is useless here #ifdef _MSC_VER #pragma warning(push) @@ -48,6 +48,7 @@ #undef MINIMP3_NO_STDIO #include + #include @@ -62,7 +63,6 @@ namespace priv class SoundFileReaderMp3 : public SoundFileReader { public: - //////////////////////////////////////////////////////////// /// \brief Check if this reader can handle a file given by an input stream /// @@ -74,7 +74,6 @@ public: [[nodiscard]] static bool check(InputStream& stream); public: - //////////////////////////////////////////////////////////// /// \brief Default constructor /// @@ -125,14 +124,13 @@ public: [[nodiscard]] Uint64 read(Int16* samples, Uint64 maxCount) override; private: - //////////////////////////////////////////////////////////// // Member data //////////////////////////////////////////////////////////// - mp3dec_io_t m_io; - mp3dec_ex_t m_decoder; - Uint64 m_numSamples; // Decompressed audio storage size - Uint64 m_position; // Position in decompressed audio buffer + mp3dec_io_t m_io; + mp3dec_ex_t m_decoder; + Uint64 m_numSamples; // Decompressed audio storage size + Uint64 m_position; // Position in decompressed audio buffer }; } // namespace priv diff --git a/src/SFML/Audio/SoundFileReaderOgg.cpp b/src/SFML/Audio/SoundFileReaderOgg.cpp index 1604c5bcc..8c3bf7df3 100644 --- a/src/SFML/Audio/SoundFileReaderOgg.cpp +++ b/src/SFML/Audio/SoundFileReaderOgg.cpp @@ -26,46 +26,47 @@ // Headers //////////////////////////////////////////////////////////// #include -#include #include -#include +#include + #include +#include #include namespace { - size_t read(void* ptr, size_t size, size_t nmemb, void* data) - { - auto* stream = static_cast(data); - return static_cast(stream->read(ptr, static_cast(size * nmemb))); - } - - int seek(void* data, ogg_int64_t offset, int whence) - { - auto* stream = static_cast(data); - switch (whence) - { - case SEEK_SET: - break; - case SEEK_CUR: - offset += stream->tell(); - break; - case SEEK_END: - offset = stream->getSize() - offset; - } - return static_cast(stream->seek(offset)); - } - - long tell(void* data) - { - auto* stream = static_cast(data); - return static_cast(stream->tell()); - } - - static ov_callbacks callbacks = {&read, &seek, nullptr, &tell}; +size_t read(void* ptr, size_t size, size_t nmemb, void* data) +{ + auto* stream = static_cast(data); + return static_cast(stream->read(ptr, static_cast(size * nmemb))); } +int seek(void* data, ogg_int64_t offset, int whence) +{ + auto* stream = static_cast(data); + switch (whence) + { + case SEEK_SET: + break; + case SEEK_CUR: + offset += stream->tell(); + break; + case SEEK_END: + offset = stream->getSize() - offset; + } + return static_cast(stream->seek(offset)); +} + +long tell(void* data) +{ + auto* stream = static_cast(data); + return static_cast(stream->tell()); +} + +static ov_callbacks callbacks = {&read, &seek, nullptr, &tell}; +} // namespace + namespace sf { namespace priv @@ -87,9 +88,7 @@ bool SoundFileReaderOgg::check(InputStream& stream) //////////////////////////////////////////////////////////// -SoundFileReaderOgg::SoundFileReaderOgg() : -m_vorbis (), -m_channelCount(0) +SoundFileReaderOgg::SoundFileReaderOgg() : m_vorbis(), m_channelCount(0) { m_vorbis.datasource = nullptr; } @@ -115,9 +114,9 @@ bool SoundFileReaderOgg::open(InputStream& stream, Info& info) // Retrieve the music attributes vorbis_info* vorbisInfo = ov_info(&m_vorbis, -1); - info.channelCount = static_cast(vorbisInfo->channels); - info.sampleRate = static_cast(vorbisInfo->rate); - info.sampleCount = static_cast(ov_pcm_total(&m_vorbis, -1) * vorbisInfo->channels); + info.channelCount = static_cast(vorbisInfo->channels); + info.sampleRate = static_cast(vorbisInfo->rate); + info.sampleCount = static_cast(ov_pcm_total(&m_vorbis, -1) * vorbisInfo->channels); // We must keep the channel count for the seek function m_channelCount = info.channelCount; @@ -144,8 +143,8 @@ Uint64 SoundFileReaderOgg::read(Int16* samples, Uint64 maxCount) Uint64 count = 0; while (count < maxCount) { - int bytesToRead = static_cast(maxCount - count) * static_cast(sizeof(Int16)); - long bytesRead = ov_read(&m_vorbis, reinterpret_cast(samples), bytesToRead, 0, 2, 1, nullptr); + int bytesToRead = static_cast(maxCount - count) * static_cast(sizeof(Int16)); + long bytesRead = ov_read(&m_vorbis, reinterpret_cast(samples), bytesToRead, 0, 2, 1, nullptr); if (bytesRead > 0) { long samplesRead = bytesRead / static_cast(sizeof(Int16)); @@ -170,7 +169,7 @@ void SoundFileReaderOgg::close() { ov_clear(&m_vorbis); m_vorbis.datasource = nullptr; - m_channelCount = 0; + m_channelCount = 0; } } diff --git a/src/SFML/Audio/SoundFileReaderOgg.hpp b/src/SFML/Audio/SoundFileReaderOgg.hpp index 771bc05cb..711c6ca93 100644 --- a/src/SFML/Audio/SoundFileReaderOgg.hpp +++ b/src/SFML/Audio/SoundFileReaderOgg.hpp @@ -29,6 +29,7 @@ // Headers //////////////////////////////////////////////////////////// #include + #include @@ -43,7 +44,6 @@ namespace priv class SoundFileReaderOgg : public SoundFileReader { public: - //////////////////////////////////////////////////////////// /// \brief Check if this reader can handle a file given by an input stream /// @@ -55,7 +55,6 @@ public: [[nodiscard]] static bool check(InputStream& stream); public: - //////////////////////////////////////////////////////////// /// \brief Default constructor /// @@ -106,7 +105,6 @@ public: [[nodiscard]] Uint64 read(Int16* samples, Uint64 maxCount) override; private: - //////////////////////////////////////////////////////////// /// \brief Close the open Vorbis file /// diff --git a/src/SFML/Audio/SoundFileReaderWav.cpp b/src/SFML/Audio/SoundFileReaderWav.cpp index d5df82b42..4e4e5d079 100644 --- a/src/SFML/Audio/SoundFileReaderWav.cpp +++ b/src/SFML/Audio/SoundFileReaderWav.cpp @@ -26,80 +26,81 @@ // Headers //////////////////////////////////////////////////////////// #include -#include #include +#include + #include -#include #include +#include #include #include namespace { - // The following functions read integers as little endian and - // return them in the host byte order +// The following functions read integers as little endian and +// return them in the host byte order - bool decode(sf::InputStream& stream, sf::Uint8& value) - { - return static_cast(stream.read(&value, sizeof(value))) == sizeof(value); - } - - bool decode(sf::InputStream& stream, sf::Int16& value) - { - unsigned char bytes[sizeof(value)]; - if (static_cast(stream.read(bytes, static_cast(sizeof(bytes)))) != sizeof(bytes)) - return false; - - value = static_cast(bytes[0] | (bytes[1] << 8)); - - return true; - } - - bool decode(sf::InputStream& stream, sf::Uint16& value) - { - unsigned char bytes[sizeof(value)]; - if (static_cast(stream.read(bytes, static_cast(sizeof(bytes)))) != sizeof(bytes)) - return false; - - value = static_cast(bytes[0] | (bytes[1] << 8)); - - return true; - } - - bool decode24bit(sf::InputStream& stream, sf::Uint32& value) - { - unsigned char bytes[3]; - if (static_cast(stream.read(bytes, static_cast(sizeof(bytes)))) != sizeof(bytes)) - return false; - - value = static_cast(bytes[0] | (bytes[1] << 8) | (bytes[2] << 16)); - - return true; - } - - bool decode(sf::InputStream& stream, sf::Uint32& value) - { - unsigned char bytes[sizeof(value)]; - if (static_cast(stream.read(bytes, static_cast(sizeof(bytes)))) != sizeof(bytes)) - return false; - - value = static_cast(bytes[0] | (bytes[1] << 8) | (bytes[2] << 16) | (bytes[3] << 24)); - - return true; - } - - const sf::Uint64 mainChunkSize = 12; - - const sf::Uint16 waveFormatPcm = 1; - - const sf::Uint16 waveFormatExtensible= 65534; - - const char* waveSubformatPcm = - "\x01\x00\x00\x00\x00\x00\x10\x00" - "\x80\x00\x00\xAA\x00\x38\x9B\x71"; +bool decode(sf::InputStream& stream, sf::Uint8& value) +{ + return static_cast(stream.read(&value, sizeof(value))) == sizeof(value); } +bool decode(sf::InputStream& stream, sf::Int16& value) +{ + unsigned char bytes[sizeof(value)]; + if (static_cast(stream.read(bytes, static_cast(sizeof(bytes)))) != sizeof(bytes)) + return false; + + value = static_cast(bytes[0] | (bytes[1] << 8)); + + return true; +} + +bool decode(sf::InputStream& stream, sf::Uint16& value) +{ + unsigned char bytes[sizeof(value)]; + if (static_cast(stream.read(bytes, static_cast(sizeof(bytes)))) != sizeof(bytes)) + return false; + + value = static_cast(bytes[0] | (bytes[1] << 8)); + + return true; +} + +bool decode24bit(sf::InputStream& stream, sf::Uint32& value) +{ + unsigned char bytes[3]; + if (static_cast(stream.read(bytes, static_cast(sizeof(bytes)))) != sizeof(bytes)) + return false; + + value = static_cast(bytes[0] | (bytes[1] << 8) | (bytes[2] << 16)); + + return true; +} + +bool decode(sf::InputStream& stream, sf::Uint32& value) +{ + unsigned char bytes[sizeof(value)]; + if (static_cast(stream.read(bytes, static_cast(sizeof(bytes)))) != sizeof(bytes)) + return false; + + value = static_cast(bytes[0] | (bytes[1] << 8) | (bytes[2] << 16) | (bytes[3] << 24)); + + return true; +} + +const sf::Uint64 mainChunkSize = 12; + +const sf::Uint16 waveFormatPcm = 1; + +const sf::Uint16 waveFormatExtensible = 65534; + +const char* waveSubformatPcm = + "\x01\x00\x00\x00\x00\x00\x10\x00" + "\x80\x00\x00\xAA\x00\x38\x9B\x71"; +} // namespace + namespace sf { namespace priv @@ -111,17 +112,13 @@ bool SoundFileReaderWav::check(InputStream& stream) if (stream.read(header, sizeof(header)) < static_cast(sizeof(header))) return false; - return (header[0] == 'R') && (header[1] == 'I') && (header[2] == 'F') && (header[3] == 'F') - && (header[8] == 'W') && (header[9] == 'A') && (header[10] == 'V') && (header[11] == 'E'); + return (header[0] == 'R') && (header[1] == 'I') && (header[2] == 'F') && (header[3] == 'F') && (header[8] == 'W') && + (header[9] == 'A') && (header[10] == 'V') && (header[11] == 'E'); } //////////////////////////////////////////////////////////// -SoundFileReaderWav::SoundFileReaderWav() : -m_stream (nullptr), -m_bytesPerSample(0), -m_dataStart (0), -m_dataEnd (0) +SoundFileReaderWav::SoundFileReaderWav() : m_stream(nullptr), m_bytesPerSample(0), m_dataStart(0), m_dataEnd(0) { } @@ -156,8 +153,8 @@ Uint64 SoundFileReaderWav::read(Int16* samples, Uint64 maxCount) { assert(m_stream); - Uint64 count = 0; - auto startPos = static_cast(m_stream->tell()); + Uint64 count = 0; + auto startPos = static_cast(m_stream->tell()); // Tracking of m_dataEnd is important to prevent sf::Music from reading // data until EOF, as WAV files may have metadata at the end. @@ -236,7 +233,8 @@ bool SoundFileReaderWav::parseHeader(Info& info) { // Parse the sub-chunk id and size char subChunkId[4]; - if (static_cast(m_stream->read(subChunkId, static_cast(sizeof(subChunkId)))) != sizeof(subChunkId)) + if (static_cast(m_stream->read(subChunkId, static_cast(sizeof(subChunkId)))) != + sizeof(subChunkId)) return false; Uint32 subChunkSize = 0; if (!decode(*m_stream, subChunkSize)) @@ -285,7 +283,8 @@ bool SoundFileReaderWav::parseHeader(Info& info) return false; if (bitsPerSample != 8 && bitsPerSample != 16 && bitsPerSample != 24 && bitsPerSample != 32) { - err() << "Unsupported sample size: " << bitsPerSample << " bit (Supported sample sizes are 8/16/24/32 bit)" << std::endl; + err() << "Unsupported sample size: " << bitsPerSample + << " bit (Supported sample sizes are 8/16/24/32 bit)" << std::endl; return false; } m_bytesPerSample = bitsPerSample / 8; @@ -309,7 +308,8 @@ bool SoundFileReaderWav::parseHeader(Info& info) // Subformat char subformat[16]; - if (static_cast(m_stream->read(subformat, static_cast(sizeof(subformat)))) != sizeof(subformat)) + if (static_cast(m_stream->read(subformat, static_cast(sizeof(subformat)))) != + sizeof(subformat)) return false; if (std::memcmp(subformat, waveSubformatPcm, sizeof(subformat)) != 0) @@ -320,8 +320,10 @@ bool SoundFileReaderWav::parseHeader(Info& info) if (validBitsPerSample != bitsPerSample) { - err() << "Unsupported format: sample size (" << validBitsPerSample << " bits) and " - "sample container size (" << bitsPerSample << " bits) differ" << std::endl; + err() << "Unsupported format: sample size (" << validBitsPerSample + << " bits) and " + "sample container size (" + << bitsPerSample << " bits) differ" << std::endl; return false; } } @@ -339,7 +341,7 @@ bool SoundFileReaderWav::parseHeader(Info& info) // Store the start and end position of samples in the file m_dataStart = static_cast(subChunkStart); - m_dataEnd = m_dataStart + info.sampleCount * m_bytesPerSample; + m_dataEnd = m_dataStart + info.sampleCount * m_bytesPerSample; dataChunkFound = true; } diff --git a/src/SFML/Audio/SoundFileReaderWav.hpp b/src/SFML/Audio/SoundFileReaderWav.hpp index dadf2e878..b3a768de8 100644 --- a/src/SFML/Audio/SoundFileReaderWav.hpp +++ b/src/SFML/Audio/SoundFileReaderWav.hpp @@ -42,7 +42,6 @@ namespace priv class SoundFileReaderWav : public SoundFileReader { public: - //////////////////////////////////////////////////////////// /// \brief Check if this reader can handle a file given by an input stream /// @@ -54,7 +53,6 @@ public: [[nodiscard]] static bool check(InputStream& stream); public: - //////////////////////////////////////////////////////////// /// \brief Default constructor /// @@ -97,7 +95,6 @@ public: [[nodiscard]] Uint64 read(Int16* samples, Uint64 maxCount) override; private: - //////////////////////////////////////////////////////////// /// \brief Read the header of the open file /// diff --git a/src/SFML/Audio/SoundFileWriterFlac.cpp b/src/SFML/Audio/SoundFileWriterFlac.cpp index f62811f3f..ed9b1ec74 100644 --- a/src/SFML/Audio/SoundFileWriterFlac.cpp +++ b/src/SFML/Audio/SoundFileWriterFlac.cpp @@ -28,9 +28,10 @@ #include #include #include + #include -#include #include +#include #include @@ -46,10 +47,7 @@ bool SoundFileWriterFlac::check(const std::filesystem::path& filename) //////////////////////////////////////////////////////////// -SoundFileWriterFlac::SoundFileWriterFlac() : -m_encoder (nullptr), -m_channelCount(0), -m_samples32 () +SoundFileWriterFlac::SoundFileWriterFlac() : m_encoder(nullptr), m_channelCount(0), m_samples32() { } @@ -68,7 +66,8 @@ bool SoundFileWriterFlac::open(const std::filesystem::path& filename, unsigned i m_encoder = FLAC__stream_encoder_new(); if (!m_encoder) { - err() << "Failed to write flac file (failed to allocate encoder)\n" << formatDebugPathInfo(filename) << std::endl; + err() << "Failed to write flac file (failed to allocate encoder)\n" + << formatDebugPathInfo(filename) << std::endl; return false; } @@ -78,7 +77,8 @@ bool SoundFileWriterFlac::open(const std::filesystem::path& filename, unsigned i FLAC__stream_encoder_set_sample_rate(m_encoder, sampleRate); // Initialize the output stream - if (FLAC__stream_encoder_init_file(m_encoder, filename.string().c_str(), nullptr, nullptr) != FLAC__STREAM_ENCODER_INIT_STATUS_OK) + if (FLAC__stream_encoder_init_file(m_encoder, filename.string().c_str(), nullptr, nullptr) != + FLAC__STREAM_ENCODER_INIT_STATUS_OK) { err() << "Failed to write flac file (failed to open the file)\n" << formatDebugPathInfo(filename) << std::endl; close(); diff --git a/src/SFML/Audio/SoundFileWriterFlac.hpp b/src/SFML/Audio/SoundFileWriterFlac.hpp index 34d611efb..534544863 100644 --- a/src/SFML/Audio/SoundFileWriterFlac.hpp +++ b/src/SFML/Audio/SoundFileWriterFlac.hpp @@ -29,6 +29,7 @@ // Headers //////////////////////////////////////////////////////////// #include + #include #include #include @@ -45,7 +46,6 @@ namespace priv class SoundFileWriterFlac : public SoundFileWriter { public: - //////////////////////////////////////////////////////////// /// \brief Check if this writer can handle a file on disk /// @@ -57,7 +57,6 @@ public: [[nodiscard]] static bool check(const std::filesystem::path& filename); public: - //////////////////////////////////////////////////////////// /// \brief Default constructor /// @@ -92,7 +91,6 @@ public: void write(const Int16* samples, Uint64 count) override; private: - //////////////////////////////////////////////////////////// /// \brief Close the file /// diff --git a/src/SFML/Audio/SoundFileWriterOgg.cpp b/src/SFML/Audio/SoundFileWriterOgg.cpp index 383143c43..0acadbda4 100644 --- a/src/SFML/Audio/SoundFileWriterOgg.cpp +++ b/src/SFML/Audio/SoundFileWriterOgg.cpp @@ -28,11 +28,12 @@ #include #include #include + #include -#include +#include #include #include -#include +#include namespace sf @@ -47,12 +48,7 @@ bool SoundFileWriterOgg::check(const std::filesystem::path& filename) //////////////////////////////////////////////////////////// -SoundFileWriterOgg::SoundFileWriterOgg() : -m_channelCount(0), -m_file (), -m_ogg (), -m_vorbis (), -m_state () +SoundFileWriterOgg::SoundFileWriterOgg() : m_channelCount(0), m_file(), m_ogg(), m_vorbis(), m_state() { } @@ -79,7 +75,8 @@ bool SoundFileWriterOgg::open(const std::filesystem::path& filename, unsigned in int status = vorbis_encode_init_vbr(&m_vorbis, static_cast(channelCount), static_cast(sampleRate), 0.4f); if (status < 0) { - err() << "Failed to write ogg/vorbis file (unsupported bitrate)\n" << formatDebugPathInfo(filename) << std::endl; + err() << "Failed to write ogg/vorbis file (unsupported bitrate)\n" + << formatDebugPathInfo(filename) << std::endl; close(); return false; } @@ -104,7 +101,8 @@ bool SoundFileWriterOgg::open(const std::filesystem::path& filename, unsigned in vorbis_comment_clear(&comment); if (status < 0) { - err() << "Failed to write ogg/vorbis file (cannot generate the headers)\n" << formatDebugPathInfo(filename) << std::endl; + err() << "Failed to write ogg/vorbis file (cannot generate the headers)\n" + << formatDebugPathInfo(filename) << std::endl; close(); return false; } diff --git a/src/SFML/Audio/SoundFileWriterOgg.hpp b/src/SFML/Audio/SoundFileWriterOgg.hpp index b5600f2b1..331af3fc5 100644 --- a/src/SFML/Audio/SoundFileWriterOgg.hpp +++ b/src/SFML/Audio/SoundFileWriterOgg.hpp @@ -29,7 +29,9 @@ // Headers //////////////////////////////////////////////////////////// #include + #include + #include #include @@ -45,7 +47,6 @@ namespace priv class SoundFileWriterOgg : public SoundFileWriter { public: - //////////////////////////////////////////////////////////// /// \brief Check if this writer can handle a file on disk /// @@ -57,7 +58,6 @@ public: [[nodiscard]] static bool check(const std::filesystem::path& filename); public: - //////////////////////////////////////////////////////////// /// \brief Default constructor /// @@ -92,7 +92,6 @@ public: void write(const Int16* samples, Uint64 count) override; private: - //////////////////////////////////////////////////////////// /// \brief Flush blocks produced by the ogg stream, if any /// diff --git a/src/SFML/Audio/SoundFileWriterWav.cpp b/src/SFML/Audio/SoundFileWriterWav.cpp index 2df02f767..fd64b37fd 100644 --- a/src/SFML/Audio/SoundFileWriterWav.cpp +++ b/src/SFML/Audio/SoundFileWriterWav.cpp @@ -28,48 +28,40 @@ #include #include #include -#include + #include +#include namespace { - // The following functions takes integers in host byte order - // and writes them to a stream as little endian +// The following functions takes integers in host byte order +// and writes them to a stream as little endian - void encode(std::ostream& stream, sf::Int16 value) - { - unsigned char bytes[] = - { - static_cast(value & 0xFF), - static_cast(value >> 8) - }; - stream.write(reinterpret_cast(bytes), sizeof(bytes)); - } - - void encode(std::ostream& stream, sf::Uint16 value) - { - unsigned char bytes[] = - { - static_cast(value & 0xFF), - static_cast(value >> 8) - }; - stream.write(reinterpret_cast(bytes), sizeof(bytes)); - } - - void encode(std::ostream& stream, sf::Uint32 value) - { - unsigned char bytes[] = - { - static_cast(value & 0x000000FF), - static_cast((value & 0x0000FF00) >> 8), - static_cast((value & 0x00FF0000) >> 16), - static_cast((value & 0xFF000000) >> 24), - }; - stream.write(reinterpret_cast(bytes), sizeof(bytes)); - } +void encode(std::ostream& stream, sf::Int16 value) +{ + unsigned char bytes[] = {static_cast(value & 0xFF), static_cast(value >> 8)}; + stream.write(reinterpret_cast(bytes), sizeof(bytes)); } +void encode(std::ostream& stream, sf::Uint16 value) +{ + unsigned char bytes[] = {static_cast(value & 0xFF), static_cast(value >> 8)}; + stream.write(reinterpret_cast(bytes), sizeof(bytes)); +} + +void encode(std::ostream& stream, sf::Uint32 value) +{ + unsigned char bytes[] = { + static_cast(value & 0x000000FF), + static_cast((value & 0x0000FF00) >> 8), + static_cast((value & 0x00FF0000) >> 16), + static_cast((value & 0xFF000000) >> 24), + }; + stream.write(reinterpret_cast(bytes), sizeof(bytes)); +} +} // namespace + namespace sf { namespace priv @@ -82,8 +74,7 @@ bool SoundFileWriterWav::check(const std::filesystem::path& filename) //////////////////////////////////////////////////////////// -SoundFileWriterWav::SoundFileWriterWav() : -m_file() +SoundFileWriterWav::SoundFileWriterWav() : m_file() { } diff --git a/src/SFML/Audio/SoundFileWriterWav.hpp b/src/SFML/Audio/SoundFileWriterWav.hpp index 0607e47d5..045263186 100644 --- a/src/SFML/Audio/SoundFileWriterWav.hpp +++ b/src/SFML/Audio/SoundFileWriterWav.hpp @@ -29,6 +29,7 @@ // Headers //////////////////////////////////////////////////////////// #include + #include #include @@ -44,7 +45,6 @@ namespace priv class SoundFileWriterWav : public SoundFileWriter { public: - //////////////////////////////////////////////////////////// /// \brief Check if this writer can handle a file on disk /// @@ -56,7 +56,6 @@ public: [[nodiscard]] static bool check(const std::filesystem::path& filename); public: - //////////////////////////////////////////////////////////// /// \brief Default constructor /// @@ -91,7 +90,6 @@ public: void write(const Int16* samples, Uint64 count) override; private: - //////////////////////////////////////////////////////////// /// \brief Write the header of the open file /// @@ -112,7 +110,7 @@ private: //////////////////////////////////////////////////////////// // Member data //////////////////////////////////////////////////////////// - std::ofstream m_file; //!< File stream to write to + std::ofstream m_file; //!< File stream to write to }; } // namespace priv diff --git a/src/SFML/Audio/SoundRecorder.cpp b/src/SFML/Audio/SoundRecorder.cpp index 3d433f1f1..df9c6bc49 100644 --- a/src/SFML/Audio/SoundRecorder.cpp +++ b/src/SFML/Audio/SoundRecorder.cpp @@ -25,44 +25,44 @@ //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// -#include -#include #include -#include +#include +#include #include -#include -#include +#include + #include +#include +#include #ifdef _MSC_VER - #pragma warning(disable: 4355) // 'this' used in base member initializer list +#pragma warning(disable : 4355) // 'this' used in base member initializer list #endif #if defined(__APPLE__) - #if defined(__clang__) - #pragma clang diagnostic ignored "-Wdeprecated-declarations" - #elif defined(__GNUC__) - #pragma GCC diagnostic ignored "-Wdeprecated-declarations" - #endif +#if defined(__clang__) +#pragma clang diagnostic ignored "-Wdeprecated-declarations" +#elif defined(__GNUC__) +#pragma GCC diagnostic ignored "-Wdeprecated-declarations" +#endif #endif namespace { - ALCdevice* captureDevice = nullptr; +ALCdevice* captureDevice = nullptr; } namespace sf { //////////////////////////////////////////////////////////// SoundRecorder::SoundRecorder() : -m_thread (), -m_sampleRate (0), +m_thread(), +m_sampleRate(0), m_processingInterval(milliseconds(100)), -m_isCapturing (false), -m_deviceName (getDefaultDevice()), -m_channelCount (1) +m_isCapturing(false), +m_deviceName(getDefaultDevice()), +m_channelCount(1) { - } @@ -74,7 +74,9 @@ SoundRecorder::~SoundRecorder() // destructor of the derived class, which makes sure that the recording // thread finishes before the derived object is destroyed. Otherwise a // "pure virtual method called" exception is triggered. - assert(!m_isCapturing && "You must call stop() in the destructor of your derived class, so that the recording thread finishes before your object is destroyed."); + assert(!m_isCapturing && + "You must call stop() in the destructor of your derived class, so that the recording thread finishes before " + "your object is destroyed."); } @@ -84,7 +86,9 @@ bool SoundRecorder::start(unsigned int sampleRate) // Check if the device can do audio capture if (!isAvailable()) { - err() << "Failed to start capture: your system cannot capture audio data (call SoundRecorder::isAvailable to check it)" << std::endl; + err() << "Failed to start capture: your system cannot capture audio data (call SoundRecorder::isAvailable to " + "check it)" + << std::endl; return false; } @@ -232,7 +236,8 @@ void SoundRecorder::setChannelCount(unsigned int channelCount) if (channelCount < 1 || channelCount > 2) { - err() << "Unsupported channel count: " << channelCount << " Currently only mono (1) and stereo (2) recording is supported." << std::endl; + err() << "Unsupported channel count: " << channelCount + << " Currently only mono (1) and stereo (2) recording is supported." << std::endl; return; } diff --git a/src/SFML/Audio/SoundSource.cpp b/src/SFML/Audio/SoundSource.cpp index b8283b106..02d31c80c 100644 --- a/src/SFML/Audio/SoundSource.cpp +++ b/src/SFML/Audio/SoundSource.cpp @@ -25,15 +25,15 @@ //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// -#include #include +#include #if defined(__APPLE__) - #if defined(__clang__) - #pragma clang diagnostic ignored "-Wdeprecated-declarations" - #elif defined(__GNUC__) - #pragma GCC diagnostic ignored "-Wdeprecated-declarations" - #endif +#if defined(__clang__) +#pragma clang diagnostic ignored "-Wdeprecated-declarations" +#elif defined(__GNUC__) +#pragma GCC diagnostic ignored "-Wdeprecated-declarations" +#endif #endif namespace sf @@ -172,7 +172,7 @@ float SoundSource::getAttenuation() const //////////////////////////////////////////////////////////// -SoundSource& SoundSource::operator =(const SoundSource& right) +SoundSource& SoundSource::operator=(const SoundSource& right) { // Leave m_source untouched -- it's not necessary to destroy and // recreate the OpenAL sound source, hence no copy-and-swap idiom @@ -198,9 +198,12 @@ SoundSource::Status SoundSource::getStatus() const switch (status) { case AL_INITIAL: - case AL_STOPPED: return Stopped; - case AL_PAUSED: return Paused; - case AL_PLAYING: return Playing; + case AL_STOPPED: + return Stopped; + case AL_PAUSED: + return Paused; + case AL_PLAYING: + return Playing; } return Stopped; diff --git a/src/SFML/Audio/SoundStream.cpp b/src/SFML/Audio/SoundStream.cpp index e1c913ebd..6e08d78ef 100644 --- a/src/SFML/Audio/SoundStream.cpp +++ b/src/SFML/Audio/SoundStream.cpp @@ -25,45 +25,45 @@ //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// -#include -#include #include -#include +#include +#include #include +#include + +#include #include #include -#include #ifdef _MSC_VER - #pragma warning(disable: 4355) // 'this' used in base member initializer list +#pragma warning(disable : 4355) // 'this' used in base member initializer list #endif #if defined(__APPLE__) - #if defined(__clang__) - #pragma clang diagnostic ignored "-Wdeprecated-declarations" - #elif defined(__GNUC__) - #pragma GCC diagnostic ignored "-Wdeprecated-declarations" - #endif +#if defined(__clang__) +#pragma clang diagnostic ignored "-Wdeprecated-declarations" +#elif defined(__GNUC__) +#pragma GCC diagnostic ignored "-Wdeprecated-declarations" +#endif #endif namespace sf { //////////////////////////////////////////////////////////// SoundStream::SoundStream() : -m_thread (), -m_threadMutex (), +m_thread(), +m_threadMutex(), m_threadStartState(Stopped), -m_isStreaming (false), -m_buffers (), -m_channelCount (0), -m_sampleRate (0), -m_format (0), -m_loop (false), +m_isStreaming(false), +m_buffers(), +m_channelCount(0), +m_sampleRate(0), +m_format(0), +m_loop(false), m_samplesProcessed(0), -m_bufferSeeks (), +m_bufferSeeks(), m_processingInterval(milliseconds(10)) { - } @@ -80,8 +80,8 @@ SoundStream::~SoundStream() //////////////////////////////////////////////////////////// void SoundStream::initialize(unsigned int channelCount, unsigned int sampleRate) { - m_channelCount = channelCount; - m_sampleRate = sampleRate; + m_channelCount = channelCount; + m_sampleRate = sampleRate; m_samplesProcessed = 0; { @@ -108,17 +108,18 @@ void SoundStream::play() // Check if the sound parameters have been set if (m_format == 0) { - err() << "Failed to play audio stream: sound parameters have not been initialized (call initialize() first)" << std::endl; + err() << "Failed to play audio stream: sound parameters have not been initialized (call initialize() first)" + << std::endl; return; } - bool isStreaming = false; + bool isStreaming = false; Status threadStartState = Stopped; { std::scoped_lock lock(m_threadMutex); - isStreaming = m_isStreaming; + isStreaming = m_isStreaming; threadStartState = m_threadStartState; } @@ -238,7 +239,8 @@ Time SoundStream::getPlayingOffset() const ALfloat secs = 0.f; alCheck(alGetSourcef(m_source, AL_SEC_OFFSET, &secs)); - return seconds(secs + static_cast(m_samplesProcessed) / static_cast(m_sampleRate) / static_cast(m_channelCount)); + return seconds(secs + static_cast(m_samplesProcessed) / static_cast(m_sampleRate) / + static_cast(m_channelCount)); } else { @@ -356,7 +358,7 @@ void SoundStream::streamData() if (m_bufferSeeks[bufferNum] != NoLoop) { // This was the last buffer before EOF or Loop End: reset the sample count - m_samplesProcessed = static_cast(m_bufferSeeks[bufferNum]); + m_samplesProcessed = static_cast(m_bufferSeeks[bufferNum]); m_bufferSeeks[bufferNum] = NoLoop; } else @@ -374,7 +376,7 @@ void SoundStream::streamData() // Abort streaming (exit main loop) std::scoped_lock lock(m_threadMutex); m_isStreaming = false; - requestStop = true; + requestStop = true; break; } else @@ -451,7 +453,7 @@ bool SoundStream::fillAndPushBuffer(unsigned int bufferNum, bool immediateLoop) if (immediateLoop && (m_bufferSeeks[bufferNum] != NoLoop)) { // We just tried to begin preloading at EOF or Loop End: reset the sample count - m_samplesProcessed = static_cast(m_bufferSeeks[bufferNum]); + m_samplesProcessed = static_cast(m_bufferSeeks[bufferNum]); m_bufferSeeks[bufferNum] = NoLoop; } @@ -516,7 +518,7 @@ void SoundStream::launchStreamingThread(Status threadStartState) { { std::scoped_lock lock(m_threadMutex); - m_isStreaming = true; + m_isStreaming = true; m_threadStartState = threadStartState; } diff --git a/src/SFML/Graphics/BlendMode.cpp b/src/SFML/Graphics/BlendMode.cpp index 713c66543..4872e319b 100644 --- a/src/SFML/Graphics/BlendMode.cpp +++ b/src/SFML/Graphics/BlendMode.cpp @@ -33,10 +33,13 @@ namespace sf //////////////////////////////////////////////////////////// // Commonly used blending modes //////////////////////////////////////////////////////////// -const BlendMode BlendAlpha(BlendMode::SrcAlpha, BlendMode::OneMinusSrcAlpha, BlendMode::Add, - BlendMode::One, BlendMode::OneMinusSrcAlpha, BlendMode::Add); -const BlendMode BlendAdd(BlendMode::SrcAlpha, BlendMode::One, BlendMode::Add, - BlendMode::One, BlendMode::One, BlendMode::Add); +const BlendMode BlendAlpha(BlendMode::SrcAlpha, + BlendMode::OneMinusSrcAlpha, + BlendMode::Add, + BlendMode::One, + BlendMode::OneMinusSrcAlpha, + BlendMode::Add); +const BlendMode BlendAdd(BlendMode::SrcAlpha, BlendMode::One, BlendMode::Add, BlendMode::One, BlendMode::One, BlendMode::Add); const BlendMode BlendMultiply(BlendMode::DstColor, BlendMode::Zero, BlendMode::Add); const BlendMode BlendMin(BlendMode::One, BlendMode::One, BlendMode::Min); const BlendMode BlendMax(BlendMode::One, BlendMode::One, BlendMode::Max); @@ -47,12 +50,11 @@ const BlendMode BlendNone(BlendMode::One, BlendMode::Zero, BlendMode::Add); BlendMode::BlendMode() : colorSrcFactor(BlendMode::SrcAlpha), colorDstFactor(BlendMode::OneMinusSrcAlpha), -colorEquation (BlendMode::Add), +colorEquation(BlendMode::Add), alphaSrcFactor(BlendMode::One), alphaDstFactor(BlendMode::OneMinusSrcAlpha), -alphaEquation (BlendMode::Add) +alphaEquation(BlendMode::Add) { - } @@ -60,44 +62,42 @@ alphaEquation (BlendMode::Add) BlendMode::BlendMode(Factor sourceFactor, Factor destinationFactor, Equation blendEquation) : colorSrcFactor(sourceFactor), colorDstFactor(destinationFactor), -colorEquation (blendEquation), +colorEquation(blendEquation), alphaSrcFactor(sourceFactor), alphaDstFactor(destinationFactor), -alphaEquation (blendEquation) +alphaEquation(blendEquation) { - } //////////////////////////////////////////////////////////// -BlendMode::BlendMode(Factor colorSourceFactor, Factor colorDestinationFactor, - Equation colorBlendEquation, Factor alphaSourceFactor, - Factor alphaDestinationFactor, Equation alphaBlendEquation) : +BlendMode::BlendMode(Factor colorSourceFactor, + Factor colorDestinationFactor, + Equation colorBlendEquation, + Factor alphaSourceFactor, + Factor alphaDestinationFactor, + Equation alphaBlendEquation) : colorSrcFactor(colorSourceFactor), colorDstFactor(colorDestinationFactor), -colorEquation (colorBlendEquation), +colorEquation(colorBlendEquation), alphaSrcFactor(alphaSourceFactor), alphaDstFactor(alphaDestinationFactor), -alphaEquation (alphaBlendEquation) +alphaEquation(alphaBlendEquation) { - } //////////////////////////////////////////////////////////// -bool operator ==(const BlendMode& left, const BlendMode& right) +bool operator==(const BlendMode& left, const BlendMode& right) { - return (left.colorSrcFactor == right.colorSrcFactor) && - (left.colorDstFactor == right.colorDstFactor) && - (left.colorEquation == right.colorEquation) && - (left.alphaSrcFactor == right.alphaSrcFactor) && - (left.alphaDstFactor == right.alphaDstFactor) && - (left.alphaEquation == right.alphaEquation); + return (left.colorSrcFactor == right.colorSrcFactor) && (left.colorDstFactor == right.colorDstFactor) && + (left.colorEquation == right.colorEquation) && (left.alphaSrcFactor == right.alphaSrcFactor) && + (left.alphaDstFactor == right.alphaDstFactor) && (left.alphaEquation == right.alphaEquation); } //////////////////////////////////////////////////////////// -bool operator !=(const BlendMode& left, const BlendMode& right) +bool operator!=(const BlendMode& left, const BlendMode& right) { return !(left == right); } diff --git a/src/SFML/Graphics/CircleShape.cpp b/src/SFML/Graphics/CircleShape.cpp index d2ef144e3..c67bd1ef0 100644 --- a/src/SFML/Graphics/CircleShape.cpp +++ b/src/SFML/Graphics/CircleShape.cpp @@ -26,15 +26,14 @@ // Headers //////////////////////////////////////////////////////////// #include + #include namespace sf { //////////////////////////////////////////////////////////// -CircleShape::CircleShape(float radius, std::size_t pointCount) : -m_radius (radius), -m_pointCount(pointCount) +CircleShape::CircleShape(float radius, std::size_t pointCount) : m_radius(radius), m_pointCount(pointCount) { update(); } diff --git a/src/SFML/Graphics/Font.cpp b/src/SFML/Graphics/Font.cpp index ffb640c8c..8ccdd5c37 100644 --- a/src/SFML/Graphics/Font.cpp +++ b/src/SFML/Graphics/Font.cpp @@ -29,60 +29,62 @@ #include #include #ifdef SFML_SYSTEM_ANDROID - #include +#include #endif -#include #include +#include #include + #include #include FT_FREETYPE_H #include FT_GLYPH_H #include FT_OUTLINE_H #include FT_BITMAP_H #include FT_STROKER_H -#include -#include +#include #include #include -#include +#include +#include namespace { - // FreeType callbacks that operate on a sf::InputStream - unsigned long read(FT_Stream rec, unsigned long offset, unsigned char* buffer, unsigned long count) +// FreeType callbacks that operate on a sf::InputStream +unsigned long read(FT_Stream rec, unsigned long offset, unsigned char* buffer, unsigned long count) +{ + auto convertedOffset = static_cast(offset); + auto* stream = static_cast(rec->descriptor.pointer); + if (stream->seek(convertedOffset) == convertedOffset) { - auto convertedOffset = static_cast(offset); - auto* stream = static_cast(rec->descriptor.pointer); - if (stream->seek(convertedOffset) == convertedOffset) - { - if (count > 0) - return static_cast(stream->read(reinterpret_cast(buffer), static_cast(count))); - else - return 0; - } + if (count > 0) + return static_cast(stream->read(reinterpret_cast(buffer), static_cast(count))); else - return count > 0 ? 0 : 1; // error code is 0 if we're reading, or nonzero if we're seeking - } - void close(FT_Stream) - { - } - - // Helper to intepret memory as a specific type - template - inline T reinterpret(const U& input) - { - T output; - std::memcpy(&output, &input, sizeof(U)); - return output; - } - - // Combine outline thickness, boldness and font glyph index into a single 64-bit key - sf::Uint64 combine(float outlineThickness, bool bold, sf::Uint32 index) - { - return (static_cast(reinterpret(outlineThickness)) << 32) | (static_cast(bold) << 31) | index; + return 0; } + else + return count > 0 ? 0 : 1; // error code is 0 if we're reading, or nonzero if we're seeking } +void close(FT_Stream) +{ +} + +// Helper to intepret memory as a specific type +template +inline T reinterpret(const U& input) +{ + T output; + std::memcpy(&output, &input, sizeof(U)); + return output; +} + +// Combine outline thickness, boldness and font glyph index into a single 64-bit key +sf::Uint64 combine(float outlineThickness, bool bold, sf::Uint32 index) +{ + return (static_cast(reinterpret(outlineThickness)) << 32) | + (static_cast(bold) << 31) | index; +} +} // namespace namespace sf @@ -94,38 +96,42 @@ private: // Default constructible deleter functor struct Deleter { - void operator()(FT_Library theLibrary) { FT_Done_FreeType(theLibrary); } - void operator()(FT_Face theFace) { FT_Done_Face(theFace); } - void operator()(FT_Stroker theStroker) { FT_Stroker_Done(theStroker); } + void operator()(FT_Library theLibrary) + { + FT_Done_FreeType(theLibrary); + } + void operator()(FT_Face theFace) + { + FT_Done_Face(theFace); + } + void operator()(FT_Stroker theStroker) + { + FT_Stroker_Done(theStroker); + } }; public: std::unique_ptr, Deleter> library; //< Pointer to the internal library interface std::unique_ptr streamRec; //< Pointer to the stream rec instance - std::unique_ptr, Deleter> face; //< Pointer to the internal font face + std::unique_ptr, Deleter> face; //< Pointer to the internal font face std::unique_ptr, Deleter> stroker; //< Pointer to the stroker }; //////////////////////////////////////////////////////////// -Font::Font() : -m_fontHandles(), -m_isSmooth (true), -m_info () +Font::Font() : m_fontHandles(), m_isSmooth(true), m_info() { - } //////////////////////////////////////////////////////////// Font::Font(const Font& copy) : m_fontHandles(copy.m_fontHandles), -m_isSmooth (copy.m_isSmooth), -m_info (copy.m_info), -m_pages (copy.m_pages), +m_isSmooth(copy.m_isSmooth), +m_info(copy.m_info), +m_pages(copy.m_pages), m_pixelBuffer(copy.m_pixelBuffer) { - } @@ -144,7 +150,7 @@ Font& Font::operator=(Font&&) noexcept = default; //////////////////////////////////////////////////////////// bool Font::loadFromFile(const std::filesystem::path& filename) { - #ifndef SFML_SYSTEM_ANDROID +#ifndef SFML_SYSTEM_ANDROID // Cleanup the previous resources cleanup(); @@ -183,7 +189,8 @@ bool Font::loadFromFile(const std::filesystem::path& filename) // Select the unicode character map if (FT_Select_Charmap(face, FT_ENCODING_UNICODE) != 0) { - err() << "Failed to load font (failed to set the Unicode character set)\n" << formatDebugPathInfo(filename) << std::endl; + err() << "Failed to load font (failed to set the Unicode character set)\n" + << formatDebugPathInfo(filename) << std::endl; return false; } @@ -195,12 +202,12 @@ bool Font::loadFromFile(const std::filesystem::path& filename) return true; - #else +#else m_stream = std::make_unique(filename); return loadFromStream(*m_stream); - #endif +#endif } @@ -349,7 +356,9 @@ const Glyph& Font::getGlyph(Uint32 codePoint, unsigned int characterSize, bool b GlyphTable& glyphs = loadPage(characterSize).glyphs; // Build the key by combining the glyph index (based on code point), bold flag, and outline thickness - Uint64 key = combine(outlineThickness, bold, FT_Get_Char_Index(m_fontHandles ? m_fontHandles->face.get() : nullptr, codePoint)); + Uint64 key = combine(outlineThickness, + bold, + FT_Get_Char_Index(m_fontHandles ? m_fontHandles->face.get() : nullptr, codePoint)); // Search the glyph into the cache if (auto it = glyphs.find(key); it != glyphs.end()) @@ -389,7 +398,7 @@ float Font::getKerning(Uint32 first, Uint32 second, unsigned int characterSize, FT_UInt index2 = FT_Get_Char_Index(face, second); // Retrieve position compensation deltas generated by FT_LOAD_FORCE_AUTOHINT flag - auto firstRsbDelta = static_cast(getGlyph(first, characterSize, bold).rsbDelta); + auto firstRsbDelta = static_cast(getGlyph(first, characterSize, bold).rsbDelta); auto secondLsbDelta = static_cast(getGlyph(second, characterSize, bold).lsbDelta); // Get the kerning vector if present @@ -404,7 +413,8 @@ float Font::getKerning(Uint32 first, Uint32 second, unsigned int characterSize, // Combine kerning with compensation deltas and return the X advance // Flooring is required as we use FT_KERNING_UNFITTED flag which is not quantized in 64 based grid - return std::floor((secondLsbDelta - firstRsbDelta + static_cast(kerning.x) + 32) / static_cast(1 << 6)); + return std::floor( + (secondLsbDelta - firstRsbDelta + static_cast(kerning.x) + 32) / static_cast(1 << 6)); } else { @@ -441,7 +451,8 @@ float Font::getUnderlinePosition(unsigned int characterSize) const if (!FT_IS_SCALABLE(face)) return static_cast(characterSize) / 10.f; - return -static_cast(FT_MulFix(face->underline_position, face->size->metrics.y_scale)) / static_cast(1 << 6); + return -static_cast(FT_MulFix(face->underline_position, face->size->metrics.y_scale)) / + static_cast(1 << 6); } else { @@ -461,7 +472,8 @@ float Font::getUnderlineThickness(unsigned int characterSize) const if (!FT_IS_SCALABLE(face)) return static_cast(characterSize) / 14.f; - return static_cast(FT_MulFix(face->underline_thickness, face->size->metrics.y_scale)) / static_cast(1 << 6); + return static_cast(FT_MulFix(face->underline_thickness, face->size->metrics.y_scale)) / + static_cast(1 << 6); } else { @@ -498,19 +510,19 @@ bool Font::isSmooth() const //////////////////////////////////////////////////////////// -Font& Font::operator =(const Font& right) +Font& Font::operator=(const Font& right) { Font temp(right); std::swap(m_fontHandles, temp.m_fontHandles); - std::swap(m_isSmooth, temp.m_isSmooth); - std::swap(m_info, temp.m_info); - std::swap(m_pages, temp.m_pages); + std::swap(m_isSmooth, temp.m_isSmooth); + std::swap(m_info, temp.m_info); + std::swap(m_pages, temp.m_pages); std::swap(m_pixelBuffer, temp.m_pixelBuffer); - #ifdef SFML_SYSTEM_ANDROID - std::swap(m_stream, temp.m_stream); - #endif +#ifdef SFML_SYSTEM_ANDROID + std::swap(m_stream, temp.m_stream); +#endif return *this; } @@ -567,8 +579,8 @@ Glyph Font::loadGlyph(Uint32 codePoint, unsigned int characterSize, bool bold, f return glyph; // Apply bold and outline (there is no fallback for outline) if necessary -- first technique using outline (highest quality) - FT_Pos weight = 1 << 6; - bool outline = (glyphDesc->format == FT_GLYPH_FORMAT_OUTLINE); + FT_Pos weight = 1 << 6; + bool outline = (glyphDesc->format == FT_GLYPH_FORMAT_OUTLINE); if (outline) { if (bold) @@ -581,7 +593,11 @@ Glyph Font::loadGlyph(Uint32 codePoint, unsigned int characterSize, bool bold, f { auto stroker = m_fontHandles->stroker.get(); - FT_Stroker_Set(stroker, static_cast(outlineThickness * static_cast(1 << 6)), FT_STROKER_LINECAP_ROUND, FT_STROKER_LINEJOIN_ROUND, 0); + FT_Stroker_Set(stroker, + static_cast(outlineThickness * static_cast(1 << 6)), + FT_STROKER_LINECAP_ROUND, + FT_STROKER_LINEJOIN_ROUND, + 0); FT_Glyph_Stroke(&glyphDesc, stroker, true); } } @@ -590,8 +606,8 @@ Glyph Font::loadGlyph(Uint32 codePoint, unsigned int characterSize, bool bold, f // Warning! After this line, do not read any data from glyphDesc directly, use // bitmapGlyph.root to access the FT_Glyph data. FT_Glyph_To_Bitmap(&glyphDesc, FT_RENDER_MODE_NORMAL, nullptr, 1); - auto bitmapGlyph = reinterpret_cast(glyphDesc); - FT_Bitmap& bitmap = bitmapGlyph->bitmap; + auto bitmapGlyph = reinterpret_cast(glyphDesc); + FT_Bitmap& bitmap = bitmapGlyph->bitmap; // Apply bold if necessary -- fallback technique using bitmap (lower quality) if (!outline) @@ -631,22 +647,22 @@ Glyph Font::loadGlyph(Uint32 codePoint, unsigned int characterSize, bool bold, f // Make sure the texture data is positioned in the center // of the allocated texture rectangle - glyph.textureRect.left += static_cast(padding); - glyph.textureRect.top += static_cast(padding); - glyph.textureRect.width -= static_cast(2 * padding); + glyph.textureRect.left += static_cast(padding); + glyph.textureRect.top += static_cast(padding); + glyph.textureRect.width -= static_cast(2 * padding); glyph.textureRect.height -= static_cast(2 * padding); // Compute the glyph's bounding box - glyph.bounds.left = static_cast( bitmapGlyph->left); + glyph.bounds.left = static_cast(bitmapGlyph->left); glyph.bounds.top = static_cast(-bitmapGlyph->top); - glyph.bounds.width = static_cast( bitmap.width); - glyph.bounds.height = static_cast( bitmap.rows); + glyph.bounds.width = static_cast(bitmap.width); + glyph.bounds.height = static_cast(bitmap.rows); // Resize the pixel buffer to the new size and fill it with transparent white pixels m_pixelBuffer.resize(static_cast(width) * static_cast(height) * 4); Uint8* current = m_pixelBuffer.data(); - Uint8* end = current + width * height * 4; + Uint8* end = current + width * height * 4; while (current != end) { @@ -666,7 +682,7 @@ Glyph Font::loadGlyph(Uint32 codePoint, unsigned int characterSize, bool bold, f for (unsigned int x = padding; x < width - padding; ++x) { // The color channels remain white, just fill the alpha channel - std::size_t index = x + y * width; + std::size_t index = x + y * width; m_pixelBuffer[index * 4 + 3] = ((pixels[(x - padding) / 8]) & (1 << (7 - ((x - padding) % 8)))) ? 255 : 0; } pixels += bitmap.pitch; @@ -680,7 +696,7 @@ Glyph Font::loadGlyph(Uint32 codePoint, unsigned int characterSize, bool bold, f for (unsigned int x = padding; x < width - padding; ++x) { // The color channels remain white, just fill the alpha channel - std::size_t index = x + y * width; + std::size_t index = x + y * width; m_pixelBuffer[index * 4 + 3] = pixels[x - padding]; } pixels += bitmap.pitch; @@ -707,7 +723,7 @@ Glyph Font::loadGlyph(Uint32 codePoint, unsigned int characterSize, bool bold, f IntRect Font::findGlyphRect(Page& page, const Vector2u& size) const { // Find the line that fits well the glyph - Row* row = nullptr; + Row* row = nullptr; float bestRatio = 0; for (auto it = page.rows.begin(); it != page.rows.end() && !row; ++it) { @@ -726,7 +742,7 @@ IntRect Font::findGlyphRect(Page& page, const Vector2u& size) const continue; // The current row passed all the tests: we can select it - row = &*it; + row = &*it; bestRatio = ratio; } @@ -737,7 +753,7 @@ IntRect Font::findGlyphRect(Page& page, const Vector2u& size) const while ((page.nextRow + rowHeight >= page.texture.getSize().y) || (size.x >= page.texture.getSize().x)) { // Not enough space: resize the texture if possible - Vector2u textureSize = page.texture.getSize(); + Vector2u textureSize = page.texture.getSize(); if ((textureSize.x * 2 <= Texture::getMaximumSize()) && (textureSize.y * 2 <= Texture::getMaximumSize())) { // Make the texture 2 times bigger @@ -755,7 +771,8 @@ IntRect Font::findGlyphRect(Page& page, const Vector2u& size) const else { // Oops, we've reached the maximum texture size... - err() << "Failed to add a new character to the font: the maximum texture size has been reached" << std::endl; + err() << "Failed to add a new character to the font: the maximum texture size has been reached" + << std::endl; return IntRect({0, 0}, {2, 2}); } } @@ -783,7 +800,7 @@ bool Font::setCurrentSize(unsigned int characterSize) const // only when necessary to avoid killing performances // m_fontHandles and m_fontHandles->face are checked to be non-null before calling this method - auto face = m_fontHandles->face.get(); + auto face = m_fontHandles->face.get(); FT_UShort currentSize = face->size->metrics.x_ppem; if (currentSize != characterSize) @@ -819,8 +836,7 @@ bool Font::setCurrentSize(unsigned int characterSize) const //////////////////////////////////////////////////////////// -Font::Page::Page(bool smooth) : -nextRow(3) +Font::Page::Page(bool smooth) : nextRow(3) { // Make sure that the texture is initialized by default sf::Image image; diff --git a/src/SFML/Graphics/GLCheck.cpp b/src/SFML/Graphics/GLCheck.cpp index 8e670a5ef..364f8eb0f 100644 --- a/src/SFML/Graphics/GLCheck.cpp +++ b/src/SFML/Graphics/GLCheck.cpp @@ -27,8 +27,9 @@ //////////////////////////////////////////////////////////// #include #include -#include + #include +#include namespace sf @@ -43,67 +44,65 @@ void glCheckError(const std::filesystem::path& file, unsigned int line, const ch if (errorCode != GL_NO_ERROR) { - std::string error = "Unknown error"; - std::string description = "No description"; + std::string error = "Unknown error"; + std::string description = "No description"; // Decode the error code switch (errorCode) { case GL_INVALID_ENUM: { - error = "GL_INVALID_ENUM"; + error = "GL_INVALID_ENUM"; description = "An unacceptable value has been specified for an enumerated argument."; break; } case GL_INVALID_VALUE: { - error = "GL_INVALID_VALUE"; + error = "GL_INVALID_VALUE"; description = "A numeric argument is out of range."; break; } case GL_INVALID_OPERATION: { - error = "GL_INVALID_OPERATION"; + error = "GL_INVALID_OPERATION"; description = "The specified operation is not allowed in the current state."; break; } case GL_STACK_OVERFLOW: { - error = "GL_STACK_OVERFLOW"; + error = "GL_STACK_OVERFLOW"; description = "This command would cause a stack overflow."; break; } case GL_STACK_UNDERFLOW: { - error = "GL_STACK_UNDERFLOW"; + error = "GL_STACK_UNDERFLOW"; description = "This command would cause a stack underflow."; break; } case GL_OUT_OF_MEMORY: { - error = "GL_OUT_OF_MEMORY"; + error = "GL_OUT_OF_MEMORY"; description = "There is not enough memory left to execute the command."; break; } case GLEXT_GL_INVALID_FRAMEBUFFER_OPERATION: { - error = "GL_INVALID_FRAMEBUFFER_OPERATION"; + error = "GL_INVALID_FRAMEBUFFER_OPERATION"; description = "The object bound to FRAMEBUFFER_BINDING is not \"framebuffer complete\"."; break; } } // Log the error - err() << "An internal OpenGL call failed in " - << file.filename() << "(" << line << ")." - << "\nExpression:\n " << expression - << "\nError description:\n " << error << "\n " << description << '\n' + err() << "An internal OpenGL call failed in " << file.filename() << "(" << line << ")." + << "\nExpression:\n " << expression << "\nError description:\n " << error << "\n " << description << '\n' << std::endl; } } diff --git a/src/SFML/Graphics/GLCheck.hpp b/src/SFML/Graphics/GLCheck.hpp index accbc8cf5..0a87f0da9 100644 --- a/src/SFML/Graphics/GLCheck.hpp +++ b/src/SFML/Graphics/GLCheck.hpp @@ -29,7 +29,9 @@ // Headers //////////////////////////////////////////////////////////// #include + #include + #include @@ -42,14 +44,19 @@ namespace priv //////////////////////////////////////////////////////////// #ifdef SFML_DEBUG - // In debug mode, perform a test on every OpenGL call - // The do-while loop is needed so that glCheck can be used as a single statement in if/else branches - #define glCheck(expr) do { expr; sf::priv::glCheckError(__FILE__, __LINE__, #expr); } while (false) +// In debug mode, perform a test on every OpenGL call +// The do-while loop is needed so that glCheck can be used as a single statement in if/else branches +#define glCheck(expr) \ + do \ + { \ + expr; \ + sf::priv::glCheckError(__FILE__, __LINE__, #expr); \ + } while (false) #else - // Else, we don't add any overhead - #define glCheck(expr) (expr) +// Else, we don't add any overhead +#define glCheck(expr) (expr) #endif diff --git a/src/SFML/Graphics/GLExtensions.cpp b/src/SFML/Graphics/GLExtensions.cpp index db8ce32c2..3ffb6156c 100644 --- a/src/SFML/Graphics/GLExtensions.cpp +++ b/src/SFML/Graphics/GLExtensions.cpp @@ -26,8 +26,8 @@ // Headers //////////////////////////////////////////////////////////// #include -#include #include +#include // We check for this definition in order to avoid multiple definitions of GLAD // entities during unity builds of SFML. @@ -40,11 +40,11 @@ #include #if !defined(GL_MAJOR_VERSION) - #define GL_MAJOR_VERSION 0x821B +#define GL_MAJOR_VERSION 0x821B #endif #if !defined(GL_MINOR_VERSION) - #define GL_MINOR_VERSION 0x821C +#define GL_MINOR_VERSION 0x821C #endif diff --git a/src/SFML/Graphics/GLExtensions.hpp b/src/SFML/Graphics/GLExtensions.hpp index 22930eb92..5d865c123 100644 --- a/src/SFML/Graphics/GLExtensions.hpp +++ b/src/SFML/Graphics/GLExtensions.hpp @@ -29,307 +29,311 @@ // Headers //////////////////////////////////////////////////////////// #include + #include #ifdef SFML_OPENGL_ES - // SFML requires at a bare minimum OpenGL ES 1.0 capability - // Some extensions only incorporated by 2.0 are also required - // OpenGL ES 1.0 is defined relative to OpenGL 1.3 - // OpenGL ES 1.1 is defined relative to OpenGL 1.5 - // OpenGL ES 2.0 is defined relative to OpenGL 2.0 - // All functionality beyond that is optional - // and has to be checked for prior to use +// SFML requires at a bare minimum OpenGL ES 1.0 capability +// Some extensions only incorporated by 2.0 are also required +// OpenGL ES 1.0 is defined relative to OpenGL 1.3 +// OpenGL ES 1.1 is defined relative to OpenGL 1.5 +// OpenGL ES 2.0 is defined relative to OpenGL 2.0 +// All functionality beyond that is optional +// and has to be checked for prior to use - // Core since 1.0 - #define GLEXT_multitexture true - #define GLEXT_texture_edge_clamp true - #define GLEXT_EXT_texture_edge_clamp true - #define GLEXT_glClientActiveTexture glClientActiveTexture - #define GLEXT_glActiveTexture glActiveTexture - #define GLEXT_GL_TEXTURE0 GL_TEXTURE0 - #define GLEXT_GL_CLAMP GL_CLAMP_TO_EDGE - #define GLEXT_GL_CLAMP_TO_EDGE GL_CLAMP_TO_EDGE +// Core since 1.0 +#define GLEXT_multitexture true +#define GLEXT_texture_edge_clamp true +#define GLEXT_EXT_texture_edge_clamp true +#define GLEXT_glClientActiveTexture glClientActiveTexture +#define GLEXT_glActiveTexture glActiveTexture +#define GLEXT_GL_TEXTURE0 GL_TEXTURE0 +#define GLEXT_GL_CLAMP GL_CLAMP_TO_EDGE +#define GLEXT_GL_CLAMP_TO_EDGE GL_CLAMP_TO_EDGE - // Core since 1.1 - // 1.1 does not support GL_STREAM_DRAW so we just define it to GL_DYNAMIC_DRAW - #define GLEXT_vertex_buffer_object true - #define GLEXT_GL_ARRAY_BUFFER GL_ARRAY_BUFFER - #define GLEXT_GL_DYNAMIC_DRAW GL_DYNAMIC_DRAW - #define GLEXT_GL_STATIC_DRAW GL_STATIC_DRAW - #define GLEXT_GL_STREAM_DRAW GL_DYNAMIC_DRAW - #define GLEXT_glBindBuffer glBindBuffer - #define GLEXT_glBufferData glBufferData - #define GLEXT_glBufferSubData glBufferSubData - #define GLEXT_glDeleteBuffers glDeleteBuffers - #define GLEXT_glGenBuffers glGenBuffers +// Core since 1.1 +// 1.1 does not support GL_STREAM_DRAW so we just define it to GL_DYNAMIC_DRAW +#define GLEXT_vertex_buffer_object true +#define GLEXT_GL_ARRAY_BUFFER GL_ARRAY_BUFFER +#define GLEXT_GL_DYNAMIC_DRAW GL_DYNAMIC_DRAW +#define GLEXT_GL_STATIC_DRAW GL_STATIC_DRAW +#define GLEXT_GL_STREAM_DRAW GL_DYNAMIC_DRAW +#define GLEXT_glBindBuffer glBindBuffer +#define GLEXT_glBufferData glBufferData +#define GLEXT_glBufferSubData glBufferSubData +#define GLEXT_glDeleteBuffers glDeleteBuffers +#define GLEXT_glGenBuffers glGenBuffers - // The following extensions are listed chronologically - // Extension macro first, followed by tokens then - // functions according to the corresponding specification +// The following extensions are listed chronologically +// Extension macro first, followed by tokens then +// functions according to the corresponding specification - // The following extensions are required. +// The following extensions are required. - // Core since 2.0 - OES_blend_subtract - #define GLEXT_blend_subtract SF_GLAD_GL_OES_blend_subtract - #define GLEXT_glBlendEquation glBlendEquationOES - #define GLEXT_GL_FUNC_ADD GL_FUNC_ADD_OES - #define GLEXT_GL_FUNC_SUBTRACT GL_FUNC_SUBTRACT_OES - #define GLEXT_GL_FUNC_REVERSE_SUBTRACT GL_FUNC_REVERSE_SUBTRACT_OES +// Core since 2.0 - OES_blend_subtract +#define GLEXT_blend_subtract SF_GLAD_GL_OES_blend_subtract +#define GLEXT_glBlendEquation glBlendEquationOES +#define GLEXT_GL_FUNC_ADD GL_FUNC_ADD_OES +#define GLEXT_GL_FUNC_SUBTRACT GL_FUNC_SUBTRACT_OES +#define GLEXT_GL_FUNC_REVERSE_SUBTRACT GL_FUNC_REVERSE_SUBTRACT_OES - // The following extensions are optional. +// The following extensions are optional. - // Core since 2.0 - OES_blend_func_separate - #define GLEXT_blend_func_separate SF_GLAD_GL_OES_blend_func_separate - #define GLEXT_glBlendFuncSeparate glBlendFuncSeparateOES +// Core since 2.0 - OES_blend_func_separate +#define GLEXT_blend_func_separate SF_GLAD_GL_OES_blend_func_separate +#define GLEXT_glBlendFuncSeparate glBlendFuncSeparateOES - // Core since 2.0 - OES_blend_equation_separate - #define GLEXT_blend_equation_separate SF_GLAD_GL_OES_blend_equation_separate - #define GLEXT_glBlendEquationSeparate glBlendEquationSeparateOES +// Core since 2.0 - OES_blend_equation_separate +#define GLEXT_blend_equation_separate SF_GLAD_GL_OES_blend_equation_separate +#define GLEXT_glBlendEquationSeparate glBlendEquationSeparateOES - // Core since 2.0 - OES_texture_npot - #define GLEXT_texture_non_power_of_two false +// Core since 2.0 - OES_texture_npot +#define GLEXT_texture_non_power_of_two false - // Core since 2.0 - OES_framebuffer_object - #define GLEXT_framebuffer_object SF_GLAD_GL_OES_framebuffer_object - #define GLEXT_glBindRenderbuffer glBindRenderbufferOES - #define GLEXT_glDeleteRenderbuffers glDeleteRenderbuffersOES - #define GLEXT_glGenRenderbuffers glGenRenderbuffersOES - #define GLEXT_glRenderbufferStorage glRenderbufferStorageOES - #define GLEXT_glBindFramebuffer glBindFramebufferOES - #define GLEXT_glDeleteFramebuffers glDeleteFramebuffersOES - #define GLEXT_glGenFramebuffers glGenFramebuffersOES - #define GLEXT_glCheckFramebufferStatus glCheckFramebufferStatusOES - #define GLEXT_glFramebufferTexture2D glFramebufferTexture2DOES - #define GLEXT_glFramebufferRenderbuffer glFramebufferRenderbufferOES - #define GLEXT_glGenerateMipmap glGenerateMipmapOES - #define GLEXT_GL_FRAMEBUFFER GL_FRAMEBUFFER_OES - #define GLEXT_GL_RENDERBUFFER GL_RENDERBUFFER_OES - #define GLEXT_GL_DEPTH_COMPONENT GL_DEPTH_COMPONENT16_OES - #define GLEXT_GL_COLOR_ATTACHMENT0 GL_COLOR_ATTACHMENT0_OES - #define GLEXT_GL_DEPTH_ATTACHMENT GL_DEPTH_ATTACHMENT_OES - #define GLEXT_GL_FRAMEBUFFER_COMPLETE GL_FRAMEBUFFER_COMPLETE_OES - #define GLEXT_GL_FRAMEBUFFER_BINDING GL_FRAMEBUFFER_BINDING_OES - #define GLEXT_GL_INVALID_FRAMEBUFFER_OPERATION GL_INVALID_FRAMEBUFFER_OPERATION_OES +// Core since 2.0 - OES_framebuffer_object +#define GLEXT_framebuffer_object SF_GLAD_GL_OES_framebuffer_object +#define GLEXT_glBindRenderbuffer glBindRenderbufferOES +#define GLEXT_glDeleteRenderbuffers glDeleteRenderbuffersOES +#define GLEXT_glGenRenderbuffers glGenRenderbuffersOES +#define GLEXT_glRenderbufferStorage glRenderbufferStorageOES +#define GLEXT_glBindFramebuffer glBindFramebufferOES +#define GLEXT_glDeleteFramebuffers glDeleteFramebuffersOES +#define GLEXT_glGenFramebuffers glGenFramebuffersOES +#define GLEXT_glCheckFramebufferStatus glCheckFramebufferStatusOES +#define GLEXT_glFramebufferTexture2D glFramebufferTexture2DOES +#define GLEXT_glFramebufferRenderbuffer glFramebufferRenderbufferOES +#define GLEXT_glGenerateMipmap glGenerateMipmapOES +#define GLEXT_GL_FRAMEBUFFER GL_FRAMEBUFFER_OES +#define GLEXT_GL_RENDERBUFFER GL_RENDERBUFFER_OES +#define GLEXT_GL_DEPTH_COMPONENT GL_DEPTH_COMPONENT16_OES +#define GLEXT_GL_COLOR_ATTACHMENT0 GL_COLOR_ATTACHMENT0_OES +#define GLEXT_GL_DEPTH_ATTACHMENT GL_DEPTH_ATTACHMENT_OES +#define GLEXT_GL_FRAMEBUFFER_COMPLETE GL_FRAMEBUFFER_COMPLETE_OES +#define GLEXT_GL_FRAMEBUFFER_BINDING GL_FRAMEBUFFER_BINDING_OES +#define GLEXT_GL_INVALID_FRAMEBUFFER_OPERATION GL_INVALID_FRAMEBUFFER_OPERATION_OES - // Core since 3.0 - #define GLEXT_packed_depth_stencil SF_GLAD_GL_OES_packed_depth_stencil - #define GLEXT_GL_DEPTH24_STENCIL8 GL_DEPTH24_STENCIL8_OES +// Core since 3.0 +#define GLEXT_packed_depth_stencil SF_GLAD_GL_OES_packed_depth_stencil +#define GLEXT_GL_DEPTH24_STENCIL8 GL_DEPTH24_STENCIL8_OES - // Core since 3.0 - #define GLEXT_framebuffer_blit false - #define GLEXT_glBlitFramebuffer glBlitFramebufferEXT // Placeholder to satisfy the compiler, entry point is not loaded in GLES - #define GLEXT_GL_READ_FRAMEBUFFER 0 - #define GLEXT_GL_DRAW_FRAMEBUFFER 0 - #define GLEXT_GL_DRAW_FRAMEBUFFER_BINDING 0 - #define GLEXT_GL_READ_FRAMEBUFFER_BINDING 0 +// Core since 3.0 +#define GLEXT_framebuffer_blit false +#define GLEXT_glBlitFramebuffer \ + glBlitFramebufferEXT // Placeholder to satisfy the compiler, entry point is not loaded in GLES +#define GLEXT_GL_READ_FRAMEBUFFER 0 +#define GLEXT_GL_DRAW_FRAMEBUFFER 0 +#define GLEXT_GL_DRAW_FRAMEBUFFER_BINDING 0 +#define GLEXT_GL_READ_FRAMEBUFFER_BINDING 0 - // Core since 3.0 - #define GLEXT_framebuffer_multisample false - #define GLEXT_glRenderbufferStorageMultisample glRenderbufferStorageMultisampleEXT // Placeholder to satisfy the compiler, entry point is not loaded in GLES - #define GLEXT_GL_MAX_SAMPLES 0 +// Core since 3.0 +#define GLEXT_framebuffer_multisample false +#define GLEXT_glRenderbufferStorageMultisample \ + glRenderbufferStorageMultisampleEXT // Placeholder to satisfy the compiler, entry point is not loaded in GLES +#define GLEXT_GL_MAX_SAMPLES 0 - // Core since 3.0 - NV_copy_buffer - #define GLEXT_copy_buffer false - #define GLEXT_GL_COPY_READ_BUFFER 0 - #define GLEXT_GL_COPY_WRITE_BUFFER 0 - #define GLEXT_glCopyBufferSubData glCopyBufferSubData // Placeholder to satisfy the compiler, entry point is not loaded in GLES +// Core since 3.0 - NV_copy_buffer +#define GLEXT_copy_buffer false +#define GLEXT_GL_COPY_READ_BUFFER 0 +#define GLEXT_GL_COPY_WRITE_BUFFER 0 +#define GLEXT_glCopyBufferSubData \ + glCopyBufferSubData // Placeholder to satisfy the compiler, entry point is not loaded in GLES - // Core since 3.0 - EXT_sRGB - #define GLEXT_texture_sRGB false - #define GLEXT_GL_SRGB8_ALPHA8 0 +// Core since 3.0 - EXT_sRGB +#define GLEXT_texture_sRGB false +#define GLEXT_GL_SRGB8_ALPHA8 0 - // Core since 3.0 - EXT_blend_minmax - #define GLEXT_blend_minmax SF_GLAD_GL_EXT_blend_minmax - #define GLEXT_GL_MIN GL_MIN_EXT - #define GLEXT_GL_MAX GL_MAX_EXT +// Core since 3.0 - EXT_blend_minmax +#define GLEXT_blend_minmax SF_GLAD_GL_EXT_blend_minmax +#define GLEXT_GL_MIN GL_MIN_EXT +#define GLEXT_GL_MAX GL_MAX_EXT #else - // SFML requires at a bare minimum OpenGL 1.1 capability - // All functionality beyond that is optional - // and has to be checked for prior to use +// SFML requires at a bare minimum OpenGL 1.1 capability +// All functionality beyond that is optional +// and has to be checked for prior to use - // Core since 1.1 - #define GLEXT_GL_DEPTH_COMPONENT GL_DEPTH_COMPONENT - #define GLEXT_GL_CLAMP GL_CLAMP +// Core since 1.1 +#define GLEXT_GL_DEPTH_COMPONENT GL_DEPTH_COMPONENT +#define GLEXT_GL_CLAMP GL_CLAMP - // The following extensions are listed chronologically - // Extension macro first, followed by tokens then - // functions according to the corresponding specification +// The following extensions are listed chronologically +// Extension macro first, followed by tokens then +// functions according to the corresponding specification - // The following extensions are optional. +// The following extensions are optional. - // Core since 1.2 - SGIS_texture_edge_clamp / EXT_texture_edge_clamp - #define GLEXT_texture_edge_clamp SF_GLAD_GL_SGIS_texture_edge_clamp - #define GLEXT_GL_CLAMP_TO_EDGE GL_CLAMP_TO_EDGE_SGIS +// Core since 1.2 - SGIS_texture_edge_clamp / EXT_texture_edge_clamp +#define GLEXT_texture_edge_clamp SF_GLAD_GL_SGIS_texture_edge_clamp +#define GLEXT_GL_CLAMP_TO_EDGE GL_CLAMP_TO_EDGE_SGIS - // Core since 1.2 - EXT_blend_minmax - #define GLEXT_blend_minmax SF_GLAD_GL_EXT_blend_minmax - #define GLEXT_glBlendEquation glBlendEquationEXT - #define GLEXT_GL_FUNC_ADD GL_FUNC_ADD_EXT - #define GLEXT_GL_MIN GL_MIN_EXT - #define GLEXT_GL_MAX GL_MAX_EXT +// Core since 1.2 - EXT_blend_minmax +#define GLEXT_blend_minmax SF_GLAD_GL_EXT_blend_minmax +#define GLEXT_glBlendEquation glBlendEquationEXT +#define GLEXT_GL_FUNC_ADD GL_FUNC_ADD_EXT +#define GLEXT_GL_MIN GL_MIN_EXT +#define GLEXT_GL_MAX GL_MAX_EXT - // Core since 1.2 - EXT_blend_subtract - #define GLEXT_blend_subtract SF_GLAD_GL_EXT_blend_subtract - #define GLEXT_GL_FUNC_SUBTRACT GL_FUNC_SUBTRACT_EXT - #define GLEXT_GL_FUNC_REVERSE_SUBTRACT GL_FUNC_REVERSE_SUBTRACT_EXT +// Core since 1.2 - EXT_blend_subtract +#define GLEXT_blend_subtract SF_GLAD_GL_EXT_blend_subtract +#define GLEXT_GL_FUNC_SUBTRACT GL_FUNC_SUBTRACT_EXT +#define GLEXT_GL_FUNC_REVERSE_SUBTRACT GL_FUNC_REVERSE_SUBTRACT_EXT - // Core since 1.3 - ARB_multitexture - #define GLEXT_multitexture SF_GLAD_GL_ARB_multitexture - #define GLEXT_glClientActiveTexture glClientActiveTextureARB - #define GLEXT_glActiveTexture glActiveTextureARB - #define GLEXT_GL_TEXTURE0 GL_TEXTURE0_ARB +// Core since 1.3 - ARB_multitexture +#define GLEXT_multitexture SF_GLAD_GL_ARB_multitexture +#define GLEXT_glClientActiveTexture glClientActiveTextureARB +#define GLEXT_glActiveTexture glActiveTextureARB +#define GLEXT_GL_TEXTURE0 GL_TEXTURE0_ARB - // Core since 1.4 - EXT_blend_func_separate - #define GLEXT_blend_func_separate SF_GLAD_GL_EXT_blend_func_separate - #define GLEXT_glBlendFuncSeparate glBlendFuncSeparateEXT +// Core since 1.4 - EXT_blend_func_separate +#define GLEXT_blend_func_separate SF_GLAD_GL_EXT_blend_func_separate +#define GLEXT_glBlendFuncSeparate glBlendFuncSeparateEXT - // Core since 1.5 - ARB_vertex_buffer_object - #define GLEXT_vertex_buffer_object SF_GLAD_GL_ARB_vertex_buffer_object - #define GLEXT_GL_ARRAY_BUFFER GL_ARRAY_BUFFER_ARB - #define GLEXT_GL_DYNAMIC_DRAW GL_DYNAMIC_DRAW_ARB - #define GLEXT_GL_READ_ONLY GL_READ_ONLY_ARB - #define GLEXT_GL_STATIC_DRAW GL_STATIC_DRAW_ARB - #define GLEXT_GL_STREAM_DRAW GL_STREAM_DRAW_ARB - #define GLEXT_GL_WRITE_ONLY GL_WRITE_ONLY_ARB - #define GLEXT_glBindBuffer glBindBufferARB - #define GLEXT_glBufferData glBufferDataARB - #define GLEXT_glBufferSubData glBufferSubDataARB - #define GLEXT_glDeleteBuffers glDeleteBuffersARB - #define GLEXT_glGenBuffers glGenBuffersARB - #define GLEXT_glMapBuffer glMapBufferARB - #define GLEXT_glUnmapBuffer glUnmapBufferARB +// Core since 1.5 - ARB_vertex_buffer_object +#define GLEXT_vertex_buffer_object SF_GLAD_GL_ARB_vertex_buffer_object +#define GLEXT_GL_ARRAY_BUFFER GL_ARRAY_BUFFER_ARB +#define GLEXT_GL_DYNAMIC_DRAW GL_DYNAMIC_DRAW_ARB +#define GLEXT_GL_READ_ONLY GL_READ_ONLY_ARB +#define GLEXT_GL_STATIC_DRAW GL_STATIC_DRAW_ARB +#define GLEXT_GL_STREAM_DRAW GL_STREAM_DRAW_ARB +#define GLEXT_GL_WRITE_ONLY GL_WRITE_ONLY_ARB +#define GLEXT_glBindBuffer glBindBufferARB +#define GLEXT_glBufferData glBufferDataARB +#define GLEXT_glBufferSubData glBufferSubDataARB +#define GLEXT_glDeleteBuffers glDeleteBuffersARB +#define GLEXT_glGenBuffers glGenBuffersARB +#define GLEXT_glMapBuffer glMapBufferARB +#define GLEXT_glUnmapBuffer glUnmapBufferARB - // Core since 2.0 - ARB_shading_language_100 - #define GLEXT_shading_language_100 SF_GLAD_GL_ARB_shading_language_100 +// Core since 2.0 - ARB_shading_language_100 +#define GLEXT_shading_language_100 SF_GLAD_GL_ARB_shading_language_100 - // Core since 2.0 - ARB_shader_objects - #define GLEXT_shader_objects SF_GLAD_GL_ARB_shader_objects - #define GLEXT_glDeleteObject glDeleteObjectARB - #define GLEXT_glGetHandle glGetHandleARB - #define GLEXT_glCreateShaderObject glCreateShaderObjectARB - #define GLEXT_glShaderSource glShaderSourceARB - #define GLEXT_glCompileShader glCompileShaderARB - #define GLEXT_glCreateProgramObject glCreateProgramObjectARB - #define GLEXT_glAttachObject glAttachObjectARB - #define GLEXT_glLinkProgram glLinkProgramARB - #define GLEXT_glUseProgramObject glUseProgramObjectARB - #define GLEXT_glUniform1f glUniform1fARB - #define GLEXT_glUniform2f glUniform2fARB - #define GLEXT_glUniform3f glUniform3fARB - #define GLEXT_glUniform4f glUniform4fARB - #define GLEXT_glUniform1i glUniform1iARB - #define GLEXT_glUniform2i glUniform2iARB - #define GLEXT_glUniform3i glUniform3iARB - #define GLEXT_glUniform4i glUniform4iARB - #define GLEXT_glUniform1fv glUniform1fvARB - #define GLEXT_glUniform2fv glUniform2fvARB - #define GLEXT_glUniform2iv glUniform2ivARB - #define GLEXT_glUniform3fv glUniform3fvARB - #define GLEXT_glUniform4fv glUniform4fvARB - #define GLEXT_glUniformMatrix3fv glUniformMatrix3fvARB - #define GLEXT_glUniformMatrix4fv glUniformMatrix4fvARB - #define GLEXT_glGetObjectParameteriv glGetObjectParameterivARB - #define GLEXT_glGetInfoLog glGetInfoLogARB - #define GLEXT_glGetUniformLocation glGetUniformLocationARB - #define GLEXT_GL_PROGRAM_OBJECT GL_PROGRAM_OBJECT_ARB - #define GLEXT_GL_OBJECT_COMPILE_STATUS GL_OBJECT_COMPILE_STATUS_ARB - #define GLEXT_GL_OBJECT_LINK_STATUS GL_OBJECT_LINK_STATUS_ARB - #define GLEXT_GLhandle GLhandleARB +// Core since 2.0 - ARB_shader_objects +#define GLEXT_shader_objects SF_GLAD_GL_ARB_shader_objects +#define GLEXT_glDeleteObject glDeleteObjectARB +#define GLEXT_glGetHandle glGetHandleARB +#define GLEXT_glCreateShaderObject glCreateShaderObjectARB +#define GLEXT_glShaderSource glShaderSourceARB +#define GLEXT_glCompileShader glCompileShaderARB +#define GLEXT_glCreateProgramObject glCreateProgramObjectARB +#define GLEXT_glAttachObject glAttachObjectARB +#define GLEXT_glLinkProgram glLinkProgramARB +#define GLEXT_glUseProgramObject glUseProgramObjectARB +#define GLEXT_glUniform1f glUniform1fARB +#define GLEXT_glUniform2f glUniform2fARB +#define GLEXT_glUniform3f glUniform3fARB +#define GLEXT_glUniform4f glUniform4fARB +#define GLEXT_glUniform1i glUniform1iARB +#define GLEXT_glUniform2i glUniform2iARB +#define GLEXT_glUniform3i glUniform3iARB +#define GLEXT_glUniform4i glUniform4iARB +#define GLEXT_glUniform1fv glUniform1fvARB +#define GLEXT_glUniform2fv glUniform2fvARB +#define GLEXT_glUniform2iv glUniform2ivARB +#define GLEXT_glUniform3fv glUniform3fvARB +#define GLEXT_glUniform4fv glUniform4fvARB +#define GLEXT_glUniformMatrix3fv glUniformMatrix3fvARB +#define GLEXT_glUniformMatrix4fv glUniformMatrix4fvARB +#define GLEXT_glGetObjectParameteriv glGetObjectParameterivARB +#define GLEXT_glGetInfoLog glGetInfoLogARB +#define GLEXT_glGetUniformLocation glGetUniformLocationARB +#define GLEXT_GL_PROGRAM_OBJECT GL_PROGRAM_OBJECT_ARB +#define GLEXT_GL_OBJECT_COMPILE_STATUS GL_OBJECT_COMPILE_STATUS_ARB +#define GLEXT_GL_OBJECT_LINK_STATUS GL_OBJECT_LINK_STATUS_ARB +#define GLEXT_GLhandle GLhandleARB - // Core since 2.0 - ARB_vertex_shader - #define GLEXT_vertex_shader SF_GLAD_GL_ARB_vertex_shader - #define GLEXT_GL_VERTEX_SHADER GL_VERTEX_SHADER_ARB - #define GLEXT_GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS_ARB +// Core since 2.0 - ARB_vertex_shader +#define GLEXT_vertex_shader SF_GLAD_GL_ARB_vertex_shader +#define GLEXT_GL_VERTEX_SHADER GL_VERTEX_SHADER_ARB +#define GLEXT_GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS_ARB - // Core since 2.0 - ARB_fragment_shader - #define GLEXT_fragment_shader SF_GLAD_GL_ARB_fragment_shader - #define GLEXT_GL_FRAGMENT_SHADER GL_FRAGMENT_SHADER_ARB +// Core since 2.0 - ARB_fragment_shader +#define GLEXT_fragment_shader SF_GLAD_GL_ARB_fragment_shader +#define GLEXT_GL_FRAGMENT_SHADER GL_FRAGMENT_SHADER_ARB - // Core since 2.0 - ARB_texture_non_power_of_two - #define GLEXT_texture_non_power_of_two SF_GLAD_GL_ARB_texture_non_power_of_two +// Core since 2.0 - ARB_texture_non_power_of_two +#define GLEXT_texture_non_power_of_two SF_GLAD_GL_ARB_texture_non_power_of_two - // Core since 2.0 - EXT_blend_equation_separate - #define GLEXT_blend_equation_separate SF_GLAD_GL_EXT_blend_equation_separate - #define GLEXT_glBlendEquationSeparate glBlendEquationSeparateEXT +// Core since 2.0 - EXT_blend_equation_separate +#define GLEXT_blend_equation_separate SF_GLAD_GL_EXT_blend_equation_separate +#define GLEXT_glBlendEquationSeparate glBlendEquationSeparateEXT - // Core since 2.1 - EXT_texture_sRGB - #define GLEXT_texture_sRGB SF_GLAD_GL_EXT_texture_sRGB - #define GLEXT_GL_SRGB8_ALPHA8 GL_SRGB8_ALPHA8_EXT +// Core since 2.1 - EXT_texture_sRGB +#define GLEXT_texture_sRGB SF_GLAD_GL_EXT_texture_sRGB +#define GLEXT_GL_SRGB8_ALPHA8 GL_SRGB8_ALPHA8_EXT - // Core since 3.0 - EXT_framebuffer_object - #define GLEXT_framebuffer_object SF_GLAD_GL_EXT_framebuffer_object - #define GLEXT_glBindRenderbuffer glBindRenderbufferEXT - #define GLEXT_glDeleteRenderbuffers glDeleteRenderbuffersEXT - #define GLEXT_glGenRenderbuffers glGenRenderbuffersEXT - #define GLEXT_glRenderbufferStorage glRenderbufferStorageEXT - #define GLEXT_glBindFramebuffer glBindFramebufferEXT - #define GLEXT_glDeleteFramebuffers glDeleteFramebuffersEXT - #define GLEXT_glGenFramebuffers glGenFramebuffersEXT - #define GLEXT_glCheckFramebufferStatus glCheckFramebufferStatusEXT - #define GLEXT_glFramebufferTexture2D glFramebufferTexture2DEXT - #define GLEXT_glFramebufferRenderbuffer glFramebufferRenderbufferEXT - #define GLEXT_glGenerateMipmap glGenerateMipmapEXT - #define GLEXT_GL_FRAMEBUFFER GL_FRAMEBUFFER_EXT - #define GLEXT_GL_RENDERBUFFER GL_RENDERBUFFER_EXT - #define GLEXT_GL_COLOR_ATTACHMENT0 GL_COLOR_ATTACHMENT0_EXT - #define GLEXT_GL_DEPTH_ATTACHMENT GL_DEPTH_ATTACHMENT_EXT - #define GLEXT_GL_FRAMEBUFFER_COMPLETE GL_FRAMEBUFFER_COMPLETE_EXT - #define GLEXT_GL_FRAMEBUFFER_BINDING GL_FRAMEBUFFER_BINDING_EXT - #define GLEXT_GL_INVALID_FRAMEBUFFER_OPERATION GL_INVALID_FRAMEBUFFER_OPERATION_EXT - #define GLEXT_GL_STENCIL_ATTACHMENT GL_STENCIL_ATTACHMENT_EXT +// Core since 3.0 - EXT_framebuffer_object +#define GLEXT_framebuffer_object SF_GLAD_GL_EXT_framebuffer_object +#define GLEXT_glBindRenderbuffer glBindRenderbufferEXT +#define GLEXT_glDeleteRenderbuffers glDeleteRenderbuffersEXT +#define GLEXT_glGenRenderbuffers glGenRenderbuffersEXT +#define GLEXT_glRenderbufferStorage glRenderbufferStorageEXT +#define GLEXT_glBindFramebuffer glBindFramebufferEXT +#define GLEXT_glDeleteFramebuffers glDeleteFramebuffersEXT +#define GLEXT_glGenFramebuffers glGenFramebuffersEXT +#define GLEXT_glCheckFramebufferStatus glCheckFramebufferStatusEXT +#define GLEXT_glFramebufferTexture2D glFramebufferTexture2DEXT +#define GLEXT_glFramebufferRenderbuffer glFramebufferRenderbufferEXT +#define GLEXT_glGenerateMipmap glGenerateMipmapEXT +#define GLEXT_GL_FRAMEBUFFER GL_FRAMEBUFFER_EXT +#define GLEXT_GL_RENDERBUFFER GL_RENDERBUFFER_EXT +#define GLEXT_GL_COLOR_ATTACHMENT0 GL_COLOR_ATTACHMENT0_EXT +#define GLEXT_GL_DEPTH_ATTACHMENT GL_DEPTH_ATTACHMENT_EXT +#define GLEXT_GL_FRAMEBUFFER_COMPLETE GL_FRAMEBUFFER_COMPLETE_EXT +#define GLEXT_GL_FRAMEBUFFER_BINDING GL_FRAMEBUFFER_BINDING_EXT +#define GLEXT_GL_INVALID_FRAMEBUFFER_OPERATION GL_INVALID_FRAMEBUFFER_OPERATION_EXT +#define GLEXT_GL_STENCIL_ATTACHMENT GL_STENCIL_ATTACHMENT_EXT - // Core since 3.0 - EXT_packed_depth_stencil - #define GLEXT_packed_depth_stencil SF_GLAD_GL_EXT_packed_depth_stencil - #define GLEXT_GL_DEPTH24_STENCIL8 GL_DEPTH24_STENCIL8_EXT +// Core since 3.0 - EXT_packed_depth_stencil +#define GLEXT_packed_depth_stencil SF_GLAD_GL_EXT_packed_depth_stencil +#define GLEXT_GL_DEPTH24_STENCIL8 GL_DEPTH24_STENCIL8_EXT - // Core since 3.0 - EXT_framebuffer_blit - #define GLEXT_framebuffer_blit SF_GLAD_GL_EXT_framebuffer_blit - #define GLEXT_glBlitFramebuffer glBlitFramebufferEXT - #define GLEXT_GL_READ_FRAMEBUFFER GL_READ_FRAMEBUFFER_EXT - #define GLEXT_GL_DRAW_FRAMEBUFFER GL_DRAW_FRAMEBUFFER_EXT - #define GLEXT_GL_DRAW_FRAMEBUFFER_BINDING GL_DRAW_FRAMEBUFFER_BINDING_EXT - #define GLEXT_GL_READ_FRAMEBUFFER_BINDING GL_READ_FRAMEBUFFER_BINDING_EXT +// Core since 3.0 - EXT_framebuffer_blit +#define GLEXT_framebuffer_blit SF_GLAD_GL_EXT_framebuffer_blit +#define GLEXT_glBlitFramebuffer glBlitFramebufferEXT +#define GLEXT_GL_READ_FRAMEBUFFER GL_READ_FRAMEBUFFER_EXT +#define GLEXT_GL_DRAW_FRAMEBUFFER GL_DRAW_FRAMEBUFFER_EXT +#define GLEXT_GL_DRAW_FRAMEBUFFER_BINDING GL_DRAW_FRAMEBUFFER_BINDING_EXT +#define GLEXT_GL_READ_FRAMEBUFFER_BINDING GL_READ_FRAMEBUFFER_BINDING_EXT - // Core since 3.0 - EXT_framebuffer_multisample - #define GLEXT_framebuffer_multisample SF_GLAD_GL_EXT_framebuffer_multisample - #define GLEXT_glRenderbufferStorageMultisample glRenderbufferStorageMultisampleEXT - #define GLEXT_GL_MAX_SAMPLES GL_MAX_SAMPLES_EXT +// Core since 3.0 - EXT_framebuffer_multisample +#define GLEXT_framebuffer_multisample SF_GLAD_GL_EXT_framebuffer_multisample +#define GLEXT_glRenderbufferStorageMultisample glRenderbufferStorageMultisampleEXT +#define GLEXT_GL_MAX_SAMPLES GL_MAX_SAMPLES_EXT - // Core since 3.1 - ARB_copy_buffer - #define GLEXT_copy_buffer SF_GLAD_GL_ARB_copy_buffer - #define GLEXT_GL_COPY_READ_BUFFER GL_COPY_READ_BUFFER - #define GLEXT_GL_COPY_WRITE_BUFFER GL_COPY_WRITE_BUFFER - #define GLEXT_glCopyBufferSubData glCopyBufferSubData +// Core since 3.1 - ARB_copy_buffer +#define GLEXT_copy_buffer SF_GLAD_GL_ARB_copy_buffer +#define GLEXT_GL_COPY_READ_BUFFER GL_COPY_READ_BUFFER +#define GLEXT_GL_COPY_WRITE_BUFFER GL_COPY_WRITE_BUFFER +#define GLEXT_glCopyBufferSubData glCopyBufferSubData - // Core since 3.2 - ARB_geometry_shader4 - #define GLEXT_geometry_shader4 SF_GLAD_GL_ARB_geometry_shader4 - #define GLEXT_GL_GEOMETRY_SHADER GL_GEOMETRY_SHADER_ARB +// Core since 3.2 - ARB_geometry_shader4 +#define GLEXT_geometry_shader4 SF_GLAD_GL_ARB_geometry_shader4 +#define GLEXT_GL_GEOMETRY_SHADER GL_GEOMETRY_SHADER_ARB #endif - // OpenGL Versions - #define GLEXT_GL_VERSION_1_0 SF_GLAD_GL_VERSION_1_0 - #define GLEXT_GL_VERSION_1_1 SF_GLAD_GL_VERSION_1_1 - #define GLEXT_GL_VERSION_1_2 SF_GLAD_GL_VERSION_1_2 - #define GLEXT_GL_VERSION_1_3 SF_GLAD_GL_VERSION_1_3 - #define GLEXT_GL_VERSION_1_4 SF_GLAD_GL_VERSION_1_4 - #define GLEXT_GL_VERSION_1_5 SF_GLAD_GL_VERSION_1_5 - #define GLEXT_GL_VERSION_2_0 SF_GLAD_GL_VERSION_2_0 - #define GLEXT_GL_VERSION_2_1 SF_GLAD_GL_VERSION_2_1 - #define GLEXT_GL_VERSION_3_0 SF_GLAD_GL_VERSION_3_0 - #define GLEXT_GL_VERSION_3_1 SF_GLAD_GL_VERSION_3_1 - #define GLEXT_GL_VERSION_3_2 SF_GLAD_GL_VERSION_3_2 - #define GLEXT_GL_VERSION_3_3 SF_GLAD_GL_VERSION_3_3 - #define GLEXT_GL_VERSION_4_0 SF_GLAD_GL_VERSION_4_0 - #define GLEXT_GL_VERSION_4_1 SF_GLAD_GL_VERSION_4_1 - #define GLEXT_GL_VERSION_4_2 SF_GLAD_GL_VERSION_4_2 - #define GLEXT_GL_VERSION_4_3 SF_GLAD_GL_VERSION_4_3 - #define GLEXT_GL_VERSION_4_4 SF_GLAD_GL_VERSION_4_4 - #define GLEXT_GL_VERSION_4_5 SF_GLAD_GL_VERSION_4_5 - #define GLEXT_GL_VERSION_4_6 SF_GLAD_GL_VERSION_4_6 +// OpenGL Versions +#define GLEXT_GL_VERSION_1_0 SF_GLAD_GL_VERSION_1_0 +#define GLEXT_GL_VERSION_1_1 SF_GLAD_GL_VERSION_1_1 +#define GLEXT_GL_VERSION_1_2 SF_GLAD_GL_VERSION_1_2 +#define GLEXT_GL_VERSION_1_3 SF_GLAD_GL_VERSION_1_3 +#define GLEXT_GL_VERSION_1_4 SF_GLAD_GL_VERSION_1_4 +#define GLEXT_GL_VERSION_1_5 SF_GLAD_GL_VERSION_1_5 +#define GLEXT_GL_VERSION_2_0 SF_GLAD_GL_VERSION_2_0 +#define GLEXT_GL_VERSION_2_1 SF_GLAD_GL_VERSION_2_1 +#define GLEXT_GL_VERSION_3_0 SF_GLAD_GL_VERSION_3_0 +#define GLEXT_GL_VERSION_3_1 SF_GLAD_GL_VERSION_3_1 +#define GLEXT_GL_VERSION_3_2 SF_GLAD_GL_VERSION_3_2 +#define GLEXT_GL_VERSION_3_3 SF_GLAD_GL_VERSION_3_3 +#define GLEXT_GL_VERSION_4_0 SF_GLAD_GL_VERSION_4_0 +#define GLEXT_GL_VERSION_4_1 SF_GLAD_GL_VERSION_4_1 +#define GLEXT_GL_VERSION_4_2 SF_GLAD_GL_VERSION_4_2 +#define GLEXT_GL_VERSION_4_3 SF_GLAD_GL_VERSION_4_3 +#define GLEXT_GL_VERSION_4_4 SF_GLAD_GL_VERSION_4_4 +#define GLEXT_GL_VERSION_4_5 SF_GLAD_GL_VERSION_4_5 +#define GLEXT_GL_VERSION_4_6 SF_GLAD_GL_VERSION_4_6 namespace sf { diff --git a/src/SFML/Graphics/Glsl.cpp b/src/SFML/Graphics/Glsl.cpp index 1342497ed..d81e2052d 100644 --- a/src/SFML/Graphics/Glsl.cpp +++ b/src/SFML/Graphics/Glsl.cpp @@ -27,6 +27,7 @@ // Headers //////////////////////////////////////////////////////////// #include + #include @@ -35,52 +36,58 @@ namespace sf namespace priv { - //////////////////////////////////////////////////////////// - void copyMatrix(const Transform& source, Matrix<3, 3>& dest) - { - const float* from = source.getMatrix(); // 4x4 - float* to = dest.array; // 3x3 +//////////////////////////////////////////////////////////// +void copyMatrix(const Transform& source, Matrix<3, 3>& dest) +{ + const float* from = source.getMatrix(); // 4x4 + float* to = dest.array; // 3x3 - // Use only left-upper 3x3 block (for a 2D transform) - to[0] = from[ 0]; to[1] = from[ 1]; to[2] = from[ 3]; - to[3] = from[ 4]; to[4] = from[ 5]; to[5] = from[ 7]; - to[6] = from[12]; to[7] = from[13]; to[8] = from[15]; - } + // Use only left-upper 3x3 block (for a 2D transform) + to[0] = from[0]; + to[1] = from[1]; + to[2] = from[3]; + to[3] = from[4]; + to[4] = from[5]; + to[5] = from[7]; + to[6] = from[12]; + to[7] = from[13]; + to[8] = from[15]; +} - //////////////////////////////////////////////////////////// - void copyMatrix(const Transform& source, Matrix<4, 4>& dest) - { - // Adopt 4x4 matrix as-is - copyMatrix(source.getMatrix(), 4 * 4, dest.array); - } +//////////////////////////////////////////////////////////// +void copyMatrix(const Transform& source, Matrix<4, 4>& dest) +{ + // Adopt 4x4 matrix as-is + copyMatrix(source.getMatrix(), 4 * 4, dest.array); +} - //////////////////////////////////////////////////////////// - void copyMatrix(const float* source, std::size_t elements, float* dest) - { - std::copy(source, source + elements, dest); - } +//////////////////////////////////////////////////////////// +void copyMatrix(const float* source, std::size_t elements, float* dest) +{ + std::copy(source, source + elements, dest); +} - //////////////////////////////////////////////////////////// - void copyVector(const Color& source, Vector4& dest) - { - dest.x = source.r / 255.f; - dest.y = source.g / 255.f; - dest.z = source.b / 255.f; - dest.w = source.a / 255.f; - } +//////////////////////////////////////////////////////////// +void copyVector(const Color& source, Vector4& dest) +{ + dest.x = source.r / 255.f; + dest.y = source.g / 255.f; + dest.z = source.b / 255.f; + dest.w = source.a / 255.f; +} - //////////////////////////////////////////////////////////// - void copyVector(const Color& source, Vector4& dest) - { - dest.x = static_cast(source.r); - dest.y = static_cast(source.g); - dest.z = static_cast(source.b); - dest.w = static_cast(source.a); - } +//////////////////////////////////////////////////////////// +void copyVector(const Color& source, Vector4& dest) +{ + dest.x = static_cast(source.r); + dest.y = static_cast(source.g); + dest.z = static_cast(source.b); + dest.w = static_cast(source.a); +} } // namespace priv } // namespace sf diff --git a/src/SFML/Graphics/Image.cpp b/src/SFML/Graphics/Image.cpp index 7c8564110..09f3c1412 100644 --- a/src/SFML/Graphics/Image.cpp +++ b/src/SFML/Graphics/Image.cpp @@ -29,11 +29,11 @@ #include #include #ifdef SFML_SYSTEM_ANDROID - #include +#include #endif #include -#include #include +#include namespace sf @@ -104,16 +104,16 @@ void Image::create(const Vector2u& size, const Uint8* pixels) //////////////////////////////////////////////////////////// bool Image::loadFromFile(const std::filesystem::path& filename) { - #ifndef SFML_SYSTEM_ANDROID +#ifndef SFML_SYSTEM_ANDROID - return priv::ImageLoader::getInstance().loadImageFromFile(filename, m_pixels, m_size); + return priv::ImageLoader::getInstance().loadImageFromFile(filename, m_pixels, m_size); - #else +#else - priv::ResourceStream stream(filename); - return loadFromStream(stream); + priv::ResourceStream stream(filename); + return loadFromStream(stream); - #endif +#endif } @@ -193,8 +193,7 @@ void Image::createMaskFromColor(const Color& color, Uint8 alpha) { // Checking the bottom right corner is enough because // left and top are non-negative and width and height are positive. - if (source.m_size.x < srcRect.left + srcRect.width || - source.m_size.y < srcRect.top + srcRect.height) + if (source.m_size.x < srcRect.left + srcRect.width || source.m_size.y < srcRect.top + srcRect.height) return false; } @@ -203,8 +202,7 @@ void Image::createMaskFromColor(const Color& color, Uint8 alpha) return false; // Then find the valid size of the destination rectangle - const Vector2u dstSize(std::min(m_size.x - dest.x, srcRect.width), - std::min(m_size.y - dest.y, srcRect.height)); + const Vector2u dstSize(std::min(m_size.x - dest.x, srcRect.width), std::min(m_size.y - dest.y, srcRect.height)); // Precompute as much as possible const std::size_t pitch = static_cast(dstSize.x) * 4; @@ -264,10 +262,10 @@ void Image::createMaskFromColor(const Color& color, Uint8 alpha) void Image::setPixel(const Vector2u& coords, const Color& color) { Uint8* pixel = &m_pixels[(coords.x + coords.y * m_size.x) * 4]; - *pixel++ = color.r; - *pixel++ = color.g; - *pixel++ = color.b; - *pixel++ = color.a; + *pixel++ = color.r; + *pixel++ = color.g; + *pixel++ = color.b; + *pixel++ = color.a; } @@ -303,8 +301,9 @@ void Image::flipHorizontally() for (std::size_t y = 0; y < m_size.y; ++y) { - auto left = m_pixels.begin() + static_cast::iterator::difference_type>(y * rowSize); - auto right = m_pixels.begin() + static_cast::iterator::difference_type>((y + 1) * rowSize - 4); + auto left = m_pixels.begin() + static_cast::iterator::difference_type>(y * rowSize); + auto right = m_pixels.begin() + + static_cast::iterator::difference_type>((y + 1) * rowSize - 4); for (std::size_t x = 0; x < m_size.x / 2; ++x) { @@ -325,7 +324,7 @@ void Image::flipVertically() { auto rowSize = static_cast::iterator::difference_type>(m_size.x * 4); - auto top = m_pixels.begin(); + auto top = m_pixels.begin(); auto bottom = m_pixels.end() - rowSize; for (std::size_t y = 0; y < m_size.y / 2; ++y) diff --git a/src/SFML/Graphics/ImageLoader.cpp b/src/SFML/Graphics/ImageLoader.cpp index b6630c93c..196731450 100644 --- a/src/SFML/Graphics/ImageLoader.cpp +++ b/src/SFML/Graphics/ImageLoader.cpp @@ -26,13 +26,14 @@ // Headers //////////////////////////////////////////////////////////// #include -#include #include +#include #include #define STB_IMAGE_IMPLEMENTATION #include #define STB_IMAGE_WRITE_IMPLEMENTATION #include + #include #include #include @@ -41,33 +42,33 @@ namespace { - // stb_image callbacks that operate on a sf::InputStream - int read(void* user, char* data, int size) - { - auto* stream = static_cast(user); - return static_cast(stream->read(data, size)); - } - void skip(void* user, int size) - { - auto* stream = static_cast(user); - - if (stream->seek(stream->tell() + size) == -1) - sf::err() << "Failed to seek image loader input stream" << std::endl; - } - int eof(void* user) - { - auto* stream = static_cast(user); - return stream->tell() >= stream->getSize(); - } - - // stb_image callback for constructing a buffer - void bufferFromCallback(void* context, void* data, int size) - { - auto* source = static_cast(data); - auto* dest = static_cast*>(context); - std::copy(source, source + size, std::back_inserter(*dest)); - } +// stb_image callbacks that operate on a sf::InputStream +int read(void* user, char* data, int size) +{ + auto* stream = static_cast(user); + return static_cast(stream->read(data, size)); } +void skip(void* user, int size) +{ + auto* stream = static_cast(user); + + if (stream->seek(stream->tell() + size) == -1) + sf::err() << "Failed to seek image loader input stream" << std::endl; +} +int eof(void* user) +{ + auto* stream = static_cast(user); + return stream->tell() >= stream->getSize(); +} + +// stb_image callback for constructing a buffer +void bufferFromCallback(void* context, void* data, int size) +{ + auto* source = static_cast(data); + auto* dest = static_cast*>(context); + std::copy(source, source + size, std::back_inserter(*dest)); +} +} // namespace namespace sf @@ -97,10 +98,10 @@ bool ImageLoader::loadImageFromFile(const std::filesystem::path& filename, std:: pixels.clear(); // Load the image and get a pointer to the pixels in memory - int width = 0; - int height = 0; - int channels = 0; - unsigned char* ptr = stbi_load(filename.string().c_str(), &width, &height, &channels, STBI_rgb_alpha); + int width = 0; + int height = 0; + int channels = 0; + unsigned char* ptr = stbi_load(filename.string().c_str(), &width, &height, &channels, STBI_rgb_alpha); if (ptr) { @@ -123,7 +124,8 @@ bool ImageLoader::loadImageFromFile(const std::filesystem::path& filename, std:: else { // Error, failed to load the image - err() << "Failed to load image\n" << formatDebugPathInfo(filename) << "\nReason: " << stbi_failure_reason() << std::endl; + err() << "Failed to load image\n" + << formatDebugPathInfo(filename) << "\nReason: " << stbi_failure_reason() << std::endl; return false; } @@ -140,10 +142,10 @@ bool ImageLoader::loadImageFromMemory(const void* data, std::size_t dataSize, st pixels.clear(); // Load the image and get a pointer to the pixels in memory - int width = 0; - int height = 0; - int channels = 0; - const auto* buffer = static_cast(data); + int width = 0; + int height = 0; + int channels = 0; + const auto* buffer = static_cast(data); unsigned char* ptr = stbi_load_from_memory(buffer, static_cast(dataSize), &width, &height, &channels, STBI_rgb_alpha); if (ptr) @@ -200,10 +202,10 @@ bool ImageLoader::loadImageFromStream(InputStream& stream, std::vector& p callbacks.eof = &eof; // Load the image and get a pointer to the pixels in memory - int width = 0; - int height = 0; - int channels = 0; - unsigned char* ptr = stbi_load_from_callbacks(&callbacks, &stream, &width, &height, &channels, STBI_rgb_alpha); + int width = 0; + int height = 0; + int channels = 0; + unsigned char* ptr = stbi_load_from_callbacks(&callbacks, &stream, &width, &height, &channels, STBI_rgb_alpha); if (ptr) { @@ -242,8 +244,8 @@ bool ImageLoader::saveImageToFile(const std::filesystem::path& filename, const s // Deduce the image type from its extension // Extract the extension - const std::filesystem::path extension = filename.extension(); - const Vector2i convertedSize = Vector2i(size); + const std::filesystem::path extension = filename.extension(); + const Vector2i convertedSize = Vector2i(size); if (extension == ".bmp") { @@ -276,14 +278,17 @@ bool ImageLoader::saveImageToFile(const std::filesystem::path& filename, const s } //////////////////////////////////////////////////////////// -bool ImageLoader::saveImageToMemory(const std::string& format, std::vector& output, const std::vector& pixels, const Vector2u& size) +bool ImageLoader::saveImageToMemory(const std::string& format, + std::vector& output, + const std::vector& pixels, + const Vector2u& size) { // Make sure the image is not empty if (!pixels.empty() && (size.x > 0) && (size.y > 0)) { // Choose function based on format - std::string specified = toLower(format); + std::string specified = toLower(format); const Vector2i convertedSize = Vector2i(size); if (specified == "bmp") diff --git a/src/SFML/Graphics/ImageLoader.hpp b/src/SFML/Graphics/ImageLoader.hpp index 1e8b26172..ef3b7aaee 100644 --- a/src/SFML/Graphics/ImageLoader.hpp +++ b/src/SFML/Graphics/ImageLoader.hpp @@ -29,7 +29,9 @@ // Headers //////////////////////////////////////////////////////////// #include + #include + #include #include #include @@ -48,7 +50,6 @@ namespace priv class ImageLoader { public: - //////////////////////////////////////////////////////////// /// \brief Get the unique instance of the class /// @@ -117,10 +118,12 @@ public: /// \return True if saving was successful /// //////////////////////////////////////////////////////////// - bool saveImageToMemory(const std::string& format, std::vector& output, const std::vector& pixels, const Vector2u& size); + bool saveImageToMemory(const std::string& format, + std::vector& output, + const std::vector& pixels, + const Vector2u& size); private: - //////////////////////////////////////////////////////////// /// \brief Default constructor /// diff --git a/src/SFML/Graphics/RectangleShape.cpp b/src/SFML/Graphics/RectangleShape.cpp index c327a4fdd..d1c59e847 100644 --- a/src/SFML/Graphics/RectangleShape.cpp +++ b/src/SFML/Graphics/RectangleShape.cpp @@ -26,6 +26,7 @@ // Headers //////////////////////////////////////////////////////////// #include + #include @@ -66,10 +67,14 @@ Vector2f RectangleShape::getPoint(std::size_t index) const switch (index) { default: - case 0: return Vector2f(0, 0); - case 1: return Vector2f(m_size.x, 0); - case 2: return Vector2f(m_size.x, m_size.y); - case 3: return Vector2f(0, m_size.y); + case 0: + return Vector2f(0, 0); + case 1: + return Vector2f(m_size.x, 0); + case 2: + return Vector2f(m_size.x, m_size.y); + case 3: + return Vector2f(0, m_size.y); } } diff --git a/src/SFML/Graphics/RenderStates.cpp b/src/SFML/Graphics/RenderStates.cpp index 3fbe0c610..63afa6521 100644 --- a/src/SFML/Graphics/RenderStates.cpp +++ b/src/SFML/Graphics/RenderStates.cpp @@ -26,6 +26,7 @@ // Headers //////////////////////////////////////////////////////////// #include + #include @@ -35,16 +36,16 @@ namespace sf // We cannot use the default constructor here, because it accesses BlendAlpha, which is also global (and dynamically // initialized). Initialization order of global objects in different translation units is not defined. const RenderStates RenderStates::Default(BlendMode( - BlendMode::SrcAlpha, BlendMode::OneMinusSrcAlpha, BlendMode::Add, - BlendMode::One, BlendMode::OneMinusSrcAlpha, BlendMode::Add)); + BlendMode::SrcAlpha, + BlendMode::OneMinusSrcAlpha, + BlendMode::Add, + BlendMode::One, + BlendMode::OneMinusSrcAlpha, + BlendMode::Add)); //////////////////////////////////////////////////////////// -RenderStates::RenderStates() : -blendMode(BlendAlpha), -transform(), -texture (nullptr), -shader (nullptr) +RenderStates::RenderStates() : blendMode(BlendAlpha), transform(), texture(nullptr), shader(nullptr) { } @@ -53,8 +54,8 @@ shader (nullptr) RenderStates::RenderStates(const Transform& theTransform) : blendMode(BlendAlpha), transform(theTransform), -texture (nullptr), -shader (nullptr) +texture(nullptr), +shader(nullptr) { } @@ -63,8 +64,8 @@ shader (nullptr) RenderStates::RenderStates(const BlendMode& theBlendMode) : blendMode(theBlendMode), transform(), -texture (nullptr), -shader (nullptr) +texture(nullptr), +shader(nullptr) { } @@ -73,8 +74,8 @@ shader (nullptr) RenderStates::RenderStates(const Texture* theTexture) : blendMode(BlendAlpha), transform(), -texture (theTexture), -shader (nullptr) +texture(theTexture), +shader(nullptr) { } @@ -83,19 +84,21 @@ shader (nullptr) RenderStates::RenderStates(const Shader* theShader) : blendMode(BlendAlpha), transform(), -texture (nullptr), -shader (theShader) +texture(nullptr), +shader(theShader) { } //////////////////////////////////////////////////////////// -RenderStates::RenderStates(const BlendMode& theBlendMode, const Transform& theTransform, - const Texture* theTexture, const Shader* theShader) : +RenderStates::RenderStates(const BlendMode& theBlendMode, + const Transform& theTransform, + const Texture* theTexture, + const Shader* theShader) : blendMode(theBlendMode), transform(theTransform), -texture (theTexture), -shader (theShader) +texture(theTexture), +shader(theShader) { } diff --git a/src/SFML/Graphics/RenderTarget.cpp b/src/SFML/Graphics/RenderTarget.cpp index 343079f02..4e311cfa7 100644 --- a/src/SFML/Graphics/RenderTarget.cpp +++ b/src/SFML/Graphics/RenderTarget.cpp @@ -25,132 +25,129 @@ //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// -#include #include +#include +#include #include #include #include #include -#include -#include #include +#include + #include +#include #include #include -#include #include -#include +#include namespace { - // A nested named namespace is used here to allow unity builds of SFML. - namespace RenderTargetImpl - { - // Mutex to protect ID generation and our context-RenderTarget-map - std::recursive_mutex mutex; +// A nested named namespace is used here to allow unity builds of SFML. +namespace RenderTargetImpl +{ +// Mutex to protect ID generation and our context-RenderTarget-map +std::recursive_mutex mutex; - // Unique identifier, used for identifying RenderTargets when - // tracking the currently active RenderTarget within a given context - sf::Uint64 getUniqueId() - { - std::scoped_lock lock(mutex); +// Unique identifier, used for identifying RenderTargets when +// tracking the currently active RenderTarget within a given context +sf::Uint64 getUniqueId() +{ + std::scoped_lock lock(mutex); - static sf::Uint64 id = 1; // start at 1, zero is "no RenderTarget" + static sf::Uint64 id = 1; // start at 1, zero is "no RenderTarget" - return id++; - } - - // Map to help us detect whether a different RenderTarget - // has been activated within a single context - using ContextRenderTargetMap = std::unordered_map; - ContextRenderTargetMap contextRenderTargetMap; - - // Check if a RenderTarget with the given ID is active in the current context - bool isActive(sf::Uint64 id) - { - auto it = contextRenderTargetMap.find(sf::Context::getActiveContextId()); - - if ((it == contextRenderTargetMap.end()) || (it->second != id)) - return false; - - return true; - } - - // Convert an sf::BlendMode::Factor constant to the corresponding OpenGL constant. - sf::Uint32 factorToGlConstant(sf::BlendMode::Factor blendFactor) - { - // clang-format off - switch (blendFactor) - { - case sf::BlendMode::Zero: return GL_ZERO; - case sf::BlendMode::One: return GL_ONE; - case sf::BlendMode::SrcColor: return GL_SRC_COLOR; - case sf::BlendMode::OneMinusSrcColor: return GL_ONE_MINUS_SRC_COLOR; - case sf::BlendMode::DstColor: return GL_DST_COLOR; - case sf::BlendMode::OneMinusDstColor: return GL_ONE_MINUS_DST_COLOR; - case sf::BlendMode::SrcAlpha: return GL_SRC_ALPHA; - case sf::BlendMode::OneMinusSrcAlpha: return GL_ONE_MINUS_SRC_ALPHA; - case sf::BlendMode::DstAlpha: return GL_DST_ALPHA; - case sf::BlendMode::OneMinusDstAlpha: return GL_ONE_MINUS_DST_ALPHA; - } - // clang-format on - - sf::err() << "Invalid value for sf::BlendMode::Factor! Fallback to sf::BlendMode::Zero." << std::endl; - assert(false); - return GL_ZERO; - } - - - // Convert an sf::BlendMode::BlendEquation constant to the corresponding OpenGL constant. - sf::Uint32 equationToGlConstant(sf::BlendMode::Equation blendEquation) - { - switch (blendEquation) - { - case sf::BlendMode::Add: - return GLEXT_GL_FUNC_ADD; - case sf::BlendMode::Subtract: - if (GLEXT_blend_subtract) - return GLEXT_GL_FUNC_SUBTRACT; - break; - case sf::BlendMode::ReverseSubtract: - if (GLEXT_blend_subtract) - return GLEXT_GL_FUNC_REVERSE_SUBTRACT; - break; - case sf::BlendMode::Min: - if (GLEXT_blend_minmax) - return GLEXT_GL_MIN; - break; - case sf::BlendMode::Max: - if (GLEXT_blend_minmax) - return GLEXT_GL_MAX; - break; - } - - static bool warned = false; - if (!warned) - { - sf::err() << "OpenGL extension EXT_blend_minmax or EXT_blend_subtract unavailable" << '\n' - << "Some blending equations will fallback to sf::BlendMode::Add" << '\n' - << "Ensure that hardware acceleration is enabled if available" << std::endl; - - warned = true; - } - - return GLEXT_GL_FUNC_ADD; - } - } + return id++; } +// Map to help us detect whether a different RenderTarget +// has been activated within a single context +using ContextRenderTargetMap = std::unordered_map; +ContextRenderTargetMap contextRenderTargetMap; + +// Check if a RenderTarget with the given ID is active in the current context +bool isActive(sf::Uint64 id) +{ + auto it = contextRenderTargetMap.find(sf::Context::getActiveContextId()); + + if ((it == contextRenderTargetMap.end()) || (it->second != id)) + return false; + + return true; +} + +// Convert an sf::BlendMode::Factor constant to the corresponding OpenGL constant. +sf::Uint32 factorToGlConstant(sf::BlendMode::Factor blendFactor) +{ + // clang-format off + switch (blendFactor) + { + case sf::BlendMode::Zero: return GL_ZERO; + case sf::BlendMode::One: return GL_ONE; + case sf::BlendMode::SrcColor: return GL_SRC_COLOR; + case sf::BlendMode::OneMinusSrcColor: return GL_ONE_MINUS_SRC_COLOR; + case sf::BlendMode::DstColor: return GL_DST_COLOR; + case sf::BlendMode::OneMinusDstColor: return GL_ONE_MINUS_DST_COLOR; + case sf::BlendMode::SrcAlpha: return GL_SRC_ALPHA; + case sf::BlendMode::OneMinusSrcAlpha: return GL_ONE_MINUS_SRC_ALPHA; + case sf::BlendMode::DstAlpha: return GL_DST_ALPHA; + case sf::BlendMode::OneMinusDstAlpha: return GL_ONE_MINUS_DST_ALPHA; + } + // clang-format on + + sf::err() << "Invalid value for sf::BlendMode::Factor! Fallback to sf::BlendMode::Zero." << std::endl; + assert(false); + return GL_ZERO; +} + + +// Convert an sf::BlendMode::BlendEquation constant to the corresponding OpenGL constant. +sf::Uint32 equationToGlConstant(sf::BlendMode::Equation blendEquation) +{ + switch (blendEquation) + { + case sf::BlendMode::Add: + return GLEXT_GL_FUNC_ADD; + case sf::BlendMode::Subtract: + if (GLEXT_blend_subtract) + return GLEXT_GL_FUNC_SUBTRACT; + break; + case sf::BlendMode::ReverseSubtract: + if (GLEXT_blend_subtract) + return GLEXT_GL_FUNC_REVERSE_SUBTRACT; + break; + case sf::BlendMode::Min: + if (GLEXT_blend_minmax) + return GLEXT_GL_MIN; + break; + case sf::BlendMode::Max: + if (GLEXT_blend_minmax) + return GLEXT_GL_MAX; + break; + } + + static bool warned = false; + if (!warned) + { + sf::err() << "OpenGL extension EXT_blend_minmax or EXT_blend_subtract unavailable" << '\n' + << "Some blending equations will fallback to sf::BlendMode::Add" << '\n' + << "Ensure that hardware acceleration is enabled if available" << std::endl; + + warned = true; + } + + return GLEXT_GL_FUNC_ADD; +} +} // namespace RenderTargetImpl +} // namespace + namespace sf { //////////////////////////////////////////////////////////// -RenderTarget::RenderTarget() : -m_defaultView(), -m_view (), -m_cache (), -m_id (0) +RenderTarget::RenderTarget() : m_defaultView(), m_view(), m_cache(), m_id(0) { m_cache.glStatesSet = false; } @@ -177,7 +174,7 @@ void RenderTarget::clear(const Color& color) //////////////////////////////////////////////////////////// void RenderTarget::setView(const View& view) { - m_view = view; + m_view = view; m_cache.viewChanged = true; } @@ -199,14 +196,12 @@ const View& RenderTarget::getDefaultView() const //////////////////////////////////////////////////////////// IntRect RenderTarget::getViewport(const View& view) const { - float width = static_cast(getSize().x); - float height = static_cast(getSize().y); + float width = static_cast(getSize().x); + float height = static_cast(getSize().y); const FloatRect& viewport = view.getViewport(); - return IntRect({static_cast(0.5f + width * viewport.left), - static_cast(0.5f + height * viewport.top)}, - {static_cast(0.5f + width * viewport.width), - static_cast(0.5f + height * viewport.height)}); + return IntRect({static_cast(0.5f + width * viewport.left), static_cast(0.5f + height * viewport.top)}, + {static_cast(0.5f + width * viewport.width), static_cast(0.5f + height * viewport.height)}); } @@ -221,10 +216,10 @@ Vector2f RenderTarget::mapPixelToCoords(const Vector2i& point) const Vector2f RenderTarget::mapPixelToCoords(const Vector2i& point, const View& view) const { // First, convert from viewport coordinates to homogeneous coordinates - Vector2f normalized; + Vector2f normalized; FloatRect viewport = FloatRect(getViewport(view)); - normalized.x = -1.f + 2.f * (static_cast(point.x) - viewport.left) / viewport.width; - normalized.y = 1.f - 2.f * (static_cast(point.y) - viewport.top) / viewport.height; + normalized.x = -1.f + 2.f * (static_cast(point.x) - viewport.left) / viewport.width; + normalized.y = 1.f - 2.f * (static_cast(point.y) - viewport.top) / viewport.height; // Then transform by the inverse of the view matrix return view.getInverseTransform().transformPoint(normalized); @@ -245,10 +240,10 @@ Vector2i RenderTarget::mapCoordsToPixel(const Vector2f& point, const View& view) Vector2f normalized = view.getTransform().transformPoint(point); // Then convert to viewport coordinates - Vector2i pixel; + Vector2i pixel; FloatRect viewport = FloatRect(getViewport(view)); - pixel.x = static_cast(( normalized.x + 1.f) / 2.f * viewport.width + viewport.left); - pixel.y = static_cast((-normalized.y + 1.f) / 2.f * viewport.height + viewport.top); + pixel.x = static_cast((normalized.x + 1.f) / 2.f * viewport.width + viewport.left); + pixel.y = static_cast((-normalized.y + 1.f) / 2.f * viewport.height + viewport.top); return pixel; } @@ -262,8 +257,7 @@ void RenderTarget::draw(const Drawable& drawable, const RenderStates& states) //////////////////////////////////////////////////////////// -void RenderTarget::draw(const Vertex* vertices, std::size_t vertexCount, - PrimitiveType type, const RenderStates& states) +void RenderTarget::draw(const Vertex* vertices, std::size_t vertexCount, PrimitiveType type, const RenderStates& states) { // Nothing to draw? if (!vertices || (vertexCount == 0)) @@ -279,9 +273,9 @@ void RenderTarget::draw(const Vertex* vertices, std::size_t vertexCount, // Pre-transform the vertices and store them into the vertex cache for (std::size_t i = 0; i < vertexCount; ++i) { - Vertex& vertex = m_cache.vertexCache[i]; - vertex.position = states.transform * vertices[i].position; - vertex.color = vertices[i].color; + Vertex& vertex = m_cache.vertexCache[i]; + vertex.position = states.transform * vertices[i].position; + vertex.color = vertices[i].color; vertex.texCoords = vertices[i].texCoords; } } @@ -325,7 +319,7 @@ void RenderTarget::draw(const Vertex* vertices, std::size_t vertexCount, cleanupDraw(states); // Update the cache - m_cache.useVertexCache = useVertexCache; + m_cache.useVertexCache = useVertexCache; m_cache.texCoordsArrayEnabled = enableTexCoordsArray; } } @@ -339,8 +333,7 @@ void RenderTarget::draw(const VertexBuffer& vertexBuffer, const RenderStates& st //////////////////////////////////////////////////////////// -void RenderTarget::draw(const VertexBuffer& vertexBuffer, std::size_t firstVertex, - std::size_t vertexCount, const RenderStates& states) +void RenderTarget::draw(const VertexBuffer& vertexBuffer, std::size_t firstVertex, std::size_t vertexCount, const RenderStates& states) { // VertexBuffer not supported? if (!VertexBuffer::isAvailable()) @@ -383,7 +376,7 @@ void RenderTarget::draw(const VertexBuffer& vertexBuffer, std::size_t firstVerte cleanupDraw(states); // Update the cache - m_cache.useVertexCache = false; + m_cache.useVertexCache = false; m_cache.texCoordsArrayEnabled = true; } } @@ -416,7 +409,7 @@ bool RenderTarget::setActive(bool active) contextRenderTargetMap[contextId] = m_id; m_cache.glStatesSet = false; - m_cache.enable = false; + m_cache.enable = false; } else if (it->second != m_id) { @@ -443,21 +436,20 @@ void RenderTarget::pushGLStates() { if (RenderTargetImpl::isActive(m_id) || setActive(true)) { - #ifdef SFML_DEBUG - // make sure that the user didn't leave an unchecked OpenGL error - GLenum error = glGetError(); - if (error != GL_NO_ERROR) - { - err() << "OpenGL error (" << error << ") detected in user code, " - << "you should check for errors with glGetError()" - << std::endl; - } - #endif +#ifdef SFML_DEBUG + // make sure that the user didn't leave an unchecked OpenGL error + GLenum error = glGetError(); + if (error != GL_NO_ERROR) + { + err() << "OpenGL error (" << error << ") detected in user code, " + << "you should check for errors with glGetError()" << std::endl; + } +#endif - #ifndef SFML_OPENGL_ES - glCheck(glPushClientAttrib(GL_CLIENT_ALL_ATTRIB_BITS)); - glCheck(glPushAttrib(GL_ALL_ATTRIB_BITS)); - #endif +#ifndef SFML_OPENGL_ES + glCheck(glPushClientAttrib(GL_CLIENT_ALL_ATTRIB_BITS)); + glCheck(glPushAttrib(GL_ALL_ATTRIB_BITS)); +#endif glCheck(glMatrixMode(GL_MODELVIEW)); glCheck(glPushMatrix()); glCheck(glMatrixMode(GL_PROJECTION)); @@ -481,10 +473,10 @@ void RenderTarget::popGLStates() glCheck(glPopMatrix()); glCheck(glMatrixMode(GL_TEXTURE)); glCheck(glPopMatrix()); - #ifndef SFML_OPENGL_ES - glCheck(glPopClientAttrib()); - glCheck(glPopAttrib()); - #endif +#ifndef SFML_OPENGL_ES + glCheck(glPopClientAttrib()); + glCheck(glPopAttrib()); +#endif } } @@ -493,17 +485,17 @@ void RenderTarget::popGLStates() void RenderTarget::resetGLStates() { // Check here to make sure a context change does not happen after activate(true) - bool shaderAvailable = Shader::isAvailable(); + bool shaderAvailable = Shader::isAvailable(); bool vertexBufferAvailable = VertexBuffer::isAvailable(); - // Workaround for states not being properly reset on - // macOS unless a context switch really takes place - #if defined(SFML_SYSTEM_MACOS) - if (!setActive(false)) - { - err() << "Failed to set render target inactive" << std::endl; - } - #endif +// Workaround for states not being properly reset on +// macOS unless a context switch really takes place +#if defined(SFML_SYSTEM_MACOS) + if (!setActive(false)) + { + err() << "Failed to set render target inactive" << std::endl; + } +#endif if (RenderTargetImpl::isActive(m_id) || setActive(true)) { @@ -573,7 +565,7 @@ void RenderTarget::applyCurrentView() { // Set the viewport IntRect viewport = getViewport(m_view); - int top = static_cast(getSize().y) - (viewport.top + viewport.height); + int top = static_cast(getSize().y) - (viewport.top + viewport.height); glCheck(glViewport(viewport.left, top, viewport.width, viewport.height)); // Set the projection matrix @@ -590,30 +582,28 @@ void RenderTarget::applyCurrentView() //////////////////////////////////////////////////////////// void RenderTarget::applyBlendMode(const BlendMode& mode) { - using RenderTargetImpl::factorToGlConstant; using RenderTargetImpl::equationToGlConstant; + using RenderTargetImpl::factorToGlConstant; // Apply the blend mode, falling back to the non-separate versions if necessary if (GLEXT_blend_func_separate) { - glCheck(GLEXT_glBlendFuncSeparate( - factorToGlConstant(mode.colorSrcFactor), factorToGlConstant(mode.colorDstFactor), - factorToGlConstant(mode.alphaSrcFactor), factorToGlConstant(mode.alphaDstFactor))); + glCheck(GLEXT_glBlendFuncSeparate(factorToGlConstant(mode.colorSrcFactor), + factorToGlConstant(mode.colorDstFactor), + factorToGlConstant(mode.alphaSrcFactor), + factorToGlConstant(mode.alphaDstFactor))); } else { - glCheck(glBlendFunc( - factorToGlConstant(mode.colorSrcFactor), - factorToGlConstant(mode.colorDstFactor))); + glCheck(glBlendFunc(factorToGlConstant(mode.colorSrcFactor), factorToGlConstant(mode.colorDstFactor))); } if (GLEXT_blend_minmax || GLEXT_blend_subtract) { if (GLEXT_blend_equation_separate) { - glCheck(GLEXT_glBlendEquationSeparate( - equationToGlConstant(mode.colorEquation), - equationToGlConstant(mode.alphaEquation))); + glCheck(GLEXT_glBlendEquationSeparate(equationToGlConstant(mode.colorEquation), + equationToGlConstant(mode.alphaEquation))); } else { @@ -734,9 +724,8 @@ void RenderTarget::setupDraw(bool useVertexCache, const RenderStates& states) void RenderTarget::drawPrimitives(PrimitiveType type, std::size_t firstVertex, std::size_t vertexCount) { // Find the OpenGL primitive type - static constexpr GLenum modes[] = {GL_POINTS, GL_LINES, GL_LINE_STRIP, GL_TRIANGLES, - GL_TRIANGLE_STRIP, GL_TRIANGLE_FAN}; - GLenum mode = modes[type]; + static constexpr GLenum modes[] = {GL_POINTS, GL_LINES, GL_LINE_STRIP, GL_TRIANGLES, GL_TRIANGLE_STRIP, GL_TRIANGLE_FAN}; + GLenum mode = modes[type]; // Draw the primitives glCheck(glDrawArrays(mode, static_cast(firstVertex), static_cast(vertexCount))); diff --git a/src/SFML/Graphics/RenderTexture.cpp b/src/SFML/Graphics/RenderTexture.cpp index b0ddd48ee..905865f18 100644 --- a/src/SFML/Graphics/RenderTexture.cpp +++ b/src/SFML/Graphics/RenderTexture.cpp @@ -26,9 +26,10 @@ // Headers //////////////////////////////////////////////////////////// #include -#include #include +#include #include + #include #include diff --git a/src/SFML/Graphics/RenderTextureImpl.hpp b/src/SFML/Graphics/RenderTextureImpl.hpp index dfdf26c8d..b37bce607 100644 --- a/src/SFML/Graphics/RenderTextureImpl.hpp +++ b/src/SFML/Graphics/RenderTextureImpl.hpp @@ -45,7 +45,6 @@ namespace priv class RenderTextureImpl { public: - //////////////////////////////////////////////////////////// /// \brief Default constructor /// diff --git a/src/SFML/Graphics/RenderTextureImplDefault.cpp b/src/SFML/Graphics/RenderTextureImplDefault.cpp index ef9b7d22f..6680ab693 100644 --- a/src/SFML/Graphics/RenderTextureImplDefault.cpp +++ b/src/SFML/Graphics/RenderTextureImplDefault.cpp @@ -25,11 +25,12 @@ //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// -#include #include +#include #include #include #include + #include @@ -38,11 +39,8 @@ namespace sf namespace priv { //////////////////////////////////////////////////////////// -RenderTextureImplDefault::RenderTextureImplDefault() : -m_context(), -m_size (0, 0) +RenderTextureImplDefault::RenderTextureImplDefault() : m_context(), m_size(0, 0) { - } @@ -95,7 +93,8 @@ void RenderTextureImplDefault::updateTexture(unsigned int textureId) // Copy the rendered pixels to the texture glCheck(glBindTexture(GL_TEXTURE_2D, textureId)); - glCheck(glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, 0, 0, static_cast(m_size.x), static_cast(m_size.y))); + glCheck( + glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, 0, 0, static_cast(m_size.x), static_cast(m_size.y))); } } // namespace priv diff --git a/src/SFML/Graphics/RenderTextureImplDefault.hpp b/src/SFML/Graphics/RenderTextureImplDefault.hpp index 40cca9dfd..8fedc39c0 100644 --- a/src/SFML/Graphics/RenderTextureImplDefault.hpp +++ b/src/SFML/Graphics/RenderTextureImplDefault.hpp @@ -30,6 +30,7 @@ //////////////////////////////////////////////////////////// #include #include + #include @@ -48,7 +49,6 @@ namespace priv class RenderTextureImplDefault : public RenderTextureImpl, GlResource { public: - //////////////////////////////////////////////////////////// /// \brief Default constructor /// @@ -70,7 +70,6 @@ public: static unsigned int getMaximumAntialiasingLevel(); private: - //////////////////////////////////////////////////////////// /// \brief Create the render texture implementation /// @@ -116,7 +115,7 @@ private: // Member data //////////////////////////////////////////////////////////// std::unique_ptr m_context; //!< P-Buffer based context - Vector2u m_size; //!< Width and height of the P-Buffer + Vector2u m_size; //!< Width and height of the P-Buffer }; } // namespace priv diff --git a/src/SFML/Graphics/RenderTextureImplFBO.cpp b/src/SFML/Graphics/RenderTextureImplFBO.cpp index 0d24c02cc..17df6fd19 100644 --- a/src/SFML/Graphics/RenderTextureImplFBO.cpp +++ b/src/SFML/Graphics/RenderTextureImplFBO.cpp @@ -25,90 +25,91 @@ //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// +#include #include #include -#include +#include #include #include -#include + #include +#include #include #include #include #include -#include namespace { - // Set to track all active FBO mappings - // This is used to free active FBOs while their owning - // RenderTextureImplFBO is still alive - std::unordered_set*> frameBuffers; +// Set to track all active FBO mappings +// This is used to free active FBOs while their owning +// RenderTextureImplFBO is still alive +std::unordered_set*> frameBuffers; - // Set to track all stale FBOs - // This is used to free stale FBOs after their owning - // RenderTextureImplFBO has already been destroyed - // An FBO cannot be destroyed until it's containing context - // becomes active, so the destruction of the RenderTextureImplFBO - // has to be decoupled from the destruction of the FBOs themselves - std::set > staleFrameBuffers; +// Set to track all stale FBOs +// This is used to free stale FBOs after their owning +// RenderTextureImplFBO has already been destroyed +// An FBO cannot be destroyed until it's containing context +// becomes active, so the destruction of the RenderTextureImplFBO +// has to be decoupled from the destruction of the FBOs themselves +std::set> staleFrameBuffers; - // Mutex to protect both active and stale frame buffer sets - std::recursive_mutex mutex; +// Mutex to protect both active and stale frame buffer sets +std::recursive_mutex mutex; - // This function is called either when a RenderTextureImplFBO is - // destroyed or via contextDestroyCallback when context destruction - // might trigger deletion of its contained stale FBOs - void destroyStaleFBOs() +// This function is called either when a RenderTextureImplFBO is +// destroyed or via contextDestroyCallback when context destruction +// might trigger deletion of its contained stale FBOs +void destroyStaleFBOs() +{ + sf::Uint64 contextId = sf::Context::getActiveContextId(); + + for (auto it = staleFrameBuffers.begin(); it != staleFrameBuffers.end();) { - sf::Uint64 contextId = sf::Context::getActiveContextId(); + if (it->first == contextId) + { + auto frameBuffer = static_cast(it->second); + glCheck(GLEXT_glDeleteFramebuffers(1, &frameBuffer)); - for (auto it = staleFrameBuffers.begin(); it != staleFrameBuffers.end();) + staleFrameBuffers.erase(it++); + } + else + { + ++it; + } + } +} + +// Callback that is called every time a context is destroyed +void contextDestroyCallback(void* /*arg*/) +{ + std::scoped_lock lock(mutex); + + sf::Uint64 contextId = sf::Context::getActiveContextId(); + + // Destroy active frame buffer objects + for (auto* frameBuffer : frameBuffers) + { + for (auto it = frameBuffer->begin(); it != frameBuffer->end(); ++it) { if (it->first == contextId) { - auto frameBuffer = static_cast(it->second); - glCheck(GLEXT_glDeleteFramebuffers(1, &frameBuffer)); + GLuint frameBufferId = it->second; + glCheck(GLEXT_glDeleteFramebuffers(1, &frameBufferId)); - staleFrameBuffers.erase(it++); - } - else - { - ++it; + // Erase the entry from the RenderTextureImplFBO's map + frameBuffer->erase(it); + + break; } } } - // Callback that is called every time a context is destroyed - void contextDestroyCallback(void* /*arg*/) - { - std::scoped_lock lock(mutex); - - sf::Uint64 contextId = sf::Context::getActiveContextId(); - - // Destroy active frame buffer objects - for (auto* frameBuffer : frameBuffers) - { - for (auto it = frameBuffer->begin(); it != frameBuffer->end(); ++it) - { - if (it->first == contextId) - { - GLuint frameBufferId = it->second; - glCheck(GLEXT_glDeleteFramebuffers(1, &frameBufferId)); - - // Erase the entry from the RenderTextureImplFBO's map - frameBuffer->erase(it); - - break; - } - } - } - - // Destroy stale frame buffer objects - destroyStaleFBOs(); - } + // Destroy stale frame buffer objects + destroyStaleFBOs(); } +} // namespace namespace sf @@ -118,13 +119,13 @@ namespace priv //////////////////////////////////////////////////////////// RenderTextureImplFBO::RenderTextureImplFBO() : m_depthStencilBuffer(0), -m_colorBuffer (0), -m_size (0, 0), -m_context (), -m_textureId (0), -m_multisample (false), -m_stencil (false), -m_sRgb (false) +m_colorBuffer(0), +m_size(0, 0), +m_context(), +m_textureId(0), +m_multisample(false), +m_stencil(false), +m_sRgb(false) { std::scoped_lock lock(mutex); @@ -262,21 +263,25 @@ bool RenderTextureImplFBO::create(const Vector2u& size, unsigned int textureId, m_depthStencilBuffer = depthStencil; if (!m_depthStencilBuffer) { - err() << "Impossible to create render texture (failed to create the attached depth/stencil buffer)" << std::endl; + err() << "Impossible to create render texture (failed to create the attached depth/stencil buffer)" + << std::endl; return false; } glCheck(GLEXT_glBindRenderbuffer(GLEXT_GL_RENDERBUFFER, m_depthStencilBuffer)); - glCheck(GLEXT_glRenderbufferStorage(GLEXT_GL_RENDERBUFFER, GLEXT_GL_DEPTH24_STENCIL8, static_cast(size.x), static_cast(size.y))); + glCheck(GLEXT_glRenderbufferStorage(GLEXT_GL_RENDERBUFFER, + GLEXT_GL_DEPTH24_STENCIL8, + static_cast(size.x), + static_cast(size.y))); #else - err() << "Impossible to create render texture (failed to create the attached depth/stencil buffer)" << std::endl; + err() << "Impossible to create render texture (failed to create the attached depth/stencil buffer)" + << std::endl; return false; #endif // SFML_OPENGL_ES m_stencil = true; - } else if (settings.depthBits) { @@ -285,11 +290,15 @@ bool RenderTextureImplFBO::create(const Vector2u& size, unsigned int textureId, m_depthStencilBuffer = depthStencil; if (!m_depthStencilBuffer) { - err() << "Impossible to create render texture (failed to create the attached depth buffer)" << std::endl; + err() << "Impossible to create render texture (failed to create the attached depth buffer)" + << std::endl; return false; } glCheck(GLEXT_glBindRenderbuffer(GLEXT_GL_RENDERBUFFER, m_depthStencilBuffer)); - glCheck(GLEXT_glRenderbufferStorage(GLEXT_GL_RENDERBUFFER, GLEXT_GL_DEPTH_COMPONENT, static_cast(size.x), static_cast(size.y))); + glCheck(GLEXT_glRenderbufferStorage(GLEXT_GL_RENDERBUFFER, + GLEXT_GL_DEPTH_COMPONENT, + static_cast(size.x), + static_cast(size.y))); } } else @@ -303,11 +312,16 @@ bool RenderTextureImplFBO::create(const Vector2u& size, unsigned int textureId, m_colorBuffer = color; if (!m_colorBuffer) { - err() << "Impossible to create render texture (failed to create the attached multisample color buffer)" << std::endl; + err() << "Impossible to create render texture (failed to create the attached multisample color buffer)" + << std::endl; return false; } glCheck(GLEXT_glBindRenderbuffer(GLEXT_GL_RENDERBUFFER, m_colorBuffer)); - glCheck(GLEXT_glRenderbufferStorageMultisample(GLEXT_GL_RENDERBUFFER, static_cast(settings.antialiasingLevel), m_sRgb ? GL_SRGB8_ALPHA8_EXT : GL_RGBA, static_cast(size.x), static_cast(size.y))); + glCheck(GLEXT_glRenderbufferStorageMultisample(GLEXT_GL_RENDERBUFFER, + static_cast(settings.antialiasingLevel), + m_sRgb ? GL_SRGB8_ALPHA8_EXT : GL_RGBA, + static_cast(size.x), + static_cast(size.y))); // Create the multisample depth/stencil buffer if requested if (settings.stencilBits) @@ -317,11 +331,17 @@ bool RenderTextureImplFBO::create(const Vector2u& size, unsigned int textureId, m_depthStencilBuffer = depthStencil; if (!m_depthStencilBuffer) { - err() << "Impossible to create render texture (failed to create the attached multisample depth/stencil buffer)" << std::endl; + err() << "Impossible to create render texture (failed to create the attached multisample " + "depth/stencil buffer)" + << std::endl; return false; } glCheck(GLEXT_glBindRenderbuffer(GLEXT_GL_RENDERBUFFER, m_depthStencilBuffer)); - glCheck(GLEXT_glRenderbufferStorageMultisample(GLEXT_GL_RENDERBUFFER, static_cast(settings.antialiasingLevel), GLEXT_GL_DEPTH24_STENCIL8, static_cast(size.x), static_cast(size.y))); + glCheck(GLEXT_glRenderbufferStorageMultisample(GLEXT_GL_RENDERBUFFER, + static_cast(settings.antialiasingLevel), + GLEXT_GL_DEPTH24_STENCIL8, + static_cast(size.x), + static_cast(size.y))); m_stencil = true; } @@ -332,11 +352,17 @@ bool RenderTextureImplFBO::create(const Vector2u& size, unsigned int textureId, m_depthStencilBuffer = depthStencil; if (!m_depthStencilBuffer) { - err() << "Impossible to create render texture (failed to create the attached multisample depth buffer)" << std::endl; + err() << "Impossible to create render texture (failed to create the attached multisample depth " + "buffer)" + << std::endl; return false; } glCheck(GLEXT_glBindRenderbuffer(GLEXT_GL_RENDERBUFFER, m_depthStencilBuffer)); - glCheck(GLEXT_glRenderbufferStorageMultisample(GLEXT_GL_RENDERBUFFER, static_cast(settings.antialiasingLevel), GLEXT_GL_DEPTH_COMPONENT, static_cast(size.x), static_cast(size.y))); + glCheck(GLEXT_glRenderbufferStorageMultisample(GLEXT_GL_RENDERBUFFER, + static_cast(settings.antialiasingLevel), + GLEXT_GL_DEPTH_COMPONENT, + static_cast(size.x), + static_cast(size.y))); } #else @@ -347,7 +373,6 @@ bool RenderTextureImplFBO::create(const Vector2u& size, unsigned int textureId, #endif // SFML_OPENGL_ES m_multisample = true; - } } @@ -414,17 +439,22 @@ bool RenderTextureImplFBO::createFrameBuffer() // Link the depth/stencil renderbuffer to the frame buffer if (!m_multisample && m_depthStencilBuffer) { - glCheck(GLEXT_glFramebufferRenderbuffer(GLEXT_GL_FRAMEBUFFER, GLEXT_GL_DEPTH_ATTACHMENT, GLEXT_GL_RENDERBUFFER, m_depthStencilBuffer)); + glCheck(GLEXT_glFramebufferRenderbuffer(GLEXT_GL_FRAMEBUFFER, + GLEXT_GL_DEPTH_ATTACHMENT, + GLEXT_GL_RENDERBUFFER, + m_depthStencilBuffer)); #ifndef SFML_OPENGL_ES if (m_stencil) { - glCheck(GLEXT_glFramebufferRenderbuffer(GLEXT_GL_FRAMEBUFFER, GLEXT_GL_STENCIL_ATTACHMENT, GLEXT_GL_RENDERBUFFER, m_depthStencilBuffer)); + glCheck(GLEXT_glFramebufferRenderbuffer(GLEXT_GL_FRAMEBUFFER, + GLEXT_GL_STENCIL_ATTACHMENT, + GLEXT_GL_RENDERBUFFER, + m_depthStencilBuffer)); } #endif - } // Link the texture to the frame buffer @@ -458,23 +488,31 @@ bool RenderTextureImplFBO::createFrameBuffer() if (!multisampleFrameBuffer) { - err() << "Impossible to create render texture (failed to create the multisample frame buffer object)" << std::endl; + err() << "Impossible to create render texture (failed to create the multisample frame buffer object)" + << std::endl; return false; } glCheck(GLEXT_glBindFramebuffer(GLEXT_GL_FRAMEBUFFER, multisampleFrameBuffer)); // Link the multisample color buffer to the frame buffer glCheck(GLEXT_glBindRenderbuffer(GLEXT_GL_RENDERBUFFER, m_colorBuffer)); - glCheck(GLEXT_glFramebufferRenderbuffer(GLEXT_GL_FRAMEBUFFER, GLEXT_GL_COLOR_ATTACHMENT0, GLEXT_GL_RENDERBUFFER, m_colorBuffer)); + glCheck( + GLEXT_glFramebufferRenderbuffer(GLEXT_GL_FRAMEBUFFER, GLEXT_GL_COLOR_ATTACHMENT0, GLEXT_GL_RENDERBUFFER, m_colorBuffer)); // Link the depth/stencil renderbuffer to the frame buffer if (m_depthStencilBuffer) { - glCheck(GLEXT_glFramebufferRenderbuffer(GLEXT_GL_FRAMEBUFFER, GLEXT_GL_DEPTH_ATTACHMENT, GLEXT_GL_RENDERBUFFER, m_depthStencilBuffer)); + glCheck(GLEXT_glFramebufferRenderbuffer(GLEXT_GL_FRAMEBUFFER, + GLEXT_GL_DEPTH_ATTACHMENT, + GLEXT_GL_RENDERBUFFER, + m_depthStencilBuffer)); if (m_stencil) { - glCheck(GLEXT_glFramebufferRenderbuffer(GLEXT_GL_FRAMEBUFFER, GLEXT_GL_STENCIL_ATTACHMENT, GLEXT_GL_RENDERBUFFER, m_depthStencilBuffer)); + glCheck(GLEXT_glFramebufferRenderbuffer(GLEXT_GL_FRAMEBUFFER, + GLEXT_GL_STENCIL_ATTACHMENT, + GLEXT_GL_RENDERBUFFER, + m_depthStencilBuffer)); } } @@ -484,7 +522,9 @@ bool RenderTextureImplFBO::createFrameBuffer() { glCheck(GLEXT_glBindFramebuffer(GLEXT_GL_FRAMEBUFFER, 0)); glCheck(GLEXT_glDeleteFramebuffers(1, &multisampleFrameBuffer)); - err() << "Impossible to create render texture (failed to link the render buffers to the multisample frame buffer)" << std::endl; + err() << "Impossible to create render texture (failed to link the render buffers to the multisample frame " + "buffer)" + << std::endl; return false; } @@ -603,13 +643,21 @@ void RenderTextureImplFBO::updateTexture(unsigned int) { // Set up the blit target (draw framebuffer) and blit (from the read framebuffer, our multisample FBO) glCheck(GLEXT_glBindFramebuffer(GLEXT_GL_DRAW_FRAMEBUFFER, frameBufferIt->second)); - glCheck(GLEXT_glBlitFramebuffer(0, 0, static_cast(m_size.x), static_cast(m_size.y), 0, 0, static_cast(m_size.x), static_cast(m_size.y), GL_COLOR_BUFFER_BIT, GL_NEAREST)); + glCheck(GLEXT_glBlitFramebuffer(0, + 0, + static_cast(m_size.x), + static_cast(m_size.y), + 0, + 0, + static_cast(m_size.x), + static_cast(m_size.y), + GL_COLOR_BUFFER_BIT, + GL_NEAREST)); glCheck(GLEXT_glBindFramebuffer(GLEXT_GL_DRAW_FRAMEBUFFER, multisampleIt->second)); } } #endif // SFML_OPENGL_ES - } } // namespace priv diff --git a/src/SFML/Graphics/RenderTextureImplFBO.hpp b/src/SFML/Graphics/RenderTextureImplFBO.hpp index c376716b6..775e47d42 100644 --- a/src/SFML/Graphics/RenderTextureImplFBO.hpp +++ b/src/SFML/Graphics/RenderTextureImplFBO.hpp @@ -30,8 +30,9 @@ //////////////////////////////////////////////////////////// #include #include -#include + #include +#include namespace sf @@ -49,7 +50,6 @@ namespace priv class RenderTextureImplFBO : public RenderTextureImpl, GlResource { public: - //////////////////////////////////////////////////////////// /// \brief Default constructor /// @@ -85,7 +85,6 @@ public: static void unbind(); private: - //////////////////////////////////////////////////////////// /// \brief Create the render texture implementation /// @@ -138,16 +137,16 @@ private: //////////////////////////////////////////////////////////// // Member data //////////////////////////////////////////////////////////// - std::unordered_map m_frameBuffers; //!< OpenGL frame buffer objects per context + std::unordered_map m_frameBuffers; //!< OpenGL frame buffer objects per context std::unordered_map m_multisampleFrameBuffers; //!< Optional per-context OpenGL frame buffer objects with multisample attachments - unsigned int m_depthStencilBuffer; //!< Optional depth/stencil buffer attached to the frame buffer - unsigned int m_colorBuffer; //!< Optional multisample color buffer attached to the frame buffer - Vector2u m_size; //!< Width and height of the attachments - std::unique_ptr m_context; //!< Backup OpenGL context, used when none already exist - unsigned int m_textureId; //!< The ID of the texture to attach to the FBO - bool m_multisample; //!< Whether we have to create a multisample frame buffer as well - bool m_stencil; //!< Whether we have stencil attachment - bool m_sRgb; //!< Whether we need to encode drawn pixels into sRGB color space + unsigned int m_depthStencilBuffer; //!< Optional depth/stencil buffer attached to the frame buffer + unsigned int m_colorBuffer; //!< Optional multisample color buffer attached to the frame buffer + Vector2u m_size; //!< Width and height of the attachments + std::unique_ptr m_context; //!< Backup OpenGL context, used when none already exist + unsigned int m_textureId; //!< The ID of the texture to attach to the FBO + bool m_multisample; //!< Whether we have to create a multisample frame buffer as well + bool m_stencil; //!< Whether we have stencil attachment + bool m_sRgb; //!< Whether we need to encode drawn pixels into sRGB color space }; } // namespace priv diff --git a/src/SFML/Graphics/RenderWindow.cpp b/src/SFML/Graphics/RenderWindow.cpp index 78f2f5feb..5b5a4f87f 100644 --- a/src/SFML/Graphics/RenderWindow.cpp +++ b/src/SFML/Graphics/RenderWindow.cpp @@ -25,18 +25,17 @@ //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// -#include -#include -#include #include #include +#include +#include +#include namespace sf { //////////////////////////////////////////////////////////// -RenderWindow::RenderWindow() : -m_defaultFrameBuffer(0) +RenderWindow::RenderWindow() : m_defaultFrameBuffer(0) { // Nothing to do } @@ -52,8 +51,7 @@ m_defaultFrameBuffer(0) //////////////////////////////////////////////////////////// -RenderWindow::RenderWindow(WindowHandle handle, const ContextSettings& settings) : -m_defaultFrameBuffer(0) +RenderWindow::RenderWindow(WindowHandle handle, const ContextSettings& settings) : m_defaultFrameBuffer(0) { // Don't call the base class constructor because it contains virtual function calls Window::create(handle, settings); diff --git a/src/SFML/Graphics/Shader.cpp b/src/SFML/Graphics/Shader.cpp index 6e8da5b66..9a6d4cfc4 100644 --- a/src/SFML/Graphics/Shader.cpp +++ b/src/SFML/Graphics/Shader.cpp @@ -26,152 +26,153 @@ //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// +#include +#include #include #include #include -#include -#include -#include -#include #include +#include #include +#include + #include #include -#include #include #include +#include #ifndef SFML_OPENGL_ES #if defined(SFML_SYSTEM_MACOS) || defined(SFML_SYSTEM_IOS) - #define castToGlHandle(x) reinterpret_cast(static_cast(x)) - #define castFromGlHandle(x) static_cast(reinterpret_cast(x)) +#define castToGlHandle(x) reinterpret_cast(static_cast(x)) +#define castFromGlHandle(x) static_cast(reinterpret_cast(x)) #else - #define castToGlHandle(x) (x) - #define castFromGlHandle(x) (x) +#define castToGlHandle(x) (x) +#define castFromGlHandle(x) (x) #endif namespace { - std::recursive_mutex isAvailableMutex; +std::recursive_mutex isAvailableMutex; - GLint checkMaxTextureUnits() +GLint checkMaxTextureUnits() +{ + GLint maxUnits = 0; + glCheck(glGetIntegerv(GLEXT_GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, &maxUnits)); + + return maxUnits; +} + +// Retrieve the maximum number of texture units available +std::size_t getMaxTextureUnits() +{ + static GLint maxUnits = checkMaxTextureUnits(); + return static_cast(maxUnits); +} + +// Read the contents of a file into an array of char +bool getFileContents(const std::filesystem::path& filename, std::vector& buffer) +{ + std::ifstream file(filename.c_str(), std::ios_base::binary); + if (file) { - GLint maxUnits = 0; - glCheck(glGetIntegerv(GLEXT_GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, &maxUnits)); - - return maxUnits; - } - - // Retrieve the maximum number of texture units available - std::size_t getMaxTextureUnits() - { - static GLint maxUnits = checkMaxTextureUnits(); - return static_cast(maxUnits); - } - - // Read the contents of a file into an array of char - bool getFileContents(const std::filesystem::path& filename, std::vector& buffer) - { - std::ifstream file(filename.c_str(), std::ios_base::binary); - if (file) - { - file.seekg(0, std::ios_base::end); - std::ifstream::pos_type size = file.tellg(); - if (size > 0) - { - file.seekg(0, std::ios_base::beg); - buffer.resize(static_cast(size)); - file.read(buffer.data(), static_cast(size)); - } - buffer.push_back('\0'); - return true; - } - else - { - return false; - } - } - - // Read the contents of a stream into an array of char - bool getStreamContents(sf::InputStream& stream, std::vector& buffer) - { - bool success = true; - sf::Int64 size = stream.getSize(); + file.seekg(0, std::ios_base::end); + std::ifstream::pos_type size = file.tellg(); if (size > 0) { + file.seekg(0, std::ios_base::beg); buffer.resize(static_cast(size)); - - if (stream.seek(0) == -1) - { - sf::err() << "Failed to seek shader stream" << std::endl; - return false; - } - - sf::Int64 read = stream.read(buffer.data(), size); - success = (read == size); + file.read(buffer.data(), static_cast(size)); } buffer.push_back('\0'); - return success; + return true; } - - // Transforms an array of 2D vectors into a contiguous array of scalars - template - std::vector flatten(const sf::Vector2* vectorArray, std::size_t length) + else { - const std::size_t vectorSize = 2; - - std::vector contiguous(vectorSize * length); - for (std::size_t i = 0; i < length; ++i) - { - contiguous[vectorSize * i] = vectorArray[i].x; - contiguous[vectorSize * i + 1] = vectorArray[i].y; - } - - return contiguous; - } - - // Transforms an array of 3D vectors into a contiguous array of scalars - template - std::vector flatten(const sf::Vector3* vectorArray, std::size_t length) - { - const std::size_t vectorSize = 3; - - std::vector contiguous(vectorSize * length); - for (std::size_t i = 0; i < length; ++i) - { - contiguous[vectorSize * i] = vectorArray[i].x; - contiguous[vectorSize * i + 1] = vectorArray[i].y; - contiguous[vectorSize * i + 2] = vectorArray[i].z; - } - - return contiguous; - } - - // Transforms an array of 4D vectors into a contiguous array of scalars - template - std::vector flatten(const sf::priv::Vector4* vectorArray, std::size_t length) - { - const std::size_t vectorSize = 4; - - std::vector contiguous(vectorSize * length); - for (std::size_t i = 0; i < length; ++i) - { - contiguous[vectorSize * i] = vectorArray[i].x; - contiguous[vectorSize * i + 1] = vectorArray[i].y; - contiguous[vectorSize * i + 2] = vectorArray[i].z; - contiguous[vectorSize * i + 3] = vectorArray[i].w; - } - - return contiguous; + return false; } } +// Read the contents of a stream into an array of char +bool getStreamContents(sf::InputStream& stream, std::vector& buffer) +{ + bool success = true; + sf::Int64 size = stream.getSize(); + if (size > 0) + { + buffer.resize(static_cast(size)); + + if (stream.seek(0) == -1) + { + sf::err() << "Failed to seek shader stream" << std::endl; + return false; + } + + sf::Int64 read = stream.read(buffer.data(), size); + success = (read == size); + } + buffer.push_back('\0'); + return success; +} + +// Transforms an array of 2D vectors into a contiguous array of scalars +template +std::vector flatten(const sf::Vector2* vectorArray, std::size_t length) +{ + const std::size_t vectorSize = 2; + + std::vector contiguous(vectorSize * length); + for (std::size_t i = 0; i < length; ++i) + { + contiguous[vectorSize * i] = vectorArray[i].x; + contiguous[vectorSize * i + 1] = vectorArray[i].y; + } + + return contiguous; +} + +// Transforms an array of 3D vectors into a contiguous array of scalars +template +std::vector flatten(const sf::Vector3* vectorArray, std::size_t length) +{ + const std::size_t vectorSize = 3; + + std::vector contiguous(vectorSize * length); + for (std::size_t i = 0; i < length; ++i) + { + contiguous[vectorSize * i] = vectorArray[i].x; + contiguous[vectorSize * i + 1] = vectorArray[i].y; + contiguous[vectorSize * i + 2] = vectorArray[i].z; + } + + return contiguous; +} + +// Transforms an array of 4D vectors into a contiguous array of scalars +template +std::vector flatten(const sf::priv::Vector4* vectorArray, std::size_t length) +{ + const std::size_t vectorSize = 4; + + std::vector contiguous(vectorSize * length); + for (std::size_t i = 0; i < length; ++i) + { + contiguous[vectorSize * i] = vectorArray[i].x; + contiguous[vectorSize * i + 1] = vectorArray[i].y; + contiguous[vectorSize * i + 2] = vectorArray[i].z; + contiguous[vectorSize * i + 3] = vectorArray[i].w; + } + + return contiguous; +} +} // namespace + namespace sf { @@ -234,11 +235,7 @@ struct Shader::UniformBinder //////////////////////////////////////////////////////////// -Shader::Shader() : -m_shaderProgram (0), -m_currentTexture(-1), -m_textures (), -m_uniforms () +Shader::Shader() : m_shaderProgram(0), m_currentTexture(-1), m_textures(), m_uniforms() { } @@ -276,7 +273,8 @@ bool Shader::loadFromFile(const std::filesystem::path& filename, Type type) //////////////////////////////////////////////////////////// -bool Shader::loadFromFile(const std::filesystem::path& vertexShaderFilename, const std::filesystem::path& fragmentShaderFilename) +bool Shader::loadFromFile(const std::filesystem::path& vertexShaderFilename, + const std::filesystem::path& fragmentShaderFilename) { // Read the vertex shader file std::vector vertexShader; @@ -300,7 +298,9 @@ bool Shader::loadFromFile(const std::filesystem::path& vertexShaderFilename, con //////////////////////////////////////////////////////////// -bool Shader::loadFromFile(const std::filesystem::path& vertexShaderFilename, const std::filesystem::path& geometryShaderFilename, const std::filesystem::path& fragmentShaderFilename) +bool Shader::loadFromFile(const std::filesystem::path& vertexShaderFilename, + const std::filesystem::path& geometryShaderFilename, + const std::filesystem::path& fragmentShaderFilename) { // Read the vertex shader file std::vector vertexShader; @@ -573,7 +573,8 @@ void Shader::setUniform(const std::string& name, const Texture& texture) // New entry, make sure there are enough texture units if (m_textures.size() + 1 >= getMaxTextureUnits()) { - err() << "Impossible to use texture " << std::quoted(name) << " for shader: all available texture units are used" << std::endl; + err() << "Impossible to use texture " << std::quoted(name) + << " for shader: all available texture units are used" << std::endl; return; } @@ -719,7 +720,7 @@ bool Shader::isAvailable() { std::scoped_lock lock(isAvailableMutex); - static bool checked = false; + static bool checked = false; static bool available = false; if (!checked) @@ -731,10 +732,7 @@ bool Shader::isAvailable() // Make sure that extensions are initialized sf::priv::ensureExtensionsInit(); - available = GLEXT_multitexture && - GLEXT_shading_language_100 && - GLEXT_shader_objects && - GLEXT_vertex_shader && + available = GLEXT_multitexture && GLEXT_shading_language_100 && GLEXT_shader_objects && GLEXT_vertex_shader && GLEXT_fragment_shader; } @@ -747,7 +745,7 @@ bool Shader::isGeometryAvailable() { std::scoped_lock lock(isAvailableMutex); - static bool checked = false; + static bool checked = false; static bool available = false; if (!checked) @@ -819,8 +817,7 @@ bool Shader::compile(const char* vertexShaderCode, const char* geometryShaderCod { char log[1024]; glCheck(GLEXT_glGetInfoLog(vertexShader, sizeof(log), nullptr, log)); - err() << "Failed to compile vertex shader:" << '\n' - << log << std::endl; + err() << "Failed to compile vertex shader:" << '\n' << log << std::endl; glCheck(GLEXT_glDeleteObject(vertexShader)); glCheck(GLEXT_glDeleteObject(shaderProgram)); return false; @@ -846,8 +843,7 @@ bool Shader::compile(const char* vertexShaderCode, const char* geometryShaderCod { char log[1024]; glCheck(GLEXT_glGetInfoLog(geometryShader, sizeof(log), nullptr, log)); - err() << "Failed to compile geometry shader:" << '\n' - << log << std::endl; + err() << "Failed to compile geometry shader:" << '\n' << log << std::endl; glCheck(GLEXT_glDeleteObject(geometryShader)); glCheck(GLEXT_glDeleteObject(shaderProgram)); return false; @@ -874,8 +870,7 @@ bool Shader::compile(const char* vertexShaderCode, const char* geometryShaderCod { char log[1024]; glCheck(GLEXT_glGetInfoLog(fragmentShader, sizeof(log), nullptr, log)); - err() << "Failed to compile fragment shader:" << '\n' - << log << std::endl; + err() << "Failed to compile fragment shader:" << '\n' << log << std::endl; glCheck(GLEXT_glDeleteObject(fragmentShader)); glCheck(GLEXT_glDeleteObject(shaderProgram)); return false; @@ -896,8 +891,7 @@ bool Shader::compile(const char* vertexShaderCode, const char* geometryShaderCod { char log[1024]; glCheck(GLEXT_glGetInfoLog(shaderProgram, sizeof(log), nullptr, log)); - err() << "Failed to link shader:" << '\n' - << log << std::endl; + err() << "Failed to link shader:" << '\n' << log << std::endl; glCheck(GLEXT_glDeleteObject(shaderProgram)); return false; } @@ -965,9 +959,7 @@ Shader::CurrentTextureType Shader::CurrentTexture; //////////////////////////////////////////////////////////// -Shader::Shader() : -m_shaderProgram (0), -m_currentTexture(-1) +Shader::Shader() : m_shaderProgram(0), m_currentTexture(-1) { } @@ -986,14 +978,17 @@ bool Shader::loadFromFile(const std::filesystem::path& /* filename */, Type /* t //////////////////////////////////////////////////////////// -bool Shader::loadFromFile(const std::filesystem::path& /* vertexShaderFilename */, const std::filesystem::path& /* fragmentShaderFilename */) +bool Shader::loadFromFile(const std::filesystem::path& /* vertexShaderFilename */, + const std::filesystem::path& /* fragmentShaderFilename */) { return false; } //////////////////////////////////////////////////////////// -bool Shader::loadFromFile(const std::filesystem::path& /* vertexShaderFilename */, const std::filesystem::path& /* geometryShaderFilename */, const std::filesystem::path& /* fragmentShaderFilename */) +bool Shader::loadFromFile(const std::filesystem::path& /* vertexShaderFilename */, + const std::filesystem::path& /* geometryShaderFilename */, + const std::filesystem::path& /* fragmentShaderFilename */) { return false; } @@ -1014,7 +1009,9 @@ bool Shader::loadFromMemory(const std::string& /* vertexShader */, const std::st //////////////////////////////////////////////////////////// -bool Shader::loadFromMemory(const std::string& /* vertexShader */, const std::string& /* geometryShader */, const std::string& /* fragmentShader */) +bool Shader::loadFromMemory(const std::string& /* vertexShader */, + const std::string& /* geometryShader */, + const std::string& /* fragmentShader */) { return false; } @@ -1035,7 +1032,9 @@ bool Shader::loadFromStream(InputStream& /* vertexShaderStream */, InputStream& //////////////////////////////////////////////////////////// -bool Shader::loadFromStream(InputStream& /* vertexShaderStream */, InputStream& /* geometryShaderStream */, InputStream& /* fragmentShaderStream */) +bool Shader::loadFromStream(InputStream& /* vertexShaderStream */, + InputStream& /* geometryShaderStream */, + InputStream& /* fragmentShaderStream */) { return false; } diff --git a/src/SFML/Graphics/Shape.cpp b/src/SFML/Graphics/Shape.cpp index 1d9a1c277..0515acd4d 100644 --- a/src/SFML/Graphics/Shape.cpp +++ b/src/SFML/Graphics/Shape.cpp @@ -25,24 +25,25 @@ //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// -#include #include +#include #include + #include namespace { - // Compute the normal of a segment - sf::Vector2f computeNormal(const sf::Vector2f& p1, const sf::Vector2f& p2) - { - sf::Vector2f normal = (p2 - p1).perpendicular(); - float length = normal.length(); - if (length != 0.f) - normal /= length; - return normal; - } +// Compute the normal of a segment +sf::Vector2f computeNormal(const sf::Vector2f& p1, const sf::Vector2f& p2) +{ + sf::Vector2f normal = (p2 - p1).perpendicular(); + float length = normal.length(); + if (length != 0.f) + normal /= length; + return normal; } +} // namespace namespace sf @@ -149,15 +150,15 @@ FloatRect Shape::getGlobalBounds() const //////////////////////////////////////////////////////////// Shape::Shape() : -m_texture (nullptr), -m_textureRect (), -m_fillColor (255, 255, 255), -m_outlineColor (255, 255, 255), +m_texture(nullptr), +m_textureRect(), +m_fillColor(255, 255, 255), +m_outlineColor(255, 255, 255), m_outlineThickness(0), -m_vertices (TriangleFan), -m_outlineVertices (TriangleStrip), -m_insideBounds (), -m_bounds () +m_vertices(TriangleFan), +m_outlineVertices(TriangleStrip), +m_insideBounds(), +m_bounds() { } @@ -182,7 +183,7 @@ void Shape::update() m_vertices[count + 1].position = m_vertices[1].position; // Update the bounding rectangle - m_vertices[0] = m_vertices[1]; // so that the result of getBounds() is correct + m_vertices[0] = m_vertices[1]; // so that the result of getBounds() is correct m_insideBounds = m_vertices.getBounds(); // Compute the center and make it the first vertex @@ -236,7 +237,8 @@ void Shape::updateTexCoords() for (std::size_t i = 0; i < m_vertices.getVertexCount(); ++i) { float xratio = m_insideBounds.width > 0 ? (m_vertices[i].position.x - m_insideBounds.left) / m_insideBounds.width : 0; - float yratio = m_insideBounds.height > 0 ? (m_vertices[i].position.y - m_insideBounds.top) / m_insideBounds.height : 0; + float yratio = m_insideBounds.height > 0 ? (m_vertices[i].position.y - m_insideBounds.top) / m_insideBounds.height + : 0; m_vertices[i].texCoords.x = convertedTextureRect.left + convertedTextureRect.width * xratio; m_vertices[i].texCoords.y = convertedTextureRect.top + convertedTextureRect.height * yratio; } @@ -278,7 +280,7 @@ void Shape::updateOutline() n2 = -n2; // Combine them to get the extrusion direction - float factor = 1.f + (n1.x * n2.x + n1.y * n2.y); + float factor = 1.f + (n1.x * n2.x + n1.y * n2.y); Vector2f normal = (n1 + n2) / factor; // Update the outline points diff --git a/src/SFML/Graphics/Sprite.cpp b/src/SFML/Graphics/Sprite.cpp index a3bdefa43..49a3f35a5 100644 --- a/src/SFML/Graphics/Sprite.cpp +++ b/src/SFML/Graphics/Sprite.cpp @@ -25,35 +25,30 @@ //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// +#include #include #include -#include + #include namespace sf { //////////////////////////////////////////////////////////// -Sprite::Sprite() : -m_texture (nullptr), -m_textureRect() +Sprite::Sprite() : m_texture(nullptr), m_textureRect() { } //////////////////////////////////////////////////////////// -Sprite::Sprite(const Texture& texture) : -m_texture (nullptr), -m_textureRect() +Sprite::Sprite(const Texture& texture) : m_texture(nullptr), m_textureRect() { setTexture(texture, true); } //////////////////////////////////////////////////////////// -Sprite::Sprite(const Texture& texture, const IntRect& rectangle) : -m_texture (nullptr), -m_textureRect() +Sprite::Sprite(const Texture& texture, const IntRect& rectangle) : m_texture(nullptr), m_textureRect() { // Compute the texture area setTextureRect(rectangle); @@ -123,7 +118,7 @@ const Color& Sprite::getColor() const //////////////////////////////////////////////////////////// FloatRect Sprite::getLocalBounds() const { - auto width = static_cast(std::abs(m_textureRect.width)); + auto width = static_cast(std::abs(m_textureRect.width)); auto height = static_cast(std::abs(m_textureRect.height)); return FloatRect({0.f, 0.f}, {width, height}); diff --git a/src/SFML/Graphics/Text.cpp b/src/SFML/Graphics/Text.cpp index f7e0d7f96..8d3f89e2a 100644 --- a/src/SFML/Graphics/Text.cpp +++ b/src/SFML/Graphics/Text.cpp @@ -25,96 +25,111 @@ //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// +#include +#include #include #include -#include -#include + #include #include namespace { - // Add an underline or strikethrough line to the vertex array - void addLine(sf::VertexArray& vertices, float lineLength, float lineTop, const sf::Color& color, float offset, float thickness, float outlineThickness = 0) - { - float top = std::floor(lineTop + offset - (thickness / 2) + 0.5f); - float bottom = top + std::floor(thickness + 0.5f); +// Add an underline or strikethrough line to the vertex array +void addLine(sf::VertexArray& vertices, + float lineLength, + float lineTop, + const sf::Color& color, + float offset, + float thickness, + float outlineThickness = 0) +{ + float top = std::floor(lineTop + offset - (thickness / 2) + 0.5f); + float bottom = top + std::floor(thickness + 0.5f); - vertices.append(sf::Vertex(sf::Vector2f(-outlineThickness, top - outlineThickness), color, sf::Vector2f(1, 1))); - vertices.append(sf::Vertex(sf::Vector2f(lineLength + outlineThickness, top - outlineThickness), color, sf::Vector2f(1, 1))); - vertices.append(sf::Vertex(sf::Vector2f(-outlineThickness, bottom + outlineThickness), color, sf::Vector2f(1, 1))); - vertices.append(sf::Vertex(sf::Vector2f(-outlineThickness, bottom + outlineThickness), color, sf::Vector2f(1, 1))); - vertices.append(sf::Vertex(sf::Vector2f(lineLength + outlineThickness, top - outlineThickness), color, sf::Vector2f(1, 1))); - vertices.append(sf::Vertex(sf::Vector2f(lineLength + outlineThickness, bottom + outlineThickness), color, sf::Vector2f(1, 1))); - } - - // Add a glyph quad to the vertex array - void addGlyphQuad(sf::VertexArray& vertices, sf::Vector2f position, const sf::Color& color, const sf::Glyph& glyph, float italicShear) - { - float padding = 1.0; - - float left = glyph.bounds.left - padding; - float top = glyph.bounds.top - padding; - float right = glyph.bounds.left + glyph.bounds.width + padding; - float bottom = glyph.bounds.top + glyph.bounds.height + padding; - - float u1 = static_cast(glyph.textureRect.left) - padding; - float v1 = static_cast(glyph.textureRect.top) - padding; - float u2 = static_cast(glyph.textureRect.left + glyph.textureRect.width) + padding; - float v2 = static_cast(glyph.textureRect.top + glyph.textureRect.height) + padding; - - vertices.append(sf::Vertex(sf::Vector2f(position.x + left - italicShear * top , position.y + top), color, sf::Vector2f(u1, v1))); - vertices.append(sf::Vertex(sf::Vector2f(position.x + right - italicShear * top , position.y + top), color, sf::Vector2f(u2, v1))); - vertices.append(sf::Vertex(sf::Vector2f(position.x + left - italicShear * bottom, position.y + bottom), color, sf::Vector2f(u1, v2))); - vertices.append(sf::Vertex(sf::Vector2f(position.x + left - italicShear * bottom, position.y + bottom), color, sf::Vector2f(u1, v2))); - vertices.append(sf::Vertex(sf::Vector2f(position.x + right - italicShear * top , position.y + top), color, sf::Vector2f(u2, v1))); - vertices.append(sf::Vertex(sf::Vector2f(position.x + right - italicShear * bottom, position.y + bottom), color, sf::Vector2f(u2, v2))); - } + vertices.append(sf::Vertex(sf::Vector2f(-outlineThickness, top - outlineThickness), color, sf::Vector2f(1, 1))); + vertices.append( + sf::Vertex(sf::Vector2f(lineLength + outlineThickness, top - outlineThickness), color, sf::Vector2f(1, 1))); + vertices.append(sf::Vertex(sf::Vector2f(-outlineThickness, bottom + outlineThickness), color, sf::Vector2f(1, 1))); + vertices.append(sf::Vertex(sf::Vector2f(-outlineThickness, bottom + outlineThickness), color, sf::Vector2f(1, 1))); + vertices.append( + sf::Vertex(sf::Vector2f(lineLength + outlineThickness, top - outlineThickness), color, sf::Vector2f(1, 1))); + vertices.append( + sf::Vertex(sf::Vector2f(lineLength + outlineThickness, bottom + outlineThickness), color, sf::Vector2f(1, 1))); } +// Add a glyph quad to the vertex array +void addGlyphQuad(sf::VertexArray& vertices, sf::Vector2f position, const sf::Color& color, const sf::Glyph& glyph, float italicShear) +{ + float padding = 1.0; + + float left = glyph.bounds.left - padding; + float top = glyph.bounds.top - padding; + float right = glyph.bounds.left + glyph.bounds.width + padding; + float bottom = glyph.bounds.top + glyph.bounds.height + padding; + + float u1 = static_cast(glyph.textureRect.left) - padding; + float v1 = static_cast(glyph.textureRect.top) - padding; + float u2 = static_cast(glyph.textureRect.left + glyph.textureRect.width) + padding; + float v2 = static_cast(glyph.textureRect.top + glyph.textureRect.height) + padding; + + vertices.append( + sf::Vertex(sf::Vector2f(position.x + left - italicShear * top, position.y + top), color, sf::Vector2f(u1, v1))); + vertices.append( + sf::Vertex(sf::Vector2f(position.x + right - italicShear * top, position.y + top), color, sf::Vector2f(u2, v1))); + vertices.append( + sf::Vertex(sf::Vector2f(position.x + left - italicShear * bottom, position.y + bottom), color, sf::Vector2f(u1, v2))); + vertices.append( + sf::Vertex(sf::Vector2f(position.x + left - italicShear * bottom, position.y + bottom), color, sf::Vector2f(u1, v2))); + vertices.append( + sf::Vertex(sf::Vector2f(position.x + right - italicShear * top, position.y + top), color, sf::Vector2f(u2, v1))); + vertices.append(sf::Vertex(sf::Vector2f(position.x + right - italicShear * bottom, position.y + bottom), + color, + sf::Vector2f(u2, v2))); +} +} // namespace + namespace sf { //////////////////////////////////////////////////////////// Text::Text() : -m_string (), -m_font (nullptr), -m_characterSize (30), +m_string(), +m_font(nullptr), +m_characterSize(30), m_letterSpacingFactor(1.f), -m_lineSpacingFactor (1.f), -m_style (Regular), -m_fillColor (255, 255, 255), -m_outlineColor (0, 0, 0), -m_outlineThickness (0), -m_vertices (Triangles), -m_outlineVertices (Triangles), -m_bounds (), -m_geometryNeedUpdate (false), -m_fontTextureId (0) +m_lineSpacingFactor(1.f), +m_style(Regular), +m_fillColor(255, 255, 255), +m_outlineColor(0, 0, 0), +m_outlineThickness(0), +m_vertices(Triangles), +m_outlineVertices(Triangles), +m_bounds(), +m_geometryNeedUpdate(false), +m_fontTextureId(0) { - } //////////////////////////////////////////////////////////// Text::Text(const String& string, const Font& font, unsigned int characterSize) : -m_string (string), -m_font (&font), -m_characterSize (characterSize), +m_string(string), +m_font(&font), +m_characterSize(characterSize), m_letterSpacingFactor(1.f), -m_lineSpacingFactor (1.f), -m_style (Regular), -m_fillColor (255, 255, 255), -m_outlineColor (0, 0, 0), -m_outlineThickness (0), -m_vertices (Triangles), -m_outlineVertices (Triangles), -m_bounds (), -m_geometryNeedUpdate (true), -m_fontTextureId (0) +m_lineSpacingFactor(1.f), +m_style(Regular), +m_fillColor(255, 255, 255), +m_outlineColor(0, 0, 0), +m_outlineThickness(0), +m_vertices(Triangles), +m_outlineVertices(Triangles), +m_bounds(), +m_geometryNeedUpdate(true), +m_fontTextureId(0) { - } @@ -139,7 +154,7 @@ void Text::setString(const String& string) { if (m_string != string) { - m_string = string; + m_string = string; m_geometryNeedUpdate = true; } } @@ -150,7 +165,7 @@ void Text::setFont(const Font& font) { if (m_font != &font) { - m_font = &font; + m_font = &font; m_geometryNeedUpdate = true; } } @@ -161,7 +176,7 @@ void Text::setCharacterSize(unsigned int size) { if (m_characterSize != size) { - m_characterSize = size; + m_characterSize = size; m_geometryNeedUpdate = true; } } @@ -173,7 +188,7 @@ void Text::setLetterSpacing(float spacingFactor) if (m_letterSpacingFactor != spacingFactor) { m_letterSpacingFactor = spacingFactor; - m_geometryNeedUpdate = true; + m_geometryNeedUpdate = true; } } @@ -183,7 +198,7 @@ void Text::setLineSpacing(float spacingFactor) { if (m_lineSpacingFactor != spacingFactor) { - m_lineSpacingFactor = spacingFactor; + m_lineSpacingFactor = spacingFactor; m_geometryNeedUpdate = true; } } @@ -194,7 +209,7 @@ void Text::setStyle(Uint32 style) { if (m_style != style) { - m_style = style; + m_style = style; m_geometryNeedUpdate = true; } } @@ -241,7 +256,7 @@ void Text::setOutlineThickness(float thickness) { if (thickness != m_outlineThickness) { - m_outlineThickness = thickness; + m_outlineThickness = thickness; m_geometryNeedUpdate = true; } } @@ -324,13 +339,13 @@ Vector2f Text::findCharacterPos(std::size_t index) const // Precompute the variables needed by the algorithm bool isBold = m_style & Bold; float whitespaceWidth = m_font->getGlyph(U' ', m_characterSize, isBold).advance; - float letterSpacing = ( whitespaceWidth / 3.f ) * ( m_letterSpacingFactor - 1.f ); - whitespaceWidth += letterSpacing; - float lineSpacing = m_font->getLineSpacing(m_characterSize) * m_lineSpacingFactor; + float letterSpacing = (whitespaceWidth / 3.f) * (m_letterSpacingFactor - 1.f); + whitespaceWidth += letterSpacing; + float lineSpacing = m_font->getLineSpacing(m_characterSize) * m_lineSpacingFactor; // Compute the position Vector2f position; - Uint32 prevChar = 0; + Uint32 prevChar = 0; for (std::size_t i = 0; i < index; ++i) { Uint32 curChar = m_string[i]; @@ -342,9 +357,16 @@ Vector2f Text::findCharacterPos(std::size_t index) const // Handle special characters switch (curChar) { - case U' ': position.x += whitespaceWidth; continue; - case U'\t': position.x += whitespaceWidth * 4; continue; - case U'\n': position.y += lineSpacing; position.x = 0; continue; + case U' ': + position.x += whitespaceWidth; + continue; + case U'\t': + position.x += whitespaceWidth * 4; + continue; + case U'\n': + position.y += lineSpacing; + position.x = 0; + continue; } // For regular characters, add the advance offset of the glyph @@ -431,22 +453,22 @@ void Text::ensureGeometryUpdate() const // Compute the location of the strike through dynamically // We use the center point of the lowercase 'x' glyph as the reference // We reuse the underline thickness as the thickness of the strike through as well - FloatRect xBounds = m_font->getGlyph(U'x', m_characterSize, isBold).bounds; - float strikeThroughOffset = xBounds.top + xBounds.height / 2.f; + FloatRect xBounds = m_font->getGlyph(U'x', m_characterSize, isBold).bounds; + float strikeThroughOffset = xBounds.top + xBounds.height / 2.f; // Precompute the variables needed by the algorithm float whitespaceWidth = m_font->getGlyph(U' ', m_characterSize, isBold).advance; - float letterSpacing = ( whitespaceWidth / 3.f ) * ( m_letterSpacingFactor - 1.f ); - whitespaceWidth += letterSpacing; - float lineSpacing = m_font->getLineSpacing(m_characterSize) * m_lineSpacingFactor; - float x = 0.f; - auto y = static_cast(m_characterSize); + float letterSpacing = (whitespaceWidth / 3.f) * (m_letterSpacingFactor - 1.f); + whitespaceWidth += letterSpacing; + float lineSpacing = m_font->getLineSpacing(m_characterSize) * m_lineSpacingFactor; + float x = 0.f; + auto y = static_cast(m_characterSize); // Create one quad for each character - auto minX = static_cast(m_characterSize); - auto minY = static_cast(m_characterSize); - float maxX = 0.f; - float maxY = 0.f; + auto minX = static_cast(m_characterSize); + auto minY = static_cast(m_characterSize); + float maxX = 0.f; + float maxY = 0.f; Uint32 prevChar = 0; for (std::size_t i = 0; i < m_string.getSize(); ++i) { @@ -488,9 +510,16 @@ void Text::ensureGeometryUpdate() const switch (curChar) { - case U' ': x += whitespaceWidth; break; - case U'\t': x += whitespaceWidth * 4; break; - case U'\n': y += lineSpacing; x = 0; break; + case U' ': + x += whitespaceWidth; + break; + case U'\t': + x += whitespaceWidth * 4; + break; + case U'\n': + y += lineSpacing; + x = 0; + break; } // Update the current bounds (max coordinates) @@ -509,14 +538,14 @@ void Text::ensureGeometryUpdate() const float left = glyph.bounds.left; float top = glyph.bounds.top; float right = glyph.bounds.left + glyph.bounds.width; - float bottom = glyph.bounds.top + glyph.bounds.height; + float bottom = glyph.bounds.top + glyph.bounds.height; // Add the outline glyph to the vertices addGlyphQuad(m_outlineVertices, Vector2f(x, y), m_outlineColor, glyph, italicShear); // Update the current bounds with the outlined glyph bounds - minX = std::min(minX, x + left - italicShear * bottom); - maxX = std::max(maxX, x + right - italicShear * top); + minX = std::min(minX, x + left - italicShear * bottom); + maxX = std::max(maxX, x + right - italicShear * top); minY = std::min(minY, y + top); maxY = std::max(maxY, y + bottom); } @@ -533,9 +562,9 @@ void Text::ensureGeometryUpdate() const float left = glyph.bounds.left; float top = glyph.bounds.top; float right = glyph.bounds.left + glyph.bounds.width; - float bottom = glyph.bounds.top + glyph.bounds.height; + float bottom = glyph.bounds.top + glyph.bounds.height; - minX = std::min(minX, x + left - italicShear * bottom); + minX = std::min(minX, x + left - italicShear * bottom); maxX = std::max(maxX, x + right - italicShear * top); minY = std::min(minY, y + top); maxY = std::max(maxY, y + bottom); @@ -564,9 +593,9 @@ void Text::ensureGeometryUpdate() const } // Update the bounding rectangle - m_bounds.left = minX; - m_bounds.top = minY; - m_bounds.width = maxX - minX; + m_bounds.left = minX; + m_bounds.top = minY; + m_bounds.width = maxX - minX; m_bounds.height = maxY - minY; } diff --git a/src/SFML/Graphics/Texture.cpp b/src/SFML/Graphics/Texture.cpp index 197a6c0e2..5f12d803f 100644 --- a/src/SFML/Graphics/Texture.cpp +++ b/src/SFML/Graphics/Texture.cpp @@ -25,72 +25,73 @@ //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// -#include -#include #include +#include +#include #include +#include #include #include -#include + #include -#include #include +#include #include #include namespace { - // A nested named namespace is used here to allow unity builds of SFML. - namespace TextureImpl - { - std::recursive_mutex idMutex; - std::recursive_mutex maximumSizeMutex; +// A nested named namespace is used here to allow unity builds of SFML. +namespace TextureImpl +{ +std::recursive_mutex idMutex; +std::recursive_mutex maximumSizeMutex; - // Thread-safe unique identifier generator, - // is used for states cache (see RenderTarget) - sf::Uint64 getUniqueId() - { - std::scoped_lock lock(idMutex); +// Thread-safe unique identifier generator, +// is used for states cache (see RenderTarget) +sf::Uint64 getUniqueId() +{ + std::scoped_lock lock(idMutex); - static sf::Uint64 id = 1; // start at 1, zero is "no texture" + static sf::Uint64 id = 1; // start at 1, zero is "no texture" - return id++; - } - } + return id++; } +} // namespace TextureImpl +} // namespace namespace sf { //////////////////////////////////////////////////////////// Texture::Texture() : -m_size (0, 0), -m_actualSize (0, 0), -m_texture (0), -m_isSmooth (false), -m_sRgb (false), -m_isRepeated (false), +m_size(0, 0), +m_actualSize(0, 0), +m_texture(0), +m_isSmooth(false), +m_sRgb(false), +m_isRepeated(false), m_pixelsFlipped(false), m_fboAttachment(false), -m_hasMipmap (false), -m_cacheId (TextureImpl::getUniqueId()) +m_hasMipmap(false), +m_cacheId(TextureImpl::getUniqueId()) { } //////////////////////////////////////////////////////////// Texture::Texture(const Texture& copy) : -m_size (0, 0), -m_actualSize (0, 0), -m_texture (0), -m_isSmooth (copy.m_isSmooth), -m_sRgb (copy.m_sRgb), -m_isRepeated (copy.m_isRepeated), +m_size(0, 0), +m_actualSize(0, 0), +m_texture(0), +m_isSmooth(copy.m_isSmooth), +m_sRgb(copy.m_sRgb), +m_isRepeated(copy.m_isRepeated), m_pixelsFlipped(false), m_fboAttachment(false), -m_hasMipmap (false), -m_cacheId (TextureImpl::getUniqueId()) +m_hasMipmap(false), +m_cacheId(TextureImpl::getUniqueId()) { if (copy.m_texture) { @@ -144,8 +145,7 @@ bool Texture::create(const Vector2u& size) { err() << "Failed to create texture, its internal size is too high " << "(" << actualSize.x << "x" << actualSize.y << ", " - << "maximum is " << maxSize << "x" << maxSize << ")" - << std::endl; + << "maximum is " << maxSize << "x" << maxSize << ")" << std::endl; return false; } @@ -166,7 +166,8 @@ bool Texture::create(const Vector2u& size) // Make sure that the current texture binding will be preserved priv::TextureSaver save; - static bool textureEdgeClamp = GLEXT_texture_edge_clamp || GLEXT_GL_VERSION_1_2 || Context::isExtensionAvailable("GL_EXT_texture_edge_clamp"); + static bool textureEdgeClamp = GLEXT_texture_edge_clamp || GLEXT_GL_VERSION_1_2 || + Context::isExtensionAvailable("GL_EXT_texture_edge_clamp"); if (!m_isRepeated && !textureEdgeClamp) { @@ -205,9 +206,21 @@ bool Texture::create(const Vector2u& size) // Initialize the texture glCheck(glBindTexture(GL_TEXTURE_2D, m_texture)); - glCheck(glTexImage2D(GL_TEXTURE_2D, 0, (m_sRgb ? GLEXT_GL_SRGB8_ALPHA8 : GL_RGBA), static_cast(m_actualSize.x), static_cast(m_actualSize.y), 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr)); - glCheck(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, m_isRepeated ? GL_REPEAT : (textureEdgeClamp ? GLEXT_GL_CLAMP_TO_EDGE : GLEXT_GL_CLAMP))); - glCheck(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, m_isRepeated ? GL_REPEAT : (textureEdgeClamp ? GLEXT_GL_CLAMP_TO_EDGE : GLEXT_GL_CLAMP))); + glCheck(glTexImage2D(GL_TEXTURE_2D, + 0, + (m_sRgb ? GLEXT_GL_SRGB8_ALPHA8 : GL_RGBA), + static_cast(m_actualSize.x), + static_cast(m_actualSize.y), + 0, + GL_RGBA, + GL_UNSIGNED_BYTE, + nullptr)); + glCheck(glTexParameteri(GL_TEXTURE_2D, + GL_TEXTURE_WRAP_S, + m_isRepeated ? GL_REPEAT : (textureEdgeClamp ? GLEXT_GL_CLAMP_TO_EDGE : GLEXT_GL_CLAMP))); + glCheck(glTexParameteri(GL_TEXTURE_2D, + GL_TEXTURE_WRAP_T, + m_isRepeated ? GL_REPEAT : (textureEdgeClamp ? GLEXT_GL_CLAMP_TO_EDGE : GLEXT_GL_CLAMP))); glCheck(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, m_isSmooth ? GL_LINEAR : GL_NEAREST)); glCheck(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, m_isSmooth ? GL_LINEAR : GL_NEAREST)); m_cacheId = TextureImpl::getUniqueId(); @@ -246,12 +259,12 @@ bool Texture::loadFromStream(InputStream& stream, const IntRect& area) bool Texture::loadFromImage(const Image& image, const IntRect& area) { // Retrieve the image size - int width = static_cast(image.getSize().x); + int width = static_cast(image.getSize().x); int height = static_cast(image.getSize().y); // Load the entire image if the source area is either empty or contains the whole image if (area.width == 0 || (area.height == 0) || - ((area.left <= 0) && (area.top <= 0) && (area.width >= width) && (area.height >= height))) + ((area.left <= 0) && (area.top <= 0) && (area.width >= width) && (area.height >= height))) { // Load the entire image if (create(image.getSize())) @@ -271,10 +284,14 @@ bool Texture::loadFromImage(const Image& image, const IntRect& area) // Adjust the rectangle to the size of the image IntRect rectangle = area; - if (rectangle.left < 0) rectangle.left = 0; - if (rectangle.top < 0) rectangle.top = 0; - if (rectangle.left + rectangle.width > width) rectangle.width = width - rectangle.left; - if (rectangle.top + rectangle.height > height) rectangle.height = height - rectangle.top; + if (rectangle.left < 0) + rectangle.left = 0; + if (rectangle.top < 0) + rectangle.top = 0; + if (rectangle.left + rectangle.width > width) + rectangle.width = width - rectangle.left; + if (rectangle.top + rectangle.height > height) + rectangle.height = height - rectangle.top; // Create the texture and upload the pixels if (create(Vector2u(rectangle.getSize()))) @@ -364,7 +381,8 @@ Image Texture::copyToImage() const // Texture is either padded or flipped, we have to use a slower algorithm // All the pixels will first be copied to a temporary array - std::vector allPixels(static_cast(m_actualSize.x) * static_cast(m_actualSize.y) * 4); + std::vector allPixels( + static_cast(m_actualSize.x) * static_cast(m_actualSize.y) * 4); glCheck(glBindTexture(GL_TEXTURE_2D, m_texture)); glCheck(glGetTexImage(GL_TEXTURE_2D, 0, GL_RGBA, GL_UNSIGNED_BYTE, allPixels.data())); @@ -422,11 +440,19 @@ void Texture::update(const Uint8* pixels, const Vector2u& size, const Vector2u& // Copy pixels from the given array to the texture glCheck(glBindTexture(GL_TEXTURE_2D, m_texture)); - glCheck(glTexSubImage2D(GL_TEXTURE_2D, 0, static_cast(dest.x), static_cast(dest.y), static_cast(size.x), static_cast(size.y), GL_RGBA, GL_UNSIGNED_BYTE, pixels)); + glCheck(glTexSubImage2D(GL_TEXTURE_2D, + 0, + static_cast(dest.x), + static_cast(dest.y), + static_cast(size.x), + static_cast(size.y), + GL_RGBA, + GL_UNSIGNED_BYTE, + pixels)); glCheck(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, m_isSmooth ? GL_LINEAR : GL_NEAREST)); - m_hasMipmap = false; + m_hasMipmap = false; m_pixelsFlipped = false; - m_cacheId = TextureImpl::getUniqueId(); + m_cacheId = TextureImpl::getUniqueId(); // Force an OpenGL flush, so that the texture data will appear updated // in all contexts immediately (solves problems in multi-threaded apps) @@ -474,7 +500,7 @@ void Texture::update(const Texture& texture, const Vector2u& dest) // Create the framebuffers GLuint sourceFrameBuffer = 0; - GLuint destFrameBuffer = 0; + GLuint destFrameBuffer = 0; glCheck(GLEXT_glGenFramebuffers(1, &sourceFrameBuffer)); glCheck(GLEXT_glGenFramebuffers(1, &destFrameBuffer)); @@ -486,11 +512,16 @@ void Texture::update(const Texture& texture, const Vector2u& dest) // Link the source texture to the source frame buffer glCheck(GLEXT_glBindFramebuffer(GLEXT_GL_READ_FRAMEBUFFER, sourceFrameBuffer)); - glCheck(GLEXT_glFramebufferTexture2D(GLEXT_GL_READ_FRAMEBUFFER, GLEXT_GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texture.m_texture, 0)); + glCheck(GLEXT_glFramebufferTexture2D(GLEXT_GL_READ_FRAMEBUFFER, + GLEXT_GL_COLOR_ATTACHMENT0, + GL_TEXTURE_2D, + texture.m_texture, + 0)); // Link the destination texture to the destination frame buffer glCheck(GLEXT_glBindFramebuffer(GLEXT_GL_DRAW_FRAMEBUFFER, destFrameBuffer)); - glCheck(GLEXT_glFramebufferTexture2D(GLEXT_GL_DRAW_FRAMEBUFFER, GLEXT_GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, m_texture, 0)); + glCheck( + GLEXT_glFramebufferTexture2D(GLEXT_GL_DRAW_FRAMEBUFFER, GLEXT_GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, m_texture, 0)); // A final check, just to be sure... GLenum sourceStatus; @@ -502,11 +533,16 @@ void Texture::update(const Texture& texture, const Vector2u& dest) if ((sourceStatus == GLEXT_GL_FRAMEBUFFER_COMPLETE) && (destStatus == GLEXT_GL_FRAMEBUFFER_COMPLETE)) { // Blit the texture contents from the source to the destination texture - glCheck(GLEXT_glBlitFramebuffer( - 0, texture.m_pixelsFlipped ? static_cast(texture.m_size.y) : 0, static_cast(texture.m_size.x), texture.m_pixelsFlipped ? 0 : static_cast(texture.m_size.y), // Source rectangle, flip y if source is flipped - static_cast(dest.x), static_cast(dest.y), static_cast(dest.x + texture.m_size.x), static_cast(dest.y + texture.m_size.y), // Destination rectangle - GL_COLOR_BUFFER_BIT, GL_NEAREST - )); + glCheck(GLEXT_glBlitFramebuffer(0, + texture.m_pixelsFlipped ? static_cast(texture.m_size.y) : 0, + static_cast(texture.m_size.x), + texture.m_pixelsFlipped ? 0 : static_cast(texture.m_size.y), // Source rectangle, flip y if source is flipped + static_cast(dest.x), + static_cast(dest.y), + static_cast(dest.x + texture.m_size.x), + static_cast(dest.y + texture.m_size.y), // Destination rectangle + GL_COLOR_BUFFER_BIT, + GL_NEAREST)); } else { @@ -527,9 +563,9 @@ void Texture::update(const Texture& texture, const Vector2u& dest) // Set the parameters of this texture glCheck(glBindTexture(GL_TEXTURE_2D, m_texture)); glCheck(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, m_isSmooth ? GL_LINEAR : GL_NEAREST)); - m_hasMipmap = false; + m_hasMipmap = false; m_pixelsFlipped = false; - m_cacheId = TextureImpl::getUniqueId(); + m_cacheId = TextureImpl::getUniqueId(); // Force an OpenGL flush, so that the texture data will appear updated // in all contexts immediately (solves problems in multi-threaded apps) @@ -581,11 +617,18 @@ void Texture::update(const Window& window, const Vector2u& dest) // Copy pixels from the back-buffer to the texture glCheck(glBindTexture(GL_TEXTURE_2D, m_texture)); - glCheck(glCopyTexSubImage2D(GL_TEXTURE_2D, 0, static_cast(dest.x), static_cast(dest.y), 0, 0, static_cast(window.getSize().x), static_cast(window.getSize().y))); + glCheck(glCopyTexSubImage2D(GL_TEXTURE_2D, + 0, + static_cast(dest.x), + static_cast(dest.y), + 0, + 0, + static_cast(window.getSize().x), + static_cast(window.getSize().y))); glCheck(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, m_isSmooth ? GL_LINEAR : GL_NEAREST)); - m_hasMipmap = false; + m_hasMipmap = false; m_pixelsFlipped = true; - m_cacheId = TextureImpl::getUniqueId(); + m_cacheId = TextureImpl::getUniqueId(); // Force an OpenGL flush, so that the texture will appear updated // in all contexts immediately (solves problems in multi-threaded apps) @@ -613,7 +656,9 @@ void Texture::setSmooth(bool smooth) if (m_hasMipmap) { - glCheck(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, m_isSmooth ? GL_LINEAR_MIPMAP_LINEAR : GL_NEAREST_MIPMAP_LINEAR)); + glCheck(glTexParameteri(GL_TEXTURE_2D, + GL_TEXTURE_MIN_FILTER, + m_isSmooth ? GL_LINEAR_MIPMAP_LINEAR : GL_NEAREST_MIPMAP_LINEAR)); } else { @@ -676,8 +721,14 @@ void Texture::setRepeated(bool repeated) } glCheck(glBindTexture(GL_TEXTURE_2D, m_texture)); - glCheck(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, m_isRepeated ? GL_REPEAT : (textureEdgeClamp ? GLEXT_GL_CLAMP_TO_EDGE : GLEXT_GL_CLAMP))); - glCheck(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, m_isRepeated ? GL_REPEAT : (textureEdgeClamp ? GLEXT_GL_CLAMP_TO_EDGE : GLEXT_GL_CLAMP))); + glCheck( + glTexParameteri(GL_TEXTURE_2D, + GL_TEXTURE_WRAP_S, + m_isRepeated ? GL_REPEAT : (textureEdgeClamp ? GLEXT_GL_CLAMP_TO_EDGE : GLEXT_GL_CLAMP))); + glCheck( + glTexParameteri(GL_TEXTURE_2D, + GL_TEXTURE_WRAP_T, + m_isRepeated ? GL_REPEAT : (textureEdgeClamp ? GLEXT_GL_CLAMP_TO_EDGE : GLEXT_GL_CLAMP))); } } } @@ -709,7 +760,9 @@ bool Texture::generateMipmap() glCheck(glBindTexture(GL_TEXTURE_2D, m_texture)); glCheck(GLEXT_glGenerateMipmap(GL_TEXTURE_2D)); - glCheck(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, m_isSmooth ? GL_LINEAR_MIPMAP_LINEAR : GL_NEAREST_MIPMAP_LINEAR)); + glCheck(glTexParameteri(GL_TEXTURE_2D, + GL_TEXTURE_MIN_FILTER, + m_isSmooth ? GL_LINEAR_MIPMAP_LINEAR : GL_NEAREST_MIPMAP_LINEAR)); m_hasMipmap = true; @@ -766,7 +819,7 @@ void Texture::bind(const Texture* texture, CoordinateType coordinateType) // If pixels are flipped we must invert the Y axis if (texture->m_pixelsFlipped) { - matrix[5] = -matrix[5]; + matrix[5] = -matrix[5]; matrix[13] = static_cast(texture->m_size.y) / static_cast(texture->m_actualSize.y); } @@ -798,8 +851,8 @@ unsigned int Texture::getMaximumSize() { std::scoped_lock lock(TextureImpl::maximumSizeMutex); - static bool checked = false; - static GLint size = 0; + static bool checked = false; + static GLint size = 0; if (!checked) { @@ -815,7 +868,7 @@ unsigned int Texture::getMaximumSize() //////////////////////////////////////////////////////////// -Texture& Texture::operator =(const Texture& right) +Texture& Texture::operator=(const Texture& right) { Texture temp(right); @@ -828,17 +881,17 @@ Texture& Texture::operator =(const Texture& right) //////////////////////////////////////////////////////////// void Texture::swap(Texture& right) { - std::swap(m_size, right.m_size); - std::swap(m_actualSize, right.m_actualSize); - std::swap(m_texture, right.m_texture); - std::swap(m_isSmooth, right.m_isSmooth); - std::swap(m_sRgb, right.m_sRgb); - std::swap(m_isRepeated, right.m_isRepeated); + std::swap(m_size, right.m_size); + std::swap(m_actualSize, right.m_actualSize); + std::swap(m_texture, right.m_texture); + std::swap(m_isSmooth, right.m_isSmooth); + std::swap(m_sRgb, right.m_sRgb); + std::swap(m_isRepeated, right.m_isRepeated); std::swap(m_pixelsFlipped, right.m_pixelsFlipped); std::swap(m_fboAttachment, right.m_fboAttachment); - std::swap(m_hasMipmap, right.m_hasMipmap); + std::swap(m_hasMipmap, right.m_hasMipmap); - m_cacheId = TextureImpl::getUniqueId(); + m_cacheId = TextureImpl::getUniqueId(); right.m_cacheId = TextureImpl::getUniqueId(); } diff --git a/src/SFML/Graphics/TextureSaver.hpp b/src/SFML/Graphics/TextureSaver.hpp index 98337e21c..0a5e9670a 100644 --- a/src/SFML/Graphics/TextureSaver.hpp +++ b/src/SFML/Graphics/TextureSaver.hpp @@ -42,7 +42,6 @@ namespace priv class TextureSaver { public: - //////////////////////////////////////////////////////////// /// \brief Default constructor /// @@ -60,7 +59,6 @@ public: ~TextureSaver(); private: - //////////////////////////////////////////////////////////// // Member data //////////////////////////////////////////////////////////// diff --git a/src/SFML/Graphics/Transform.cpp b/src/SFML/Graphics/Transform.cpp index 3b55f6ade..59b97ee2f 100644 --- a/src/SFML/Graphics/Transform.cpp +++ b/src/SFML/Graphics/Transform.cpp @@ -27,6 +27,7 @@ //////////////////////////////////////////////////////////// #include #include + #include diff --git a/src/SFML/Graphics/Transformable.cpp b/src/SFML/Graphics/Transformable.cpp index 2399cb86e..c6b534621 100644 --- a/src/SFML/Graphics/Transformable.cpp +++ b/src/SFML/Graphics/Transformable.cpp @@ -26,6 +26,7 @@ // Headers //////////////////////////////////////////////////////////// #include + #include @@ -33,13 +34,13 @@ namespace sf { //////////////////////////////////////////////////////////// Transformable::Transformable() : -m_origin (0, 0), -m_position (0, 0), -m_rotation (), -m_scale (1, 1), -m_transform (), -m_transformNeedUpdate (true), -m_inverseTransform (), +m_origin(0, 0), +m_position(0, 0), +m_rotation(), +m_scale(1, 1), +m_transform(), +m_transformNeedUpdate(true), +m_inverseTransform(), m_inverseTransformNeedUpdate(true) { } @@ -52,8 +53,8 @@ Transformable::~Transformable() = default; //////////////////////////////////////////////////////////// void Transformable::setPosition(const Vector2f& position) { - m_position = position; - m_transformNeedUpdate = true; + m_position = position; + m_transformNeedUpdate = true; m_inverseTransformNeedUpdate = true; } @@ -63,7 +64,7 @@ void Transformable::setRotation(Angle angle) { m_rotation = angle.wrapUnsigned(); - m_transformNeedUpdate = true; + m_transformNeedUpdate = true; m_inverseTransformNeedUpdate = true; } @@ -71,8 +72,8 @@ void Transformable::setRotation(Angle angle) //////////////////////////////////////////////////////////// void Transformable::setScale(const Vector2f& factors) { - m_scale = factors; - m_transformNeedUpdate = true; + m_scale = factors; + m_transformNeedUpdate = true; m_inverseTransformNeedUpdate = true; } @@ -80,8 +81,8 @@ void Transformable::setScale(const Vector2f& factors) //////////////////////////////////////////////////////////// void Transformable::setOrigin(const Vector2f& origin) { - m_origin = origin; - m_transformNeedUpdate = true; + m_origin = origin; + m_transformNeedUpdate = true; m_inverseTransformNeedUpdate = true; } @@ -149,7 +150,7 @@ const Transform& Transformable::getTransform() const float sxs = m_scale.x * sine; float sys = m_scale.y * sine; float tx = -m_origin.x * sxc - m_origin.y * sys + m_position.x; - float ty = m_origin.x * sxs - m_origin.y * syc + m_position.y; + float ty = m_origin.x * sxs - m_origin.y * syc + m_position.y; // clang-format off m_transform = Transform( sxc, sys, tx, @@ -169,7 +170,7 @@ const Transform& Transformable::getInverseTransform() const // Recompute the inverse transform if needed if (m_inverseTransformNeedUpdate) { - m_inverseTransform = getTransform().getInverse(); + m_inverseTransform = getTransform().getInverse(); m_inverseTransformNeedUpdate = false; } diff --git a/src/SFML/Graphics/VertexArray.cpp b/src/SFML/Graphics/VertexArray.cpp index fe39c6e6c..0ab75996b 100644 --- a/src/SFML/Graphics/VertexArray.cpp +++ b/src/SFML/Graphics/VertexArray.cpp @@ -25,24 +25,20 @@ //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// -#include #include +#include namespace sf { //////////////////////////////////////////////////////////// -VertexArray::VertexArray() : -m_vertices (), -m_primitiveType(Points) +VertexArray::VertexArray() : m_vertices(), m_primitiveType(Points) { } //////////////////////////////////////////////////////////// -VertexArray::VertexArray(PrimitiveType type, std::size_t vertexCount) : -m_vertices (vertexCount), -m_primitiveType(type) +VertexArray::VertexArray(PrimitiveType type, std::size_t vertexCount) : m_vertices(vertexCount), m_primitiveType(type) { } @@ -55,14 +51,14 @@ std::size_t VertexArray::getVertexCount() const //////////////////////////////////////////////////////////// -Vertex& VertexArray::operator [](std::size_t index) +Vertex& VertexArray::operator[](std::size_t index) { return m_vertices[index]; } //////////////////////////////////////////////////////////// -const Vertex& VertexArray::operator [](std::size_t index) const +const Vertex& VertexArray::operator[](std::size_t index) const { return m_vertices[index]; } diff --git a/src/SFML/Graphics/VertexBuffer.cpp b/src/SFML/Graphics/VertexBuffer.cpp index d3fef25a2..0efae603c 100644 --- a/src/SFML/Graphics/VertexBuffer.cpp +++ b/src/SFML/Graphics/VertexBuffer.cpp @@ -25,85 +25,77 @@ //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// -#include +#include #include #include -#include +#include #include -#include -#include -#include + #include #include +#include +#include +#include namespace { - // A nested named namespace is used here to allow unity builds of SFML. - namespace VertexBufferImpl - { - std::recursive_mutex isAvailableMutex; +// A nested named namespace is used here to allow unity builds of SFML. +namespace VertexBufferImpl +{ +std::recursive_mutex isAvailableMutex; - GLenum usageToGlEnum(sf::VertexBuffer::Usage usage) - { - switch (usage) - { - case sf::VertexBuffer::Static: return GLEXT_GL_STATIC_DRAW; - case sf::VertexBuffer::Dynamic: return GLEXT_GL_DYNAMIC_DRAW; - default: return GLEXT_GL_STREAM_DRAW; - } - } +GLenum usageToGlEnum(sf::VertexBuffer::Usage usage) +{ + switch (usage) + { + case sf::VertexBuffer::Static: + return GLEXT_GL_STATIC_DRAW; + case sf::VertexBuffer::Dynamic: + return GLEXT_GL_DYNAMIC_DRAW; + default: + return GLEXT_GL_STREAM_DRAW; } } +} // namespace VertexBufferImpl +} // namespace namespace sf { //////////////////////////////////////////////////////////// -VertexBuffer::VertexBuffer() : -m_buffer (0), -m_size (0), -m_primitiveType(Points), -m_usage (Stream) +VertexBuffer::VertexBuffer() : m_buffer(0), m_size(0), m_primitiveType(Points), m_usage(Stream) { } //////////////////////////////////////////////////////////// -VertexBuffer::VertexBuffer(PrimitiveType type) : -m_buffer (0), -m_size (0), -m_primitiveType(type), -m_usage (Stream) +VertexBuffer::VertexBuffer(PrimitiveType type) : m_buffer(0), m_size(0), m_primitiveType(type), m_usage(Stream) { } //////////////////////////////////////////////////////////// -VertexBuffer::VertexBuffer(VertexBuffer::Usage usage) : -m_buffer (0), -m_size (0), -m_primitiveType(Points), -m_usage (usage) +VertexBuffer::VertexBuffer(VertexBuffer::Usage usage) : m_buffer(0), m_size(0), m_primitiveType(Points), m_usage(usage) { } //////////////////////////////////////////////////////////// VertexBuffer::VertexBuffer(PrimitiveType type, VertexBuffer::Usage usage) : -m_buffer (0), -m_size (0), +m_buffer(0), +m_size(0), m_primitiveType(type), -m_usage (usage) +m_usage(usage) { } //////////////////////////////////////////////////////////// VertexBuffer::VertexBuffer(const VertexBuffer& copy) : -m_buffer (0), -m_size (0), +m_buffer(0), +m_size(0), m_primitiveType(copy.m_primitiveType), -m_usage (copy.m_usage) +m_usage(copy.m_usage) { if (copy.m_buffer && copy.m_size) { @@ -149,7 +141,10 @@ bool VertexBuffer::create(std::size_t vertexCount) } glCheck(GLEXT_glBindBuffer(GLEXT_GL_ARRAY_BUFFER, m_buffer)); - glCheck(GLEXT_glBufferData(GLEXT_GL_ARRAY_BUFFER, static_cast(sizeof(Vertex) * vertexCount), nullptr, VertexBufferImpl::usageToGlEnum(m_usage))); + glCheck(GLEXT_glBufferData(GLEXT_GL_ARRAY_BUFFER, + static_cast(sizeof(Vertex) * vertexCount), + nullptr, + VertexBufferImpl::usageToGlEnum(m_usage))); glCheck(GLEXT_glBindBuffer(GLEXT_GL_ARRAY_BUFFER, 0)); m_size = vertexCount; @@ -192,12 +187,18 @@ bool VertexBuffer::update(const Vertex* vertices, std::size_t vertexCount, unsig // Check if we need to resize or orphan the buffer if (vertexCount >= m_size) { - glCheck(GLEXT_glBufferData(GLEXT_GL_ARRAY_BUFFER, static_cast(sizeof(Vertex) * vertexCount), nullptr, VertexBufferImpl::usageToGlEnum(m_usage))); + glCheck(GLEXT_glBufferData(GLEXT_GL_ARRAY_BUFFER, + static_cast(sizeof(Vertex) * vertexCount), + nullptr, + VertexBufferImpl::usageToGlEnum(m_usage))); m_size = vertexCount; } - glCheck(GLEXT_glBufferSubData(GLEXT_GL_ARRAY_BUFFER, static_cast(sizeof(Vertex) * offset), static_cast(sizeof(Vertex) * vertexCount), vertices)); + glCheck(GLEXT_glBufferSubData(GLEXT_GL_ARRAY_BUFFER, + static_cast(sizeof(Vertex) * offset), + static_cast(sizeof(Vertex) * vertexCount), + vertices)); glCheck(GLEXT_glBindBuffer(GLEXT_GL_ARRAY_BUFFER, 0)); @@ -227,7 +228,11 @@ bool VertexBuffer::update([[maybe_unused]] const VertexBuffer& vertexBuffer) glCheck(GLEXT_glBindBuffer(GLEXT_GL_COPY_READ_BUFFER, vertexBuffer.m_buffer)); glCheck(GLEXT_glBindBuffer(GLEXT_GL_COPY_WRITE_BUFFER, m_buffer)); - glCheck(GLEXT_glCopyBufferSubData(GLEXT_GL_COPY_READ_BUFFER, GLEXT_GL_COPY_WRITE_BUFFER, 0, 0, static_cast(sizeof(Vertex) * vertexBuffer.m_size))); + glCheck(GLEXT_glCopyBufferSubData(GLEXT_GL_COPY_READ_BUFFER, + GLEXT_GL_COPY_WRITE_BUFFER, + 0, + 0, + static_cast(sizeof(Vertex) * vertexBuffer.m_size))); glCheck(GLEXT_glBindBuffer(GLEXT_GL_COPY_WRITE_BUFFER, 0)); glCheck(GLEXT_glBindBuffer(GLEXT_GL_COPY_READ_BUFFER, 0)); @@ -236,7 +241,10 @@ bool VertexBuffer::update([[maybe_unused]] const VertexBuffer& vertexBuffer) } glCheck(GLEXT_glBindBuffer(GLEXT_GL_ARRAY_BUFFER, m_buffer)); - glCheck(GLEXT_glBufferData(GLEXT_GL_ARRAY_BUFFER, static_cast(sizeof(Vertex) * vertexBuffer.m_size), nullptr, VertexBufferImpl::usageToGlEnum(m_usage))); + glCheck(GLEXT_glBufferData(GLEXT_GL_ARRAY_BUFFER, + static_cast(sizeof(Vertex) * vertexBuffer.m_size), + nullptr, + VertexBufferImpl::usageToGlEnum(m_usage))); void* destination = nullptr; glCheck(destination = GLEXT_glMapBuffer(GLEXT_GL_ARRAY_BUFFER, GLEXT_GL_WRITE_ONLY)); @@ -268,7 +276,7 @@ bool VertexBuffer::update([[maybe_unused]] const VertexBuffer& vertexBuffer) //////////////////////////////////////////////////////////// -VertexBuffer& VertexBuffer::operator =(const VertexBuffer& right) +VertexBuffer& VertexBuffer::operator=(const VertexBuffer& right) { VertexBuffer temp(right); @@ -281,10 +289,10 @@ VertexBuffer& VertexBuffer::operator =(const VertexBuffer& right) //////////////////////////////////////////////////////////// void VertexBuffer::swap(VertexBuffer& right) { - std::swap(m_size, right.m_size); - std::swap(m_buffer, right.m_buffer); + std::swap(m_size, right.m_size); + std::swap(m_buffer, right.m_buffer); std::swap(m_primitiveType, right.m_primitiveType); - std::swap(m_usage, right.m_usage); + std::swap(m_usage, right.m_usage); } @@ -340,7 +348,7 @@ bool VertexBuffer::isAvailable() { std::scoped_lock lock(VertexBufferImpl::isAvailableMutex); - static bool checked = false; + static bool checked = false; static bool available = false; if (!checked) diff --git a/src/SFML/Graphics/View.cpp b/src/SFML/Graphics/View.cpp index d7c5866fa..a6f812af8 100644 --- a/src/SFML/Graphics/View.cpp +++ b/src/SFML/Graphics/View.cpp @@ -26,6 +26,7 @@ // Headers //////////////////////////////////////////////////////////// #include + #include @@ -33,11 +34,11 @@ namespace sf { //////////////////////////////////////////////////////////// View::View() : -m_center (), -m_size (), -m_rotation (), -m_viewport ({0, 0}, {1, 1}), -m_transformUpdated (false), +m_center(), +m_size(), +m_rotation(), +m_viewport({0, 0}, {1, 1}), +m_transformUpdated(false), m_invTransformUpdated(false) { reset(FloatRect({0, 0}, {1000, 1000})); @@ -46,11 +47,11 @@ m_invTransformUpdated(false) //////////////////////////////////////////////////////////// View::View(const FloatRect& rectangle) : -m_center (), -m_size (), -m_rotation (), -m_viewport ({0, 0}, {1, 1}), -m_transformUpdated (false), +m_center(), +m_size(), +m_rotation(), +m_viewport({0, 0}, {1, 1}), +m_transformUpdated(false), m_invTransformUpdated(false) { reset(rectangle); @@ -59,21 +60,20 @@ m_invTransformUpdated(false) //////////////////////////////////////////////////////////// View::View(const Vector2f& center, const Vector2f& size) : -m_center (center), -m_size (size), -m_rotation (), -m_viewport ({0, 0}, {1, 1}), -m_transformUpdated (false), +m_center(center), +m_size(size), +m_rotation(), +m_viewport({0, 0}, {1, 1}), +m_transformUpdated(false), m_invTransformUpdated(false) { - } //////////////////////////////////////////////////////////// void View::setCenter(const Vector2f& center) { - m_center = center; + m_center = center; m_transformUpdated = false; m_invTransformUpdated = false; } @@ -179,10 +179,10 @@ const Transform& View::getTransform() const float cosine = std::cos(angle); float sine = std::sin(angle); float tx = -m_center.x * cosine - m_center.y * sine + m_center.x; - float ty = m_center.x * sine - m_center.y * cosine + m_center.y; + float ty = m_center.x * sine - m_center.y * cosine + m_center.y; // Projection components - float a = 2.f / m_size.x; + float a = 2.f / m_size.x; float b = -2.f / m_size.y; float c = -a * m_center.x; float d = -b * m_center.y; @@ -206,7 +206,7 @@ const Transform& View::getInverseTransform() const // Recompute the matrix if needed if (!m_invTransformUpdated) { - m_inverseTransform = getTransform().getInverse(); + m_inverseTransform = getTransform().getInverse(); m_invTransformUpdated = true; } diff --git a/src/SFML/Main/MainAndroid.cpp b/src/SFML/Main/MainAndroid.cpp index 1e08ca93e..bde81960e 100644 --- a/src/SFML/Main/MainAndroid.cpp +++ b/src/SFML/Main/MainAndroid.cpp @@ -39,13 +39,15 @@ #ifdef SFML_SYSTEM_ANDROID #include -#include #include +#include #include -#include + #include -#include +#include + #include +#include #include #include @@ -53,7 +55,7 @@ #include -extern int main(int argc, char *argv[]); +extern int main(int argc, char* argv[]); namespace sf { @@ -74,7 +76,7 @@ int getAndroidApiLevel(ANativeActivity* activity) return 0; jint sdkInt = 0; - sdkInt = lJNIEnv->GetStaticIntField(versionClass, sdkIntFieldID); + sdkInt = lJNIEnv->GetStaticIntField(versionClass, sdkIntFieldID); return sdkInt; } @@ -98,7 +100,7 @@ static void initializeMain(ActivityStates* states) // Prepare and share the looper to be read later ALooper* looper = ALooper_prepare(ALOOPER_PREPARE_ALLOW_NON_CALLBACKS); - states->looper = looper; + states->looper = looper; /** * Acquire increments a reference counter on the looper. This keeps android @@ -158,21 +160,20 @@ void goToFullscreenMode(ANativeActivity* activity) int apiLevel = sf::priv::getAndroidApiLevel(activity); // Hide the status bar - ANativeActivity_setWindowFlags(activity, AWINDOW_FLAG_FULLSCREEN, - AWINDOW_FLAG_FULLSCREEN); + ANativeActivity_setWindowFlags(activity, AWINDOW_FLAG_FULLSCREEN, AWINDOW_FLAG_FULLSCREEN); // Hide the navigation bar JNIEnv* lJNIEnv = activity->env; jobject objectActivity = activity->clazz; - jclass classActivity = lJNIEnv->GetObjectClass(objectActivity); + jclass classActivity = lJNIEnv->GetObjectClass(objectActivity); jmethodID methodGetWindow = lJNIEnv->GetMethodID(classActivity, "getWindow", "()Landroid/view/Window;"); - jobject objectWindow = lJNIEnv->CallObjectMethod(objectActivity, methodGetWindow); + jobject objectWindow = lJNIEnv->CallObjectMethod(objectActivity, methodGetWindow); - jclass classWindow = lJNIEnv->FindClass("android/view/Window"); + jclass classWindow = lJNIEnv->FindClass("android/view/Window"); jmethodID methodGetDecorView = lJNIEnv->GetMethodID(classWindow, "getDecorView", "()Landroid/view/View;"); - jobject objectDecorView = lJNIEnv->CallObjectMethod(objectWindow, methodGetDecorView); + jobject objectDecorView = lJNIEnv->CallObjectMethod(objectWindow, methodGetDecorView); jclass classView = lJNIEnv->FindClass("android/view/View"); @@ -182,8 +183,10 @@ void goToFullscreenMode(ANativeActivity* activity) // API Level 14 if (apiLevel >= 14) { - jfieldID FieldSYSTEM_UI_FLAG_LOW_PROFILE = lJNIEnv->GetStaticFieldID(classView, "SYSTEM_UI_FLAG_HIDE_NAVIGATION", "I"); - jint SYSTEM_UI_FLAG_LOW_PROFILE = lJNIEnv->GetStaticIntField(classView, FieldSYSTEM_UI_FLAG_LOW_PROFILE); + jfieldID FieldSYSTEM_UI_FLAG_LOW_PROFILE = lJNIEnv->GetStaticFieldID(classView, + "SYSTEM_UI_FLAG_HIDE_NAVIGATION", + "I"); + jint SYSTEM_UI_FLAG_LOW_PROFILE = lJNIEnv->GetStaticIntField(classView, FieldSYSTEM_UI_FLAG_LOW_PROFILE); flags |= SYSTEM_UI_FLAG_LOW_PROFILE; } @@ -191,14 +194,16 @@ void goToFullscreenMode(ANativeActivity* activity) if (apiLevel >= 16) { jfieldID FieldSYSTEM_UI_FLAG_FULLSCREEN = lJNIEnv->GetStaticFieldID(classView, "SYSTEM_UI_FLAG_FULLSCREEN", "I"); - jint SYSTEM_UI_FLAG_FULLSCREEN = lJNIEnv->GetStaticIntField(classView, FieldSYSTEM_UI_FLAG_FULLSCREEN); + jint SYSTEM_UI_FLAG_FULLSCREEN = lJNIEnv->GetStaticIntField(classView, FieldSYSTEM_UI_FLAG_FULLSCREEN); flags |= SYSTEM_UI_FLAG_FULLSCREEN; } // API Level 19 if (apiLevel >= 19) { - jfieldID FieldSYSTEM_UI_FLAG_IMMERSIVE_STICKY = lJNIEnv->GetStaticFieldID(classView, "SYSTEM_UI_FLAG_IMMERSIVE_STICKY", "I"); + jfieldID FieldSYSTEM_UI_FLAG_IMMERSIVE_STICKY = lJNIEnv->GetStaticFieldID(classView, + "SYSTEM_UI_FLAG_IMMERSIVE_STICKY", + "I"); jint SYSTEM_UI_FLAG_IMMERSIVE_STICKY = lJNIEnv->GetStaticIntField(classView, FieldSYSTEM_UI_FLAG_IMMERSIVE_STICKY); flags |= SYSTEM_UI_FLAG_IMMERSIVE_STICKY; } @@ -219,27 +224,31 @@ void getScreenSizeInPixels(ANativeActivity* activity, int* width, int* height) JNIEnv* lJNIEnv = activity->env; jobject objectActivity = activity->clazz; - jclass classActivity = lJNIEnv->GetObjectClass(objectActivity); + jclass classActivity = lJNIEnv->GetObjectClass(objectActivity); - jclass classDisplayMetrics = lJNIEnv->FindClass("android/util/DisplayMetrics"); - jmethodID initDisplayMetrics = lJNIEnv->GetMethodID(classDisplayMetrics, "", "()V"); - jobject objectDisplayMetrics = lJNIEnv->NewObject(classDisplayMetrics, initDisplayMetrics); + jclass classDisplayMetrics = lJNIEnv->FindClass("android/util/DisplayMetrics"); + jmethodID initDisplayMetrics = lJNIEnv->GetMethodID(classDisplayMetrics, "", "()V"); + jobject objectDisplayMetrics = lJNIEnv->NewObject(classDisplayMetrics, initDisplayMetrics); - jmethodID methodGetWindowManager = lJNIEnv->GetMethodID(classActivity, "getWindowManager", "()Landroid/view/WindowManager;"); - jobject objectWindowManager = lJNIEnv->CallObjectMethod(objectActivity, methodGetWindowManager); + jmethodID methodGetWindowManager = lJNIEnv->GetMethodID(classActivity, + "getWindowManager", + "()Landroid/view/WindowManager;"); + jobject objectWindowManager = lJNIEnv->CallObjectMethod(objectActivity, methodGetWindowManager); - jclass classWindowManager = lJNIEnv->FindClass("android/view/WindowManager"); - jmethodID methodGetDefaultDisplay = lJNIEnv->GetMethodID(classWindowManager, "getDefaultDisplay", "()Landroid/view/Display;"); - jobject objectDisplay = lJNIEnv->CallObjectMethod(objectWindowManager, methodGetDefaultDisplay); + jclass classWindowManager = lJNIEnv->FindClass("android/view/WindowManager"); + jmethodID methodGetDefaultDisplay = lJNIEnv->GetMethodID(classWindowManager, + "getDefaultDisplay", + "()Landroid/view/Display;"); + jobject objectDisplay = lJNIEnv->CallObjectMethod(objectWindowManager, methodGetDefaultDisplay); - jclass classDisplay = lJNIEnv->FindClass("android/view/Display"); + jclass classDisplay = lJNIEnv->FindClass("android/view/Display"); jmethodID methodGetMetrics = lJNIEnv->GetMethodID(classDisplay, "getMetrics", "(Landroid/util/DisplayMetrics;)V"); lJNIEnv->CallVoidMethod(objectDisplay, methodGetMetrics, objectDisplayMetrics); - jfieldID fieldWidthPixels = lJNIEnv->GetFieldID(classDisplayMetrics, "widthPixels", "I"); + jfieldID fieldWidthPixels = lJNIEnv->GetFieldID(classDisplayMetrics, "widthPixels", "I"); jfieldID fieldHeightPixels = lJNIEnv->GetFieldID(classDisplayMetrics, "heightPixels", "I"); - *width = lJNIEnv->GetIntField(objectDisplayMetrics, fieldWidthPixels); + *width = lJNIEnv->GetIntField(objectDisplayMetrics, fieldWidthPixels); *height = lJNIEnv->GetIntField(objectDisplayMetrics, fieldHeightPixels); } @@ -255,7 +264,7 @@ static void onResume(ANativeActivity* activity) { // Retrieve our activity states from the activity instance sf::priv::ActivityStates* states = sf::priv::retrieveStates(activity); - std::scoped_lock lock(states->mutex); + std::scoped_lock lock(states->mutex); if (states->fullscreen) goToFullscreenMode(activity); @@ -273,7 +282,7 @@ static void onPause(ANativeActivity* activity) { // Retrieve our activity states from the activity instance sf::priv::ActivityStates* states = sf::priv::retrieveStates(activity); - std::scoped_lock lock(states->mutex); + std::scoped_lock lock(states->mutex); // Send an event to warn people the activity has been paused sf::Event event; @@ -339,7 +348,7 @@ static void onDestroy(ANativeActivity* activity) static void onNativeWindowCreated(ANativeActivity* activity, ANativeWindow* window) { sf::priv::ActivityStates* states = sf::priv::retrieveStates(activity); - std::scoped_lock lock(states->mutex); + std::scoped_lock lock(states->mutex); // Update the activity states states->window = window; @@ -351,7 +360,7 @@ static void onNativeWindowCreated(ANativeActivity* activity, ANativeWindow* wind // Wait for the event to be taken into account by SFML states->updated = false; - while(!(states->updated | states->terminated)) + while (!(states->updated | states->terminated)) { states->mutex.unlock(); sf::sleep(sf::milliseconds(10)); @@ -364,7 +373,7 @@ static void onNativeWindowCreated(ANativeActivity* activity, ANativeWindow* wind static void onNativeWindowDestroyed(ANativeActivity* activity, ANativeWindow* /* window */) { sf::priv::ActivityStates* states = sf::priv::retrieveStates(activity); - std::scoped_lock lock(states->mutex); + std::scoped_lock lock(states->mutex); // Update the activity states states->window = nullptr; @@ -376,7 +385,7 @@ static void onNativeWindowDestroyed(ANativeActivity* activity, ANativeWindow* /* // Wait for the event to be taken into account by SFML states->updated = false; - while(!(states->updated | states->terminated)) + while (!(states->updated | states->terminated)) { states->mutex.unlock(); sf::sleep(sf::milliseconds(10)); @@ -442,14 +451,15 @@ static void onContentRectChanged(ANativeActivity* activity, const ARect* /* rect { // Retrieve our activity states from the activity instance sf::priv::ActivityStates* states = sf::priv::retrieveStates(activity); - std::scoped_lock lock(states->mutex); + std::scoped_lock lock(states->mutex); // Make sure the window still exists before we access the dimensions on it - if (states->window != nullptr) { + if (states->window != nullptr) + { // Send an event to warn people about the window move/resize sf::Event event; - event.type = sf::Event::Resized; - event.size.width = static_cast(ANativeWindow_getWidth(states->window)); + event.type = sf::Event::Resized; + event.size.width = static_cast(ANativeWindow_getWidth(states->window)); event.size.height = static_cast(ANativeWindow_getHeight(states->window)); states->forwardEvent(event); @@ -499,7 +509,7 @@ JNIEXPORT void ANativeActivity_onCreate(ANativeActivity* activity, void* savedSt if (savedState != nullptr) { - states->savedState = malloc(savedStateSize); + states->savedState = malloc(savedStateSize); states->savedStateSize = savedStateSize; std::memcpy(states->savedState, savedState, savedStateSize); } @@ -507,7 +517,7 @@ JNIEXPORT void ANativeActivity_onCreate(ANativeActivity* activity, void* savedSt states->mainOver = false; states->initialized = false; - states->terminated = false; + states->terminated = false; // Share it across the SFML modules sf::priv::resetActivity(states); @@ -520,27 +530,26 @@ JNIEXPORT void ANativeActivity_onCreate(ANativeActivity* activity, void* savedSt activity->callbacks->onStop = onStop; activity->callbacks->onDestroy = onDestroy; - activity->callbacks->onNativeWindowCreated = onNativeWindowCreated; - activity->callbacks->onNativeWindowDestroyed = onNativeWindowDestroyed; + activity->callbacks->onNativeWindowCreated = onNativeWindowCreated; + activity->callbacks->onNativeWindowDestroyed = onNativeWindowDestroyed; activity->callbacks->onNativeWindowRedrawNeeded = onNativeWindowRedrawNeeded; - activity->callbacks->onNativeWindowResized = onNativeWindowResized; + activity->callbacks->onNativeWindowResized = onNativeWindowResized; - activity->callbacks->onInputQueueCreated = onInputQueueCreated; + activity->callbacks->onInputQueueCreated = onInputQueueCreated; activity->callbacks->onInputQueueDestroyed = onInputQueueDestroyed; - activity->callbacks->onWindowFocusChanged = onWindowFocusChanged; - activity->callbacks->onContentRectChanged = onContentRectChanged; + activity->callbacks->onWindowFocusChanged = onWindowFocusChanged; + activity->callbacks->onContentRectChanged = onContentRectChanged; activity->callbacks->onConfigurationChanged = onConfigurationChanged; activity->callbacks->onSaveInstanceState = onSaveInstanceState; - activity->callbacks->onLowMemory = onLowMemory; + activity->callbacks->onLowMemory = onLowMemory; // Share this activity with the callback functions states->activity = activity; // Keep the screen turned on and bright - ANativeActivity_setWindowFlags(activity, AWINDOW_FLAG_KEEP_SCREEN_ON, - AWINDOW_FLAG_KEEP_SCREEN_ON); + ANativeActivity_setWindowFlags(activity, AWINDOW_FLAG_KEEP_SCREEN_ON, AWINDOW_FLAG_KEEP_SCREEN_ON); // Initialize the display eglInitialize(states->display, nullptr, nullptr); diff --git a/src/SFML/Main/MainWin32.cpp b/src/SFML/Main/MainWin32.cpp index 8d06b148e..e617e7a4a 100644 --- a/src/SFML/Main/MainWin32.cpp +++ b/src/SFML/Main/MainWin32.cpp @@ -40,6 +40,7 @@ #ifdef SFML_SYSTEM_WINDOWS #include + #include // for `__argc` and `__argv` extern int main(int argc, char* argv[]); @@ -47,11 +48,10 @@ extern int main(int argc, char* argv[]); //////////////////////////////////////////////////////////// int WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR, INT) { - #pragma GCC diagnostic push - #pragma GCC diagnostic ignored "-Wpedantic" +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wpedantic" return main(__argc, __argv); - #pragma GCC diagnostic pop +#pragma GCC diagnostic pop } #endif // SFML_SYSTEM_WINDOWS - diff --git a/src/SFML/Main/SFMLActivity.cpp b/src/SFML/Main/SFMLActivity.cpp index 8e0fabf8f..8d229c3d1 100644 --- a/src/SFML/Main/SFMLActivity.cpp +++ b/src/SFML/Main/SFMLActivity.cpp @@ -23,22 +23,25 @@ //////////////////////////////////////////////////////////// #include -#include + #include +#include +#include + #include #include #include #include -#include #include #define LOGE(...) ((void)__android_log_print(ANDROID_LOG_INFO, "sfml-activity", __VA_ARGS__)) -namespace { - using activityOnCreatePointer = void (*)(ANativeActivity*, void*, size_t); +namespace +{ +using activityOnCreatePointer = void (*)(ANativeActivity*, void*, size_t); } -const char *getLibraryName(JNIEnv* lJNIEnv, jobject& objectActivityInfo) +const char* getLibraryName(JNIEnv* lJNIEnv, jobject& objectActivityInfo) { // This function reads the value of meta-data "sfml.app.lib_name" // found in the Android Manifest file and returns it. It performs the @@ -48,17 +51,17 @@ const char *getLibraryName(JNIEnv* lJNIEnv, jobject& objectActivityInfo) static char name[256]; // Get metaData instance from the ActivityInfo object - jclass classActivityInfo = lJNIEnv->FindClass("android/content/pm/ActivityInfo"); - jfieldID fieldMetaData = lJNIEnv->GetFieldID(classActivityInfo, "metaData", "Landroid/os/Bundle;"); - jobject objectMetaData = lJNIEnv->GetObjectField(objectActivityInfo, fieldMetaData); + jclass classActivityInfo = lJNIEnv->FindClass("android/content/pm/ActivityInfo"); + jfieldID fieldMetaData = lJNIEnv->GetFieldID(classActivityInfo, "metaData", "Landroid/os/Bundle;"); + jobject objectMetaData = lJNIEnv->GetObjectField(objectActivityInfo, fieldMetaData); // Create a java string object containing "sfml.app.lib_name" jobject objectName = lJNIEnv->NewStringUTF("sfml.app.lib_name"); // Get the value of meta-data named "sfml.app.lib_name" - jclass classBundle = lJNIEnv->FindClass("android/os/Bundle"); + jclass classBundle = lJNIEnv->FindClass("android/os/Bundle"); jmethodID methodGetString = lJNIEnv->GetMethodID(classBundle, "getString", "(Ljava/lang/String;)Ljava/lang/String;"); - jstring valueString = (jstring)lJNIEnv->CallObjectMethod(objectMetaData, methodGetString, objectName); + jstring valueString = (jstring)lJNIEnv->CallObjectMethod(objectMetaData, methodGetString, objectName); // No meta-data "sfml.app.lib_name" was found so we abort and inform the user if (valueString == nullptr) @@ -69,7 +72,7 @@ const char *getLibraryName(JNIEnv* lJNIEnv, jobject& objectActivityInfo) // Convert the application name to a C++ string and return it const size_t applicationNameLength = static_cast(lJNIEnv->GetStringUTFLength(valueString)); - const char* applicationName = lJNIEnv->GetStringUTFChars(valueString, nullptr); + const char* applicationName = lJNIEnv->GetStringUTFChars(valueString, nullptr); if (applicationNameLength >= 256) { @@ -87,32 +90,36 @@ const char *getLibraryName(JNIEnv* lJNIEnv, jobject& objectActivityInfo) void* loadLibrary(const char* libraryName, JNIEnv* lJNIEnv, jobject& ObjectActivityInfo) { // Find out the absolute path of the library - jclass ClassActivityInfo = lJNIEnv->FindClass("android/content/pm/ActivityInfo"); - jfieldID FieldApplicationInfo = lJNIEnv->GetFieldID(ClassActivityInfo, "applicationInfo", "Landroid/content/pm/ApplicationInfo;"); - jobject ObjectApplicationInfo = lJNIEnv->GetObjectField(ObjectActivityInfo, FieldApplicationInfo); + jclass ClassActivityInfo = lJNIEnv->FindClass("android/content/pm/ActivityInfo"); + jfieldID FieldApplicationInfo = lJNIEnv->GetFieldID(ClassActivityInfo, + "applicationInfo", + "Landroid/content/pm/ApplicationInfo;"); + jobject ObjectApplicationInfo = lJNIEnv->GetObjectField(ObjectActivityInfo, FieldApplicationInfo); - jclass ClassApplicationInfo = lJNIEnv->FindClass("android/content/pm/ApplicationInfo"); + jclass ClassApplicationInfo = lJNIEnv->FindClass("android/content/pm/ApplicationInfo"); jfieldID FieldNativeLibraryDir = lJNIEnv->GetFieldID(ClassApplicationInfo, "nativeLibraryDir", "Ljava/lang/String;"); jobject ObjectDirPath = lJNIEnv->GetObjectField(ObjectApplicationInfo, FieldNativeLibraryDir); - jclass ClassSystem = lJNIEnv->FindClass("java/lang/System"); - jmethodID StaticMethodMapLibraryName = lJNIEnv->GetStaticMethodID(ClassSystem, "mapLibraryName", "(Ljava/lang/String;)Ljava/lang/String;"); + jclass ClassSystem = lJNIEnv->FindClass("java/lang/System"); + jmethodID StaticMethodMapLibraryName = lJNIEnv->GetStaticMethodID(ClassSystem, + "mapLibraryName", + "(Ljava/lang/String;)Ljava/lang/String;"); jstring LibNameObject = lJNIEnv->NewStringUTF(libraryName); - jobject ObjectName = lJNIEnv->CallStaticObjectMethod(ClassSystem, StaticMethodMapLibraryName, LibNameObject); + jobject ObjectName = lJNIEnv->CallStaticObjectMethod(ClassSystem, StaticMethodMapLibraryName, LibNameObject); - jclass ClassFile = lJNIEnv->FindClass("java/io/File"); + jclass ClassFile = lJNIEnv->FindClass("java/io/File"); jmethodID FileConstructor = lJNIEnv->GetMethodID(ClassFile, "", "(Ljava/lang/String;Ljava/lang/String;)V"); - jobject ObjectFile = lJNIEnv->NewObject(ClassFile, FileConstructor, ObjectDirPath, ObjectName); + jobject ObjectFile = lJNIEnv->NewObject(ClassFile, FileConstructor, ObjectDirPath, ObjectName); // Get the library absolute path and convert it - jmethodID MethodGetPath = lJNIEnv->GetMethodID(ClassFile, "getPath", "()Ljava/lang/String;"); - jstring javaLibraryPath = static_cast(lJNIEnv->CallObjectMethod(ObjectFile, MethodGetPath)); - const char* libraryPath = lJNIEnv->GetStringUTFChars(javaLibraryPath, nullptr); + jmethodID MethodGetPath = lJNIEnv->GetMethodID(ClassFile, "getPath", "()Ljava/lang/String;"); + jstring javaLibraryPath = static_cast(lJNIEnv->CallObjectMethod(ObjectFile, MethodGetPath)); + const char* libraryPath = lJNIEnv->GetStringUTFChars(javaLibraryPath, nullptr); // Manually load the library - void * handle = dlopen(libraryPath, RTLD_NOW | RTLD_GLOBAL); + void* handle = dlopen(libraryPath, RTLD_NOW | RTLD_GLOBAL); if (!handle) { LOGE("dlopen(\"%s\"): %s", libraryPath, dlerror()); @@ -145,32 +152,42 @@ void ANativeActivity_onCreate(ANativeActivity* activity, void* savedState, size_ // Retrieve the NativeActivity jobject ObjectNativeActivity = activity->clazz; - jclass ClassNativeActivity = lJNIEnv->GetObjectClass(ObjectNativeActivity); + jclass ClassNativeActivity = lJNIEnv->GetObjectClass(ObjectNativeActivity); // Retrieve the ActivityInfo - jmethodID MethodGetPackageManager = lJNIEnv->GetMethodID(ClassNativeActivity, "getPackageManager", "()Landroid/content/pm/PackageManager;"); - jobject ObjectPackageManager = lJNIEnv->CallObjectMethod(ObjectNativeActivity, MethodGetPackageManager); + jmethodID MethodGetPackageManager = lJNIEnv->GetMethodID(ClassNativeActivity, + "getPackageManager", + "()Landroid/content/pm/PackageManager;"); + jobject ObjectPackageManager = lJNIEnv->CallObjectMethod(ObjectNativeActivity, MethodGetPackageManager); jmethodID MethodGetIndent = lJNIEnv->GetMethodID(ClassNativeActivity, "getIntent", "()Landroid/content/Intent;"); - jobject ObjectIntent = lJNIEnv->CallObjectMethod(ObjectNativeActivity, MethodGetIndent); + jobject ObjectIntent = lJNIEnv->CallObjectMethod(ObjectNativeActivity, MethodGetIndent); - jclass ClassIntent = lJNIEnv->FindClass("android/content/Intent"); - jmethodID MethodGetComponent = lJNIEnv->GetMethodID(ClassIntent, "getComponent", "()Landroid/content/ComponentName;"); + jclass ClassIntent = lJNIEnv->FindClass("android/content/Intent"); + jmethodID MethodGetComponent = lJNIEnv->GetMethodID(ClassIntent, + "getComponent", + "()Landroid/content/ComponentName;"); jobject ObjectComponentName = lJNIEnv->CallObjectMethod(ObjectIntent, MethodGetComponent); jclass ClassPackageManager = lJNIEnv->FindClass("android/content/pm/PackageManager"); jfieldID FieldGET_META_DATA = lJNIEnv->GetStaticFieldID(ClassPackageManager, "GET_META_DATA", "I"); - jint GET_META_DATA = lJNIEnv->GetStaticIntField(ClassPackageManager, FieldGET_META_DATA); + jint GET_META_DATA = lJNIEnv->GetStaticIntField(ClassPackageManager, FieldGET_META_DATA); - jmethodID MethodGetActivityInfo = lJNIEnv->GetMethodID(ClassPackageManager, "getActivityInfo", "(Landroid/content/ComponentName;I)Landroid/content/pm/ActivityInfo;"); - jobject ObjectActivityInfo = lJNIEnv->CallObjectMethod(ObjectPackageManager, MethodGetActivityInfo, ObjectComponentName, GET_META_DATA); + jmethodID MethodGetActivityInfo = lJNIEnv->GetMethodID(ClassPackageManager, + "getActivityInfo", + "(Landroid/content/ComponentName;I)Landroid/content/pm/" + "ActivityInfo;"); + jobject ObjectActivityInfo = lJNIEnv->CallObjectMethod(ObjectPackageManager, + MethodGetActivityInfo, + ObjectComponentName, + GET_META_DATA); // Load our libraries in reverse order #if defined(STL_LIBRARY) #define _SFML_QS(s) _SFML_S(s) -#define _SFML_S(s) #s +#define _SFML_S(s) #s loadLibrary(_SFML_QS(STL_LIBRARY), lJNIEnv, ObjectActivityInfo); #undef _SFML_S #undef _SFML_QS @@ -194,7 +211,8 @@ void ANativeActivity_onCreate(ANativeActivity* activity, void* savedState, size_ void* handle = loadLibrary(getLibraryName(lJNIEnv, ObjectActivityInfo), lJNIEnv, ObjectActivityInfo); // Call the original ANativeActivity_onCreate function - activityOnCreatePointer ANativeActivity_onCreate = (activityOnCreatePointer)dlsym(handle, "ANativeActivity_onCreate"); + activityOnCreatePointer ANativeActivity_onCreate = (activityOnCreatePointer)dlsym(handle, + "ANativeActivity_onCreate"); if (!ANativeActivity_onCreate) { diff --git a/src/SFML/Network/Ftp.cpp b/src/SFML/Network/Ftp.cpp index b51da526f..b23ec4111 100644 --- a/src/SFML/Network/Ftp.cpp +++ b/src/SFML/Network/Ftp.cpp @@ -28,13 +28,14 @@ #include #include #include + #include #include +#include #include #include -#include #include -#include +#include namespace sf @@ -43,7 +44,6 @@ namespace sf class Ftp::DataChannel { public: - //////////////////////////////////////////////////////////// DataChannel(Ftp& owner); @@ -69,7 +69,6 @@ public: void receive(std::ostream& stream); private: - //////////////////////////////////////////////////////////// // Member data //////////////////////////////////////////////////////////// @@ -79,11 +78,8 @@ private: //////////////////////////////////////////////////////////// -Ftp::Response::Response(Status code, const std::string& message) : -m_status (code), -m_message(message) +Ftp::Response::Response(Status code, const std::string& message) : m_status(code), m_message(message) { - } @@ -109,15 +105,14 @@ const std::string& Ftp::Response::getMessage() const //////////////////////////////////////////////////////////// -Ftp::DirectoryResponse::DirectoryResponse(const Ftp::Response& response) : -Ftp::Response(response) +Ftp::DirectoryResponse::DirectoryResponse(const Ftp::Response& response) : Ftp::Response(response) { if (isOk()) { // Extract the directory from the server response std::string::size_type begin = getMessage().find('"', 0); std::string::size_type end = getMessage().find('"', begin + 1); - m_directory = getMessage().substr(begin + 1, end - begin - 1); + m_directory = getMessage().substr(begin + 1, end - begin - 1); } } @@ -130,8 +125,7 @@ const std::filesystem::path& Ftp::DirectoryResponse::getDirectory() const //////////////////////////////////////////////////////////// -Ftp::ListingResponse::ListingResponse(const Ftp::Response& response, const std::string& data) : -Ftp::Response(response) +Ftp::ListingResponse::ListingResponse(const Ftp::Response& response, const std::string& data) : Ftp::Response(response) { if (isOk()) { @@ -156,7 +150,7 @@ const std::vector& Ftp::ListingResponse::getListing() const //////////////////////////////////////////////////////////// Ftp::~Ftp() { - (void) disconnect(); + (void)disconnect(); } @@ -221,8 +215,8 @@ Ftp::ListingResponse Ftp::getDirectoryListing(const std::string& directory) { // Open a data channel on default port (20) using ASCII transfer mode std::ostringstream directoryData; - DataChannel data(*this); - Response response = data.open(Ascii); + DataChannel data(*this); + Response response = data.open(Ascii); if (response.isOk()) { // Tell the server to send us the listing @@ -274,7 +268,7 @@ Ftp::Response Ftp::renameFile(const std::filesystem::path& file, const std::file { Response response = sendCommand("RNFR", file.string()); if (response.isOk()) - response = sendCommand("RNTO", newName.string()); + response = sendCommand("RNTO", newName.string()); return response; } @@ -292,7 +286,7 @@ Ftp::Response Ftp::download(const std::filesystem::path& remoteFile, const std:: { // Open a data channel using the given transfer mode DataChannel data(*this); - Response response = data.open(mode); + Response response = data.open(mode); if (response.isOk()) { // Tell the server to start the transfer @@ -301,7 +295,7 @@ Ftp::Response Ftp::download(const std::filesystem::path& remoteFile, const std:: { // Create the file and truncate it if necessary const std::filesystem::path filepath = localPath / remoteFile.filename(); - std::ofstream file(filepath, std::ios_base::binary | std::ios_base::trunc); + std::ofstream file(filepath, std::ios_base::binary | std::ios_base::trunc); if (!file) return Response(Response::InvalidFile); @@ -333,8 +327,8 @@ Ftp::Response Ftp::upload(const std::string& localFile, const std::string& remot return Response(Response::InvalidFile); // Extract the filename from the file path - std::string filename = localFile; - std::string::size_type pos = filename.find_last_of("/\\"); + std::string filename = localFile; + std::string::size_type pos = filename.find_last_of("/\\"); if (pos != std::string::npos) filename = filename.substr(pos + 1); @@ -345,7 +339,7 @@ Ftp::Response Ftp::upload(const std::string& localFile, const std::string& remot // Open a data channel using the given transfer mode DataChannel data(*this); - Response response = data.open(mode); + Response response = data.open(mode); if (response.isOk()) { // Tell the server to start the transfer @@ -389,14 +383,14 @@ Ftp::Response Ftp::getResponse() // We'll use a variable to keep track of the last valid code. // It is useful in case of multi-lines responses, because the end of such a response // will start by the same code - unsigned int lastCode = 0; - bool isInsideMultiline = false; - std::string message; + unsigned int lastCode = 0; + bool isInsideMultiline = false; + std::string message; for (;;) { // Receive the response from the server - char buffer[1024]; + char buffer[1024]; std::size_t length; if (m_receiveBuffer.empty()) @@ -466,7 +460,8 @@ Ftp::Response Ftp::getResponse() } // Save the remaining data for the next time getResponse() is called - m_receiveBuffer.assign(buffer + static_cast(in.tellg()), length - static_cast(in.tellg())); + m_receiveBuffer.assign(buffer + static_cast(in.tellg()), + length - static_cast(in.tellg())); // Return the response code and message return Response(static_cast(code), message); @@ -526,10 +521,8 @@ Ftp::Response Ftp::getResponse() //////////////////////////////////////////////////////////// -Ftp::DataChannel::DataChannel(Ftp& owner) : -m_ftp(owner) +Ftp::DataChannel::DataChannel(Ftp& owner) : m_ftp(owner) { - } @@ -544,9 +537,9 @@ Ftp::Response Ftp::DataChannel::open(Ftp::TransferMode mode) std::string::size_type begin = response.getMessage().find_first_of("0123456789"); if (begin != std::string::npos) { - Uint8 data[6] = {0, 0, 0, 0, 0, 0}; - std::string str = response.getMessage().substr(begin); - std::size_t index = 0; + Uint8 data[6] = {0, 0, 0, 0, 0, 0}; + std::string str = response.getMessage().substr(begin); + std::size_t index = 0; for (unsigned char& datum : data) { // Extract the current number @@ -562,10 +555,7 @@ Ftp::Response Ftp::DataChannel::open(Ftp::TransferMode mode) // Reconstruct connection port and address unsigned short port = static_cast(data[4] * 256) + data[5]; - IpAddress address(data[0], - data[1], - data[2], - data[3]); + IpAddress address(data[0], data[1], data[2], data[3]); // Connect the data channel to the server if (m_dataSocket.connect(address, port) == Socket::Done) @@ -574,9 +564,15 @@ Ftp::Response Ftp::DataChannel::open(Ftp::TransferMode mode) std::string modeStr; switch (mode) { - case Ftp::Binary: modeStr = "I"; break; - case Ftp::Ascii: modeStr = "A"; break; - case Ftp::Ebcdic: modeStr = "E"; break; + case Ftp::Binary: + modeStr = "I"; + break; + case Ftp::Ascii: + modeStr = "A"; + break; + case Ftp::Ebcdic: + modeStr = "E"; + break; } // Set the transfer mode @@ -598,7 +594,7 @@ Ftp::Response Ftp::DataChannel::open(Ftp::TransferMode mode) void Ftp::DataChannel::receive(std::ostream& stream) { // Receive data - char buffer[1024]; + char buffer[1024]; std::size_t received; while (m_dataSocket.receive(buffer, sizeof(buffer), received) == Socket::Done) { @@ -620,7 +616,7 @@ void Ftp::DataChannel::receive(std::ostream& stream) void Ftp::DataChannel::send(std::istream& stream) { // Send data - char buffer[1024]; + char buffer[1024]; std::size_t count; for (;;) diff --git a/src/SFML/Network/Http.cpp b/src/SFML/Network/Http.cpp index e58e7ef6a..c4f37393d 100644 --- a/src/SFML/Network/Http.cpp +++ b/src/SFML/Network/Http.cpp @@ -28,10 +28,11 @@ #include #include #include + #include -#include #include #include +#include namespace sf @@ -95,11 +96,21 @@ std::string Http::Request::prepare() const std::string method; switch (m_method) { - case Get: method = "GET"; break; - case Post: method = "POST"; break; - case Head: method = "HEAD"; break; - case Put: method = "PUT"; break; - case Delete: method = "DELETE"; break; + case Get: + method = "GET"; + break; + case Post: + method = "POST"; + break; + case Head: + method = "HEAD"; + break; + case Put: + method = "PUT"; + break; + case Delete: + method = "DELETE"; + break; } // Write the first line containing the request type @@ -130,12 +141,8 @@ bool Http::Request::hasField(const std::string& field) const //////////////////////////////////////////////////////////// -Http::Response::Response() : -m_status (ConnectionFailed), -m_majorVersion(0), -m_minorVersion(0) +Http::Response::Response() : m_status(ConnectionFailed), m_majorVersion(0), m_minorVersion(0) { - } @@ -189,9 +196,8 @@ void Http::Response::parse(const std::string& data) std::string version; if (in >> version) { - if ((version.size() >= 8) && (version[6] == '.') && - (toLower(version.substr(0, 5)) == "http/") && - std::isdigit(version[5]) && std::isdigit(version[7])) + if ((version.size() >= 8) && (version[6] == '.') && (toLower(version.substr(0, 5)) == "http/") && + std::isdigit(version[5]) && std::isdigit(version[7])) { m_majorVersion = static_cast(version[5] - '0'); m_minorVersion = static_cast(version[7] - '0'); @@ -262,7 +268,7 @@ void Http::Response::parse(const std::string& data) //////////////////////////////////////////////////////////// -void Http::Response::parseFields(std::istream &in) +void Http::Response::parseFields(std::istream& in) { std::string line; while (std::getline(in, line) && (line.size() > 2)) @@ -286,11 +292,8 @@ void Http::Response::parseFields(std::istream &in) //////////////////////////////////////////////////////////// -Http::Http() : -m_host(), -m_port(0) +Http::Http() : m_host(), m_port(0) { - } @@ -316,7 +319,7 @@ void Http::setHost(const std::string& host, unsigned short port) // HTTPS protocol -- unsupported (requires encryption and certificates and stuff...) err() << "HTTPS protocol is not supported by sf::Http" << std::endl; m_hostName.clear(); - m_port = 0; + m_port = 0; } else { @@ -382,7 +385,7 @@ Http::Response Http::sendRequest(const Http::Request& request, Time timeout) // Wait for the server's response std::string receivedStr; std::size_t size = 0; - char buffer[1024]; + char buffer[1024]; while (m_connection.receive(buffer, sizeof(buffer), size) == Socket::Done) { receivedStr.append(buffer, buffer + size); diff --git a/src/SFML/Network/IpAddress.cpp b/src/SFML/Network/IpAddress.cpp index d37a2e8b3..c8112badf 100644 --- a/src/SFML/Network/IpAddress.cpp +++ b/src/SFML/Network/IpAddress.cpp @@ -25,12 +25,13 @@ //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// -#include #include +#include #include + +#include #include #include -#include #include @@ -92,8 +93,7 @@ m_address(htonl(static_cast((byte0 << 24) | (byte1 << 16) | (byte //////////////////////////////////////////////////////////// -IpAddress::IpAddress(Uint32 address) : -m_address(htonl(address)) +IpAddress::IpAddress(Uint32 address) : m_address(htonl(address)) { } @@ -160,8 +160,8 @@ std::optional IpAddress::getPublicAddress(Time timeout) // and parse the result to extract our IP address // (not very hard: the web page contains only our IP address). - Http server("www.sfml-dev.org"); - Http::Request request("/ip-provider.php", Http::Request::Get); + Http server("www.sfml-dev.org"); + Http::Request request("/ip-provider.php", Http::Request::Get); Http::Response page = server.sendRequest(request, timeout); if (page.getStatus() == Http::Response::Ok) return IpAddress::resolve(page.getBody()); @@ -172,49 +172,49 @@ std::optional IpAddress::getPublicAddress(Time timeout) //////////////////////////////////////////////////////////// -bool operator ==(const IpAddress& left, const IpAddress& right) +bool operator==(const IpAddress& left, const IpAddress& right) { return !(left < right) && !(right < left); } //////////////////////////////////////////////////////////// -bool operator !=(const IpAddress& left, const IpAddress& right) +bool operator!=(const IpAddress& left, const IpAddress& right) { return !(left == right); } //////////////////////////////////////////////////////////// -bool operator <(const IpAddress& left, const IpAddress& right) +bool operator<(const IpAddress& left, const IpAddress& right) { return left.m_address < right.m_address; } //////////////////////////////////////////////////////////// -bool operator >(const IpAddress& left, const IpAddress& right) +bool operator>(const IpAddress& left, const IpAddress& right) { return right < left; } //////////////////////////////////////////////////////////// -bool operator <=(const IpAddress& left, const IpAddress& right) +bool operator<=(const IpAddress& left, const IpAddress& right) { return !(right < left); } //////////////////////////////////////////////////////////// -bool operator >=(const IpAddress& left, const IpAddress& right) +bool operator>=(const IpAddress& left, const IpAddress& right) { return !(left < right); } //////////////////////////////////////////////////////////// -std::istream& operator >>(std::istream& stream, std::optional& address) +std::istream& operator>>(std::istream& stream, std::optional& address) { std::string str; stream >> str; @@ -225,7 +225,7 @@ std::istream& operator >>(std::istream& stream, std::optional& addres //////////////////////////////////////////////////////////// -std::ostream& operator <<(std::ostream& stream, const IpAddress& address) +std::ostream& operator<<(std::ostream& stream, const IpAddress& address) { return stream << address.toString(); } diff --git a/src/SFML/Network/Packet.cpp b/src/SFML/Network/Packet.cpp index 51c602c14..ce3dbe6f3 100644 --- a/src/SFML/Network/Packet.cpp +++ b/src/SFML/Network/Packet.cpp @@ -28,6 +28,7 @@ #include #include #include + #include #include @@ -35,12 +36,8 @@ namespace sf { //////////////////////////////////////////////////////////// -Packet::Packet() : -m_readPos(0), -m_sendPos(0), -m_isValid(true) +Packet::Packet() : m_readPos(0), m_sendPos(0), m_isValid(true) { - } @@ -121,7 +118,7 @@ Packet::operator bool() const //////////////////////////////////////////////////////////// -Packet& Packet::operator >>(bool& data) +Packet& Packet::operator>>(bool& data) { Uint8 value; if (*this >> value) @@ -132,7 +129,7 @@ Packet& Packet::operator >>(bool& data) //////////////////////////////////////////////////////////// -Packet& Packet::operator >>(Int8& data) +Packet& Packet::operator>>(Int8& data) { if (checkSize(sizeof(data))) { @@ -145,7 +142,7 @@ Packet& Packet::operator >>(Int8& data) //////////////////////////////////////////////////////////// -Packet& Packet::operator >>(Uint8& data) +Packet& Packet::operator>>(Uint8& data) { if (checkSize(sizeof(data))) { @@ -158,7 +155,7 @@ Packet& Packet::operator >>(Uint8& data) //////////////////////////////////////////////////////////// -Packet& Packet::operator >>(Int16& data) +Packet& Packet::operator>>(Int16& data) { if (checkSize(sizeof(data))) { @@ -172,7 +169,7 @@ Packet& Packet::operator >>(Int16& data) //////////////////////////////////////////////////////////// -Packet& Packet::operator >>(Uint16& data) +Packet& Packet::operator>>(Uint16& data) { if (checkSize(sizeof(data))) { @@ -186,7 +183,7 @@ Packet& Packet::operator >>(Uint16& data) //////////////////////////////////////////////////////////// -Packet& Packet::operator >>(Int32& data) +Packet& Packet::operator>>(Int32& data) { if (checkSize(sizeof(data))) { @@ -200,7 +197,7 @@ Packet& Packet::operator >>(Int32& data) //////////////////////////////////////////////////////////// -Packet& Packet::operator >>(Uint32& data) +Packet& Packet::operator>>(Uint32& data) { if (checkSize(sizeof(data))) { @@ -214,7 +211,7 @@ Packet& Packet::operator >>(Uint32& data) //////////////////////////////////////////////////////////// -Packet& Packet::operator >>(Int64& data) +Packet& Packet::operator>>(Int64& data) { if (checkSize(sizeof(data))) { @@ -223,14 +220,10 @@ Packet& Packet::operator >>(Int64& data) Uint8 bytes[sizeof(data)]; std::memcpy(bytes, &m_data[m_readPos], sizeof(data)); - data = (static_cast(bytes[0]) << 56) | - (static_cast(bytes[1]) << 48) | - (static_cast(bytes[2]) << 40) | - (static_cast(bytes[3]) << 32) | - (static_cast(bytes[4]) << 24) | - (static_cast(bytes[5]) << 16) | - (static_cast(bytes[6]) << 8) | - (static_cast(bytes[7]) ); + data = (static_cast(bytes[0]) << 56) | (static_cast(bytes[1]) << 48) | + (static_cast(bytes[2]) << 40) | (static_cast(bytes[3]) << 32) | + (static_cast(bytes[4]) << 24) | (static_cast(bytes[5]) << 16) | + (static_cast(bytes[6]) << 8) | (static_cast(bytes[7])); m_readPos += sizeof(data); } @@ -240,7 +233,7 @@ Packet& Packet::operator >>(Int64& data) //////////////////////////////////////////////////////////// -Packet& Packet::operator >>(Uint64& data) +Packet& Packet::operator>>(Uint64& data) { if (checkSize(sizeof(data))) { @@ -249,14 +242,10 @@ Packet& Packet::operator >>(Uint64& data) Uint8 bytes[sizeof(data)]; std::memcpy(bytes, &m_data[m_readPos], sizeof(data)); - data = (static_cast(bytes[0]) << 56) | - (static_cast(bytes[1]) << 48) | - (static_cast(bytes[2]) << 40) | - (static_cast(bytes[3]) << 32) | - (static_cast(bytes[4]) << 24) | - (static_cast(bytes[5]) << 16) | - (static_cast(bytes[6]) << 8) | - (static_cast(bytes[7]) ); + data = (static_cast(bytes[0]) << 56) | (static_cast(bytes[1]) << 48) | + (static_cast(bytes[2]) << 40) | (static_cast(bytes[3]) << 32) | + (static_cast(bytes[4]) << 24) | (static_cast(bytes[5]) << 16) | + (static_cast(bytes[6]) << 8) | (static_cast(bytes[7])); m_readPos += sizeof(data); } @@ -266,7 +255,7 @@ Packet& Packet::operator >>(Uint64& data) //////////////////////////////////////////////////////////// -Packet& Packet::operator >>(float& data) +Packet& Packet::operator>>(float& data) { if (checkSize(sizeof(data))) { @@ -279,7 +268,7 @@ Packet& Packet::operator >>(float& data) //////////////////////////////////////////////////////////// -Packet& Packet::operator >>(double& data) +Packet& Packet::operator>>(double& data) { if (checkSize(sizeof(data))) { @@ -292,7 +281,7 @@ Packet& Packet::operator >>(double& data) //////////////////////////////////////////////////////////// -Packet& Packet::operator >>(char* data) +Packet& Packet::operator>>(char* data) { // First extract string length Uint32 length = 0; @@ -313,7 +302,7 @@ Packet& Packet::operator >>(char* data) //////////////////////////////////////////////////////////// -Packet& Packet::operator >>(std::string& data) +Packet& Packet::operator>>(std::string& data) { // First extract string length Uint32 length = 0; @@ -334,7 +323,7 @@ Packet& Packet::operator >>(std::string& data) //////////////////////////////////////////////////////////// -Packet& Packet::operator >>(wchar_t* data) +Packet& Packet::operator>>(wchar_t* data) { // First extract string length Uint32 length = 0; @@ -357,7 +346,7 @@ Packet& Packet::operator >>(wchar_t* data) //////////////////////////////////////////////////////////// -Packet& Packet::operator >>(std::wstring& data) +Packet& Packet::operator>>(std::wstring& data) { // First extract string length Uint32 length = 0; @@ -380,7 +369,7 @@ Packet& Packet::operator >>(std::wstring& data) //////////////////////////////////////////////////////////// -Packet& Packet::operator >>(String& data) +Packet& Packet::operator>>(String& data) { // First extract the string length Uint32 length = 0; @@ -403,7 +392,7 @@ Packet& Packet::operator >>(String& data) //////////////////////////////////////////////////////////// -Packet& Packet::operator <<(bool data) +Packet& Packet::operator<<(bool data) { *this << static_cast(data); return *this; @@ -411,7 +400,7 @@ Packet& Packet::operator <<(bool data) //////////////////////////////////////////////////////////// -Packet& Packet::operator <<(Int8 data) +Packet& Packet::operator<<(Int8 data) { append(&data, sizeof(data)); return *this; @@ -419,7 +408,7 @@ Packet& Packet::operator <<(Int8 data) //////////////////////////////////////////////////////////// -Packet& Packet::operator <<(Uint8 data) +Packet& Packet::operator<<(Uint8 data) { append(&data, sizeof(data)); return *this; @@ -427,7 +416,7 @@ Packet& Packet::operator <<(Uint8 data) //////////////////////////////////////////////////////////// -Packet& Packet::operator <<(Int16 data) +Packet& Packet::operator<<(Int16 data) { auto toWrite = static_cast(htons(static_cast(data))); append(&toWrite, sizeof(toWrite)); @@ -436,7 +425,7 @@ Packet& Packet::operator <<(Int16 data) //////////////////////////////////////////////////////////// -Packet& Packet::operator <<(Uint16 data) +Packet& Packet::operator<<(Uint16 data) { Uint16 toWrite = htons(data); append(&toWrite, sizeof(toWrite)); @@ -445,7 +434,7 @@ Packet& Packet::operator <<(Uint16 data) //////////////////////////////////////////////////////////// -Packet& Packet::operator <<(Int32 data) +Packet& Packet::operator<<(Int32 data) { Int32 toWrite = static_cast(htonl(static_cast(data))); append(&toWrite, sizeof(toWrite)); @@ -454,7 +443,7 @@ Packet& Packet::operator <<(Int32 data) //////////////////////////////////////////////////////////// -Packet& Packet::operator <<(Uint32 data) +Packet& Packet::operator<<(Uint32 data) { Uint32 toWrite = htonl(data); append(&toWrite, sizeof(toWrite)); @@ -463,22 +452,19 @@ Packet& Packet::operator <<(Uint32 data) //////////////////////////////////////////////////////////// -Packet& Packet::operator <<(Int64 data) +Packet& Packet::operator<<(Int64 data) { // Since htonll is not available everywhere, we have to convert // to network byte order (big endian) manually - Uint8 toWrite[] = - { - static_cast((data >> 56) & 0xFF), - static_cast((data >> 48) & 0xFF), - static_cast((data >> 40) & 0xFF), - static_cast((data >> 32) & 0xFF), - static_cast((data >> 24) & 0xFF), - static_cast((data >> 16) & 0xFF), - static_cast((data >> 8) & 0xFF), - static_cast((data ) & 0xFF) - }; + Uint8 toWrite[] = {static_cast((data >> 56) & 0xFF), + static_cast((data >> 48) & 0xFF), + static_cast((data >> 40) & 0xFF), + static_cast((data >> 32) & 0xFF), + static_cast((data >> 24) & 0xFF), + static_cast((data >> 16) & 0xFF), + static_cast((data >> 8) & 0xFF), + static_cast((data)&0xFF)}; append(&toWrite, sizeof(toWrite)); return *this; @@ -486,22 +472,19 @@ Packet& Packet::operator <<(Int64 data) //////////////////////////////////////////////////////////// -Packet& Packet::operator <<(Uint64 data) +Packet& Packet::operator<<(Uint64 data) { // Since htonll is not available everywhere, we have to convert // to network byte order (big endian) manually - Uint8 toWrite[] = - { - static_cast((data >> 56) & 0xFF), - static_cast((data >> 48) & 0xFF), - static_cast((data >> 40) & 0xFF), - static_cast((data >> 32) & 0xFF), - static_cast((data >> 24) & 0xFF), - static_cast((data >> 16) & 0xFF), - static_cast((data >> 8) & 0xFF), - static_cast((data ) & 0xFF) - }; + Uint8 toWrite[] = {static_cast((data >> 56) & 0xFF), + static_cast((data >> 48) & 0xFF), + static_cast((data >> 40) & 0xFF), + static_cast((data >> 32) & 0xFF), + static_cast((data >> 24) & 0xFF), + static_cast((data >> 16) & 0xFF), + static_cast((data >> 8) & 0xFF), + static_cast((data)&0xFF)}; append(&toWrite, sizeof(toWrite)); return *this; @@ -509,7 +492,7 @@ Packet& Packet::operator <<(Uint64 data) //////////////////////////////////////////////////////////// -Packet& Packet::operator <<(float data) +Packet& Packet::operator<<(float data) { append(&data, sizeof(data)); return *this; @@ -517,7 +500,7 @@ Packet& Packet::operator <<(float data) //////////////////////////////////////////////////////////// -Packet& Packet::operator <<(double data) +Packet& Packet::operator<<(double data) { append(&data, sizeof(data)); return *this; @@ -525,7 +508,7 @@ Packet& Packet::operator <<(double data) //////////////////////////////////////////////////////////// -Packet& Packet::operator <<(const char* data) +Packet& Packet::operator<<(const char* data) { // First insert string length auto length = static_cast(std::strlen(data)); @@ -539,7 +522,7 @@ Packet& Packet::operator <<(const char* data) //////////////////////////////////////////////////////////// -Packet& Packet::operator <<(const std::string& data) +Packet& Packet::operator<<(const std::string& data) { // First insert string length auto length = static_cast(data.size()); @@ -554,7 +537,7 @@ Packet& Packet::operator <<(const std::string& data) //////////////////////////////////////////////////////////// -Packet& Packet::operator <<(const wchar_t* data) +Packet& Packet::operator<<(const wchar_t* data) { // First insert string length auto length = static_cast(std::wcslen(data)); @@ -569,7 +552,7 @@ Packet& Packet::operator <<(const wchar_t* data) //////////////////////////////////////////////////////////// -Packet& Packet::operator <<(const std::wstring& data) +Packet& Packet::operator<<(const std::wstring& data) { // First insert string length auto length = static_cast(data.size()); @@ -587,7 +570,7 @@ Packet& Packet::operator <<(const std::wstring& data) //////////////////////////////////////////////////////////// -Packet& Packet::operator <<(const String& data) +Packet& Packet::operator<<(const String& data) { // First insert the string length auto length = static_cast(data.getSize()); diff --git a/src/SFML/Network/Socket.cpp b/src/SFML/Network/Socket.cpp index d77e2f225..be839ad50 100644 --- a/src/SFML/Network/Socket.cpp +++ b/src/SFML/Network/Socket.cpp @@ -28,18 +28,15 @@ #include #include #include + #include namespace sf { //////////////////////////////////////////////////////////// -Socket::Socket(Type type) : -m_type (type), -m_socket (priv::SocketImpl::invalidSocket()), -m_isBlocking(true) +Socket::Socket(Type type) : m_type(type), m_socket(priv::SocketImpl::invalidSocket()), m_isBlocking(true) { - } @@ -117,13 +114,13 @@ void Socket::create(SocketHandle handle) << "all your TCP packets will be buffered" << std::endl; } - // On Mac OS X, disable the SIGPIPE signal on disconnection - #ifdef SFML_SYSTEM_MACOS - if (setsockopt(m_socket, SOL_SOCKET, SO_NOSIGPIPE, reinterpret_cast(&yes), sizeof(yes)) == -1) - { - err() << "Failed to set socket option \"SO_NOSIGPIPE\"" << std::endl; - } - #endif +// On Mac OS X, disable the SIGPIPE signal on disconnection +#ifdef SFML_SYSTEM_MACOS + if (setsockopt(m_socket, SOL_SOCKET, SO_NOSIGPIPE, reinterpret_cast(&yes), sizeof(yes)) == -1) + { + err() << "Failed to set socket option \"SO_NOSIGPIPE\"" << std::endl; + } +#endif } else { diff --git a/src/SFML/Network/SocketImpl.hpp b/src/SFML/Network/SocketImpl.hpp index 398d1ef18..8677d902a 100644 --- a/src/SFML/Network/SocketImpl.hpp +++ b/src/SFML/Network/SocketImpl.hpp @@ -30,10 +30,10 @@ #if defined(SFML_SYSTEM_WINDOWS) - #include +#include #else - #include +#include #endif diff --git a/src/SFML/Network/SocketSelector.cpp b/src/SFML/Network/SocketSelector.cpp index a03bb6df9..b7b564e35 100644 --- a/src/SFML/Network/SocketSelector.cpp +++ b/src/SFML/Network/SocketSelector.cpp @@ -25,17 +25,18 @@ //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// -#include #include #include +#include #include + #include #include #include #include #ifdef _MSC_VER - #pragma warning(disable: 4127) // "conditional expression is constant" generated by the FD_SET macro +#pragma warning(disable : 4127) // "conditional expression is constant" generated by the FD_SET macro #endif @@ -52,18 +53,15 @@ struct SocketSelector::SocketSelectorImpl //////////////////////////////////////////////////////////// -SocketSelector::SocketSelector() : -m_impl(std::make_unique()) +SocketSelector::SocketSelector() : m_impl(std::make_unique()) { clear(); } //////////////////////////////////////////////////////////// -SocketSelector::SocketSelector(const SocketSelector& copy) : -m_impl(std::make_unique(*copy.m_impl)) +SocketSelector::SocketSelector(const SocketSelector& copy) : m_impl(std::make_unique(*copy.m_impl)) { - } @@ -146,7 +144,7 @@ void SocketSelector::clear() FD_ZERO(&m_impl->allSockets); FD_ZERO(&m_impl->socketsReady); - m_impl->maxSocket = 0; + m_impl->maxSocket = 0; m_impl->socketCount = 0; } @@ -192,7 +190,7 @@ bool SocketSelector::isReady(Socket& socket) const //////////////////////////////////////////////////////////// -SocketSelector& SocketSelector::operator =(const SocketSelector& right) +SocketSelector& SocketSelector::operator=(const SocketSelector& right) { SocketSelector temp(right); diff --git a/src/SFML/Network/TcpListener.cpp b/src/SFML/Network/TcpListener.cpp index 8213070f6..8c8602adb 100644 --- a/src/SFML/Network/TcpListener.cpp +++ b/src/SFML/Network/TcpListener.cpp @@ -25,20 +25,19 @@ //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// +#include #include #include -#include #include + #include namespace sf { //////////////////////////////////////////////////////////// -TcpListener::TcpListener() : -Socket(Tcp) +TcpListener::TcpListener() : Socket(Tcp) { - } @@ -48,7 +47,7 @@ unsigned short TcpListener::getLocalPort() const if (getHandle() != priv::SocketImpl::invalidSocket()) { // Retrieve informations about the local end of the socket - sockaddr_in address; + sockaddr_in address; priv::SocketImpl::AddrLength size = sizeof(address); if (getsockname(getHandle(), reinterpret_cast(&address), &size) != -1) { @@ -114,9 +113,9 @@ Socket::Status TcpListener::accept(TcpSocket& socket) } // Accept a new connection - sockaddr_in address; + sockaddr_in address; priv::SocketImpl::AddrLength length = sizeof(address); - SocketHandle remote = ::accept(getHandle(), reinterpret_cast(&address), &length); + SocketHandle remote = ::accept(getHandle(), reinterpret_cast(&address), &length); // Check for errors if (remote == priv::SocketImpl::invalidSocket()) diff --git a/src/SFML/Network/TcpSocket.cpp b/src/SFML/Network/TcpSocket.cpp index 693562500..066a374a1 100644 --- a/src/SFML/Network/TcpSocket.cpp +++ b/src/SFML/Network/TcpSocket.cpp @@ -25,37 +25,36 @@ //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// -#include #include #include #include +#include #include + #include -#include #include +#include #ifdef _MSC_VER - #pragma warning(disable: 4127) // "conditional expression is constant" generated by the FD_SET macro +#pragma warning(disable : 4127) // "conditional expression is constant" generated by the FD_SET macro #endif namespace { - // Define the low-level send/receive flags, which depend on the OS - #ifdef SFML_SYSTEM_LINUX - const int flags = MSG_NOSIGNAL; - #else - const int flags = 0; - #endif -} +// Define the low-level send/receive flags, which depend on the OS +#ifdef SFML_SYSTEM_LINUX +const int flags = MSG_NOSIGNAL; +#else +const int flags = 0; +#endif +} // namespace namespace sf { //////////////////////////////////////////////////////////// -TcpSocket::TcpSocket() : -Socket(Tcp) +TcpSocket::TcpSocket() : Socket(Tcp) { - } @@ -65,7 +64,7 @@ unsigned short TcpSocket::getLocalPort() const if (getHandle() != priv::SocketImpl::invalidSocket()) { // Retrieve informations about the local end of the socket - sockaddr_in address; + sockaddr_in address; priv::SocketImpl::AddrLength size = sizeof(address); if (getsockname(getHandle(), reinterpret_cast(&address), &size) != -1) { @@ -84,7 +83,7 @@ std::optional TcpSocket::getRemoteAddress() const if (getHandle() != priv::SocketImpl::invalidSocket()) { // Retrieve informations about the remote end of the socket - sockaddr_in address; + sockaddr_in address; priv::SocketImpl::AddrLength size = sizeof(address); if (getpeername(getHandle(), reinterpret_cast(&address), &size) != -1) { @@ -103,7 +102,7 @@ unsigned short TcpSocket::getRemotePort() const if (getHandle() != priv::SocketImpl::invalidSocket()) { // Retrieve informations about the remote end of the socket - sockaddr_in address; + sockaddr_in address; priv::SocketImpl::AddrLength size = sizeof(address); if (getpeername(getHandle(), reinterpret_cast(&address), &size) != -1) { @@ -246,11 +245,12 @@ Socket::Status TcpSocket::send(const void* data, std::size_t size, std::size_t& int result = 0; for (sent = 0; sent < size; sent += static_cast(result)) { - #pragma GCC diagnostic push - #pragma GCC diagnostic ignored "-Wuseless-cast" +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wuseless-cast" // Send a chunk of data - result = static_cast(::send(getHandle(), static_cast(data) + sent, static_cast(size - sent), flags)); - #pragma GCC diagnostic pop + result = static_cast( + ::send(getHandle(), static_cast(data) + sent, static_cast(size - sent), flags)); +#pragma GCC diagnostic pop // Check for errors if (result < 0) @@ -281,11 +281,12 @@ Socket::Status TcpSocket::receive(void* data, std::size_t size, std::size_t& rec return Error; } - #pragma GCC diagnostic push - #pragma GCC diagnostic ignored "-Wuseless-cast" +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wuseless-cast" // Receive a chunk of bytes - int sizeReceived = static_cast(recv(getHandle(), static_cast(data), static_cast(size), flags)); - #pragma GCC diagnostic pop + int sizeReceived = static_cast( + recv(getHandle(), static_cast(data), static_cast(size), flags)); +#pragma GCC diagnostic pop // Check the number of bytes received if (sizeReceived > 0) @@ -326,26 +327,28 @@ Socket::Status TcpSocket::send(Packet& packet) // Allocate memory for the data block to send m_blockToSendBuffer.resize(sizeof(packetSize) + size); - // Copy the packet size and data into the block to send - #pragma GCC diagnostic push - #pragma GCC diagnostic ignored "-Wnull-dereference" // False positive. +// Copy the packet size and data into the block to send +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wnull-dereference" // False positive. std::memcpy(m_blockToSendBuffer.data(), &packetSize, sizeof(packetSize)); - #pragma GCC diagnostic pop +#pragma GCC diagnostic pop if (size > 0) std::memcpy(m_blockToSendBuffer.data() + sizeof(packetSize), data, size); - // These warnings are ignored here for portability, as even on Windows the - // signature of `send` might change depending on whether Win32 or MinGW is - // being used. - #pragma GCC diagnostic push - #pragma GCC diagnostic ignored "-Wuseless-cast" - #pragma GCC diagnostic push - #pragma GCC diagnostic ignored "-Wsign-conversion" +// These warnings are ignored here for portability, as even on Windows the +// signature of `send` might change depending on whether Win32 or MinGW is +// being used. +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wuseless-cast" +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wsign-conversion" // Send the data block std::size_t sent; - Status status = send(m_blockToSendBuffer.data() + packet.m_sendPos, static_cast(m_blockToSendBuffer.size() - packet.m_sendPos), sent); - #pragma GCC diagnostic pop - #pragma GCC diagnostic pop + Status status = send(m_blockToSendBuffer.data() + packet.m_sendPos, + static_cast(m_blockToSendBuffer.size() - packet.m_sendPos), + sent); +#pragma GCC diagnostic pop +#pragma GCC diagnostic pop // In the case of a partial send, record the location to resume from if (status == Partial) @@ -368,15 +371,15 @@ Socket::Status TcpSocket::receive(Packet& packet) packet.clear(); // We start by getting the size of the incoming packet - Uint32 packetSize = 0; - std::size_t received = 0; + Uint32 packetSize = 0; + std::size_t received = 0; if (m_pendingPacket.SizeReceived < sizeof(m_pendingPacket.Size)) { // Loop until we've received the entire size of the packet // (even a 4 byte variable may be received in more than one call) while (m_pendingPacket.SizeReceived < sizeof(m_pendingPacket.Size)) { - char* data = reinterpret_cast(&m_pendingPacket.Size) + m_pendingPacket.SizeReceived; + char* data = reinterpret_cast(&m_pendingPacket.Size) + m_pendingPacket.SizeReceived; Status status = receive(data, sizeof(m_pendingPacket.Size) - m_pendingPacket.SizeReceived, received); m_pendingPacket.SizeReceived += received; @@ -399,7 +402,7 @@ Socket::Status TcpSocket::receive(Packet& packet) { // Receive a chunk of data std::size_t sizeToGet = std::min(packetSize - m_pendingPacket.Data.size(), sizeof(buffer)); - Status status = receive(buffer, sizeToGet, received); + Status status = receive(buffer, sizeToGet, received); if (status != Done) return status; @@ -424,12 +427,8 @@ Socket::Status TcpSocket::receive(Packet& packet) //////////////////////////////////////////////////////////// -TcpSocket::PendingPacket::PendingPacket() : -Size (0), -SizeReceived(0), -Data () +TcpSocket::PendingPacket::PendingPacket() : Size(0), SizeReceived(0), Data() { - } } // namespace sf diff --git a/src/SFML/Network/UdpSocket.cpp b/src/SFML/Network/UdpSocket.cpp index 4bf5713e8..a2db3d0c2 100644 --- a/src/SFML/Network/UdpSocket.cpp +++ b/src/SFML/Network/UdpSocket.cpp @@ -25,23 +25,21 @@ //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// -#include #include #include #include +#include #include -#include + #include +#include namespace sf { //////////////////////////////////////////////////////////// -UdpSocket::UdpSocket() : -Socket (Udp), -m_buffer(MaxDatagramSize) +UdpSocket::UdpSocket() : Socket(Udp), m_buffer(MaxDatagramSize) { - } @@ -51,7 +49,7 @@ unsigned short UdpSocket::getLocalPort() const if (getHandle() != priv::SocketImpl::invalidSocket()) { // Retrieve informations about the local end of the socket - sockaddr_in address; + sockaddr_in address; priv::SocketImpl::AddrLength size = sizeof(address); if (getsockname(getHandle(), reinterpret_cast(&address), &size) != -1) { @@ -114,11 +112,17 @@ Socket::Status UdpSocket::send(const void* data, std::size_t size, const IpAddre // Build the target address sockaddr_in address = priv::SocketImpl::createAddress(remoteAddress.toInteger(), remotePort); - #pragma GCC diagnostic push - #pragma GCC diagnostic ignored "-Wuseless-cast" +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wuseless-cast" // Send the data (unlike TCP, all the data is always sent in one call) - int sent = static_cast(sendto(getHandle(), static_cast(data), static_cast(size), 0, reinterpret_cast(&address), sizeof(address))); - #pragma GCC diagnostic pop + int sent = static_cast( + sendto(getHandle(), + static_cast(data), + static_cast(size), + 0, + reinterpret_cast(&address), + sizeof(address))); +#pragma GCC diagnostic pop // Check for errors if (sent < 0) @@ -129,7 +133,11 @@ Socket::Status UdpSocket::send(const void* data, std::size_t size, const IpAddre //////////////////////////////////////////////////////////// -Socket::Status UdpSocket::receive(void* data, std::size_t size, std::size_t& received, std::optional& remoteAddress, unsigned short& remotePort) +Socket::Status UdpSocket::receive(void* data, + std::size_t size, + std::size_t& received, + std::optional& remoteAddress, + unsigned short& remotePort) { // First clear the variables to fill received = 0; @@ -146,12 +154,18 @@ Socket::Status UdpSocket::receive(void* data, std::size_t size, std::size_t& rec // Data that will be filled with the other computer's address sockaddr_in address = priv::SocketImpl::createAddress(INADDR_ANY, 0); - #pragma GCC diagnostic push - #pragma GCC diagnostic ignored "-Wuseless-cast" +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wuseless-cast" // Receive a chunk of bytes - priv::SocketImpl::AddrLength addressSize = sizeof(address); - int sizeReceived = static_cast(recvfrom(getHandle(), static_cast(data), static_cast(size), 0, reinterpret_cast(&address), &addressSize)); - #pragma GCC diagnostic pop + priv::SocketImpl::AddrLength addressSize = sizeof(address); + int sizeReceived = static_cast( + recvfrom(getHandle(), + static_cast(data), + static_cast(size), + 0, + reinterpret_cast(&address), + &addressSize)); +#pragma GCC diagnostic pop // Check for errors if (sizeReceived < 0) @@ -193,7 +207,7 @@ Socket::Status UdpSocket::receive(Packet& packet, std::optional& remo // Receive the datagram std::size_t received = 0; - Status status = receive(m_buffer.data(), m_buffer.size(), received, remoteAddress, remotePort); + Status status = receive(m_buffer.data(), m_buffer.size(), received, remoteAddress, remotePort); // If we received valid data, we can copy it to the user packet packet.clear(); diff --git a/src/SFML/Network/Unix/SocketImpl.cpp b/src/SFML/Network/Unix/SocketImpl.cpp index 06458f5d6..ea8f2b93b 100644 --- a/src/SFML/Network/Unix/SocketImpl.cpp +++ b/src/SFML/Network/Unix/SocketImpl.cpp @@ -27,10 +27,11 @@ //////////////////////////////////////////////////////////// #include #include -#include + #include #include #include +#include namespace sf @@ -81,7 +82,6 @@ void SocketImpl::setBlocking(SocketHandle sock, bool block) { if (fcntl(sock, F_SETFL, status | O_NONBLOCK) == -1) err() << "Failed to set file status flags: " << errno << std::endl; - } } diff --git a/src/SFML/Network/Unix/SocketImpl.hpp b/src/SFML/Network/Unix/SocketImpl.hpp index a8a4b29df..60fc40237 100644 --- a/src/SFML/Network/Unix/SocketImpl.hpp +++ b/src/SFML/Network/Unix/SocketImpl.hpp @@ -29,12 +29,13 @@ // Headers //////////////////////////////////////////////////////////// #include -#include -#include -#include -#include + #include #include +#include +#include +#include +#include #include @@ -50,12 +51,11 @@ namespace priv class SocketImpl { public: - //////////////////////////////////////////////////////////// // Types //////////////////////////////////////////////////////////// using AddrLength = socklen_t; - using Size = size_t; + using Size = size_t; //////////////////////////////////////////////////////////// /// \brief Create an internal sockaddr_in address diff --git a/src/SFML/Network/Win32/SocketImpl.cpp b/src/SFML/Network/Win32/SocketImpl.cpp index 0ecc475b7..0484f25b7 100644 --- a/src/SFML/Network/Win32/SocketImpl.cpp +++ b/src/SFML/Network/Win32/SocketImpl.cpp @@ -26,6 +26,7 @@ // Headers //////////////////////////////////////////////////////////// #include + #include diff --git a/src/SFML/Network/Win32/SocketImpl.hpp b/src/SFML/Network/Win32/SocketImpl.hpp index 2c6cf736f..0f91c10b8 100644 --- a/src/SFML/Network/Win32/SocketImpl.hpp +++ b/src/SFML/Network/Win32/SocketImpl.hpp @@ -30,6 +30,7 @@ //////////////////////////////////////////////////////////// #include #include + #include #include @@ -46,12 +47,11 @@ namespace priv class SocketImpl { public: - //////////////////////////////////////////////////////////// // Types //////////////////////////////////////////////////////////// using AddrLength = int; - using Size = int; + using Size = int; //////////////////////////////////////////////////////////// /// \brief Create an internal sockaddr_in address diff --git a/src/SFML/System/Android/Activity.cpp b/src/SFML/System/Android/Activity.cpp index 3638d6f76..eb8906430 100644 --- a/src/SFML/System/Android/Activity.cpp +++ b/src/SFML/System/Android/Activity.cpp @@ -28,18 +28,19 @@ // Headers //////////////////////////////////////////////////////////// #include + #include + #include #define LOGE(...) ((void)__android_log_print(ANDROID_LOG_INFO, "sfml-error", __VA_ARGS__)) -LogcatStream::LogcatStream() : -std::streambuf() +LogcatStream::LogcatStream() : std::streambuf() { // Nothing to do } -std::streambuf::int_type LogcatStream::overflow (std::streambuf::int_type c) +std::streambuf::int_type LogcatStream::overflow(std::streambuf::int_type c) { if (c == '\n') { @@ -76,5 +77,5 @@ ActivityStates& getActivity() return *states; } -} -} +} // namespace priv +} // namespace sf diff --git a/src/SFML/System/Android/Activity.hpp b/src/SFML/System/Android/Activity.hpp index fd818cbe9..d0f785f12 100644 --- a/src/SFML/System/Android/Activity.hpp +++ b/src/SFML/System/Android/Activity.hpp @@ -28,15 +28,17 @@ //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// -#include #include -#include +#include + #include -#include -#include -#include +#include + #include #include +#include +#include +#include class SFML_SYSTEM_API LogcatStream : public std::streambuf { @@ -56,16 +58,16 @@ namespace priv struct ActivityStates { ANativeActivity* activity; - ANativeWindow* window; + ANativeWindow* window; ALooper* looper; AInputQueue* inputQueue; AConfiguration* config; - EGLDisplay display; + EGLDisplay display; EglContext* context; - void* savedState; + void* savedState; size_t savedStateSize; std::recursive_mutex mutex; @@ -74,8 +76,8 @@ struct ActivityStates int (*processEvent)(int fd, int events, void* data); std::unordered_map touchEvents; - Vector2i mousePosition; - bool isButtonPressed[Mouse::ButtonCount]; + Vector2i mousePosition; + bool isButtonPressed[Mouse::ButtonCount]; bool mainOver; diff --git a/src/SFML/System/Android/NativeActivity.cpp b/src/SFML/System/Android/NativeActivity.cpp index 2833a99a9..3592ddb7a 100644 --- a/src/SFML/System/Android/NativeActivity.cpp +++ b/src/SFML/System/Android/NativeActivity.cpp @@ -25,8 +25,8 @@ //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// -#include #include +#include namespace sf { diff --git a/src/SFML/System/Android/ResourceStream.cpp b/src/SFML/System/Android/ResourceStream.cpp index 1317a96f0..7fe73199a 100644 --- a/src/SFML/System/Android/ResourceStream.cpp +++ b/src/SFML/System/Android/ResourceStream.cpp @@ -26,8 +26,9 @@ //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// -#include #include +#include + #include @@ -37,10 +38,9 @@ namespace priv { //////////////////////////////////////////////////////////// -ResourceStream::ResourceStream(const std::filesystem::path& filename) : -m_file (nullptr) +ResourceStream::ResourceStream(const std::filesystem::path& filename) : m_file(nullptr) { - ActivityStates& states = getActivity(); + ActivityStates& states = getActivity(); std::scoped_lock lock(states.mutex); m_file = AAssetManager_open(states.activity->assetManager, filename.c_str(), AASSET_MODE_UNKNOWN); } @@ -57,7 +57,7 @@ ResourceStream::~ResourceStream() //////////////////////////////////////////////////////////// -Int64 ResourceStream::read(void *data, Int64 size) +Int64 ResourceStream::read(void* data, Int64 size) { if (m_file) { diff --git a/src/SFML/System/Android/ResourceStream.hpp b/src/SFML/System/Android/ResourceStream.hpp index fbdb81448..da559fd0a 100644 --- a/src/SFML/System/Android/ResourceStream.hpp +++ b/src/SFML/System/Android/ResourceStream.hpp @@ -29,8 +29,11 @@ // Headers //////////////////////////////////////////////////////////// #include + #include + #include + #include #include @@ -46,7 +49,6 @@ namespace priv class SFML_SYSTEM_API ResourceStream : public InputStream { public: - //////////////////////////////////////////////////////////// /// \brief Default constructor /// @@ -70,7 +72,7 @@ public: /// \return The number of bytes actually read, or -1 on error /// //////////////////////////////////////////////////////////// - Int64 read(void *data, Int64 size) override; + Int64 read(void* data, Int64 size) override; //////////////////////////////////////////////////////////// /// \brief Change the current reading position in the asset file @@ -99,7 +101,6 @@ public: Int64 getSize() override; private: - //////////////////////////////////////////////////////////// // Member data //////////////////////////////////////////////////////////// diff --git a/src/SFML/System/Android/SuspendAwareClock.cpp b/src/SFML/System/Android/SuspendAwareClock.cpp index c3bb256d0..997ccc0a0 100644 --- a/src/SFML/System/Android/SuspendAwareClock.cpp +++ b/src/SFML/System/Android/SuspendAwareClock.cpp @@ -26,6 +26,7 @@ // Headers //////////////////////////////////////////////////////////// #include + #include namespace sf @@ -37,7 +38,7 @@ SuspendAwareClock::time_point SuspendAwareClock::now() noexcept #ifdef CLOCK_BOOTTIME clock_gettime(CLOCK_BOOTTIME, &ts); #else - #error "CLOCK_BOOTTIME is essential for SuspendAwareClock to work" +#error "CLOCK_BOOTTIME is essential for SuspendAwareClock to work" #endif // CLOCK_BOOTTIME return time_point(std::chrono::seconds(ts.tv_sec) + std::chrono::nanoseconds(ts.tv_nsec)); } diff --git a/src/SFML/System/Clock.cpp b/src/SFML/System/Clock.cpp index f9c0ea5a3..727a17076 100644 --- a/src/SFML/System/Clock.cpp +++ b/src/SFML/System/Clock.cpp @@ -32,8 +32,7 @@ namespace sf { //////////////////////////////////////////////////////////// -Clock::Clock() : -m_startTime(ClockImpl::now()) +Clock::Clock() : m_startTime(ClockImpl::now()) { } @@ -48,9 +47,9 @@ Time Clock::getElapsedTime() const //////////////////////////////////////////////////////////// Time Clock::restart() { - const ClockImpl::time_point now = ClockImpl::now(); - Time elapsed = durationToTime(now - m_startTime); - m_startTime = now; + const ClockImpl::time_point now = ClockImpl::now(); + Time elapsed = durationToTime(now - m_startTime); + m_startTime = now; return elapsed; } diff --git a/src/SFML/System/Err.cpp b/src/SFML/System/Err.cpp index e6d8aec5a..1fda4a2a4 100644 --- a/src/SFML/System/Err.cpp +++ b/src/SFML/System/Err.cpp @@ -26,9 +26,10 @@ // Headers //////////////////////////////////////////////////////////// #include + +#include #include #include -#include namespace @@ -38,12 +39,11 @@ namespace class DefaultErrStreamBuf : public std::streambuf { public: - DefaultErrStreamBuf() { // Allocate the write buffer - constexpr int size = 64; - char* buffer = new char[size]; + constexpr int size = 64; + char* buffer = new char[size]; setp(buffer, buffer + size); } @@ -57,7 +57,6 @@ public: } private: - int overflow(int character) override { if ((character != EOF) && (pptr() != epptr())) @@ -94,7 +93,7 @@ private: return 0; } }; -} +} // namespace namespace sf { @@ -102,7 +101,7 @@ namespace sf std::ostream& err() { static DefaultErrStreamBuf buffer; - static std::ostream stream(&buffer); + static std::ostream stream(&buffer); return stream; } diff --git a/src/SFML/System/FileInputStream.cpp b/src/SFML/System/FileInputStream.cpp index 9f108219f..a928ec84d 100644 --- a/src/SFML/System/FileInputStream.cpp +++ b/src/SFML/System/FileInputStream.cpp @@ -29,8 +29,8 @@ #ifdef SFML_SYSTEM_ANDROID #include #endif -#include #include +#include namespace sf { diff --git a/src/SFML/System/MemoryInputStream.cpp b/src/SFML/System/MemoryInputStream.cpp index c2fc994c6..3a8720e0b 100644 --- a/src/SFML/System/MemoryInputStream.cpp +++ b/src/SFML/System/MemoryInputStream.cpp @@ -26,16 +26,14 @@ // Headers //////////////////////////////////////////////////////////// #include + #include namespace sf { //////////////////////////////////////////////////////////// -MemoryInputStream::MemoryInputStream() : -m_data (nullptr), -m_size (0), -m_offset(0) +MemoryInputStream::MemoryInputStream() : m_data(nullptr), m_size(0), m_offset(0) { } @@ -43,8 +41,8 @@ m_offset(0) //////////////////////////////////////////////////////////// void MemoryInputStream::open(const void* data, std::size_t sizeInBytes) { - m_data = static_cast(data); - m_size = static_cast(sizeInBytes); + m_data = static_cast(data); + m_size = static_cast(sizeInBytes); m_offset = 0; } @@ -56,7 +54,7 @@ Int64 MemoryInputStream::read(void* data, Int64 size) return -1; Int64 endPosition = m_offset + size; - Int64 count = endPosition <= m_size ? size : m_size - m_offset; + Int64 count = endPosition <= m_size ? size : m_size - m_offset; if (count > 0) { diff --git a/src/SFML/System/Sleep.cpp b/src/SFML/System/Sleep.cpp index bc0522311..c39985cb2 100644 --- a/src/SFML/System/Sleep.cpp +++ b/src/SFML/System/Sleep.cpp @@ -29,9 +29,9 @@ #include #if defined(SFML_SYSTEM_WINDOWS) - #include +#include #else - #include +#include #endif diff --git a/src/SFML/System/String.cpp b/src/SFML/System/String.cpp index 3eb232b53..10852eaf2 100644 --- a/src/SFML/System/String.cpp +++ b/src/SFML/System/String.cpp @@ -27,8 +27,9 @@ //////////////////////////////////////////////////////////// #include #include -#include + #include +#include namespace sf @@ -119,15 +120,13 @@ String::String(const Uint32* utf32String) //////////////////////////////////////////////////////////// -String::String(const std::basic_string& utf32String) : -m_string(utf32String) +String::String(const std::basic_string& utf32String) : m_string(utf32String) { } //////////////////////////////////////////////////////////// -String::String(const String& copy) : -m_string(copy.m_string) +String::String(const String& copy) : m_string(copy.m_string) { } @@ -218,7 +217,7 @@ std::basic_string String::toUtf32() const //////////////////////////////////////////////////////////// -String& String::operator =(const String& right) +String& String::operator=(const String& right) { m_string = right.m_string; return *this; @@ -226,7 +225,7 @@ String& String::operator =(const String& right) //////////////////////////////////////////////////////////// -String& String::operator +=(const String& right) +String& String::operator+=(const String& right) { m_string += right.m_string; return *this; @@ -234,14 +233,14 @@ String& String::operator +=(const String& right) //////////////////////////////////////////////////////////// -Uint32 String::operator [](std::size_t index) const +Uint32 String::operator[](std::size_t index) const { return m_string[index]; } //////////////////////////////////////////////////////////// -Uint32& String::operator [](std::size_t index) +Uint32& String::operator[](std::size_t index) { return m_string[index]; } @@ -300,8 +299,8 @@ void String::replace(std::size_t position, std::size_t length, const String& rep void String::replace(const String& searchFor, const String& replaceWith) { std::size_t step = replaceWith.getSize(); - std::size_t len = searchFor.getSize(); - std::size_t pos = find(searchFor); + std::size_t len = searchFor.getSize(); + std::size_t pos = find(searchFor); // Replace each occurrence of search while (pos != InvalidPos) @@ -355,49 +354,49 @@ String::ConstIterator String::end() const //////////////////////////////////////////////////////////// -bool operator ==(const String& left, const String& right) +bool operator==(const String& left, const String& right) { return left.m_string == right.m_string; } //////////////////////////////////////////////////////////// -bool operator !=(const String& left, const String& right) +bool operator!=(const String& left, const String& right) { return !(left == right); } //////////////////////////////////////////////////////////// -bool operator <(const String& left, const String& right) +bool operator<(const String& left, const String& right) { return left.m_string < right.m_string; } //////////////////////////////////////////////////////////// -bool operator >(const String& left, const String& right) +bool operator>(const String& left, const String& right) { return right < left; } //////////////////////////////////////////////////////////// -bool operator <=(const String& left, const String& right) +bool operator<=(const String& left, const String& right) { return !(right < left); } //////////////////////////////////////////////////////////// -bool operator >=(const String& left, const String& right) +bool operator>=(const String& left, const String& right) { return !(left < right); } //////////////////////////////////////////////////////////// -String operator +(const String& left, const String& right) +String operator+(const String& left, const String& right) { String string = left; string += right; diff --git a/src/SFML/System/Unix/SleepImpl.cpp b/src/SFML/System/Unix/SleepImpl.cpp index 599a448dd..9446377da 100644 --- a/src/SFML/System/Unix/SleepImpl.cpp +++ b/src/SFML/System/Unix/SleepImpl.cpp @@ -25,8 +25,9 @@ //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// -#include #include +#include + #include #include @@ -40,7 +41,7 @@ void sleepImpl(Time time) // Construct the time to wait timespec ti; - ti.tv_sec = static_cast(usecs / 1000000); + ti.tv_sec = static_cast(usecs / 1000000); ti.tv_nsec = static_cast((usecs % 1000000) * 1000); // Wait... diff --git a/src/SFML/System/Unix/SleepImpl.hpp b/src/SFML/System/Unix/SleepImpl.hpp index dbaff3741..e536710ad 100644 --- a/src/SFML/System/Unix/SleepImpl.hpp +++ b/src/SFML/System/Unix/SleepImpl.hpp @@ -31,7 +31,10 @@ #include -namespace sf { class Time; } +namespace sf +{ +class Time; +} namespace sf::priv { diff --git a/src/SFML/System/Vector2.cpp b/src/SFML/System/Vector2.cpp index a2b35bce4..9c8b389d2 100644 --- a/src/SFML/System/Vector2.cpp +++ b/src/SFML/System/Vector2.cpp @@ -23,9 +23,10 @@ //////////////////////////////////////////////////////////// #include -#include + #include #include +#include namespace sf @@ -75,9 +76,7 @@ Vector2 Vector2::rotatedBy(Angle angle) const T sin = std::sin(static_cast(angle.asRadians())); // Don't manipulate x and y separately, otherwise they're overwritten too early - return Vector2( - cos * x - sin * y, - sin * x + cos * y); + return Vector2(cos * x - sin * y, sin * x + cos * y); } @@ -111,7 +110,7 @@ T Vector2::length() const return std::hypot(x, y); } -} +} // namespace sf //////////////////////////////////////////////////////////// diff --git a/src/SFML/System/Vector3.cpp b/src/SFML/System/Vector3.cpp index 9ff43ab8a..fa52b9fc7 100644 --- a/src/SFML/System/Vector3.cpp +++ b/src/SFML/System/Vector3.cpp @@ -23,9 +23,10 @@ //////////////////////////////////////////////////////////// #include -#include + #include #include +#include namespace sf @@ -50,7 +51,7 @@ T Vector3::length() const return std::hypot(x, y, z); } -} +} // namespace sf //////////////////////////////////////////////////////////// diff --git a/src/SFML/System/Win32/SleepImpl.cpp b/src/SFML/System/Win32/SleepImpl.cpp index 8207d48f4..708e1622b 100644 --- a/src/SFML/System/Win32/SleepImpl.cpp +++ b/src/SFML/System/Win32/SleepImpl.cpp @@ -25,9 +25,10 @@ //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// +#include #include #include -#include + #include namespace sf::priv diff --git a/src/SFML/System/Win32/SleepImpl.hpp b/src/SFML/System/Win32/SleepImpl.hpp index 4ab282830..da1d39fe3 100644 --- a/src/SFML/System/Win32/SleepImpl.hpp +++ b/src/SFML/System/Win32/SleepImpl.hpp @@ -30,7 +30,10 @@ //////////////////////////////////////////////////////////// #include -namespace sf { class Time; } +namespace sf +{ +class Time; +} namespace sf::priv { diff --git a/src/SFML/Window/Android/ClipboardImpl.cpp b/src/SFML/Window/Android/ClipboardImpl.cpp index 98036166c..4cddf1490 100644 --- a/src/SFML/Window/Android/ClipboardImpl.cpp +++ b/src/SFML/Window/Android/ClipboardImpl.cpp @@ -25,9 +25,10 @@ //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// -#include #include #include +#include + #include diff --git a/src/SFML/Window/Android/ClipboardImpl.hpp b/src/SFML/Window/Android/ClipboardImpl.hpp index 6b19716a4..4537e00cc 100644 --- a/src/SFML/Window/Android/ClipboardImpl.hpp +++ b/src/SFML/Window/Android/ClipboardImpl.hpp @@ -39,7 +39,6 @@ namespace priv class ClipboardImpl { public: - //////////////////////////////////////////////////////////// /// \brief Get the content of the clipboard as string data /// diff --git a/src/SFML/Window/Android/CursorImpl.cpp b/src/SFML/Window/Android/CursorImpl.cpp index f09b269d0..91bf5e245 100644 --- a/src/SFML/Window/Android/CursorImpl.cpp +++ b/src/SFML/Window/Android/CursorImpl.cpp @@ -58,4 +58,3 @@ bool CursorImpl::loadFromSystem(Cursor::Type /* type */) } // namespace priv } // namespace sf - diff --git a/src/SFML/Window/Android/CursorImpl.hpp b/src/SFML/Window/Android/CursorImpl.hpp index bb4b14709..eecbb3f07 100644 --- a/src/SFML/Window/Android/CursorImpl.hpp +++ b/src/SFML/Window/Android/CursorImpl.hpp @@ -28,8 +28,8 @@ //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// -#include #include +#include namespace sf @@ -46,7 +46,6 @@ namespace priv class CursorImpl { public: - //////////////////////////////////////////////////////////// /// \brief Default constructor /// diff --git a/src/SFML/Window/Android/InputImpl.cpp b/src/SFML/Window/Android/InputImpl.cpp index 2405cd977..3b560bf8f 100644 --- a/src/SFML/Window/Android/InputImpl.cpp +++ b/src/SFML/Window/Android/InputImpl.cpp @@ -25,12 +25,14 @@ //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// -#include #include #include +#include + +#include + #include #include -#include namespace sf @@ -49,7 +51,7 @@ void InputImpl::setVirtualKeyboardVisible(bool visible) { // todo: Check if the window is active - ActivityStates& states = getActivity(); + ActivityStates& states = getActivity(); std::scoped_lock lock(states.mutex); // Initializes JNI @@ -60,8 +62,8 @@ void InputImpl::setVirtualKeyboardVisible(bool visible) JavaVMAttachArgs lJavaVMAttachArgs; lJavaVMAttachArgs.version = JNI_VERSION_1_6; - lJavaVMAttachArgs.name = "NativeThread"; - lJavaVMAttachArgs.group = nullptr; + lJavaVMAttachArgs.name = "NativeThread"; + lJavaVMAttachArgs.group = nullptr; jint lResult = lJavaVM->AttachCurrentThread(&lJNIEnv, &lJavaVMAttachArgs); @@ -69,34 +71,31 @@ void InputImpl::setVirtualKeyboardVisible(bool visible) err() << "Failed to initialize JNI, couldn't switch the keyboard visibility" << std::endl; // Retrieves NativeActivity - jobject lNativeActivity = states.activity->clazz; - jclass ClassNativeActivity = lJNIEnv->GetObjectClass(lNativeActivity); + jobject lNativeActivity = states.activity->clazz; + jclass ClassNativeActivity = lJNIEnv->GetObjectClass(lNativeActivity); // Retrieves Context.INPUT_METHOD_SERVICE - jclass ClassContext = lJNIEnv->FindClass("android/content/Context"); + jclass ClassContext = lJNIEnv->FindClass("android/content/Context"); jfieldID FieldINPUT_METHOD_SERVICE = lJNIEnv->GetStaticFieldID(ClassContext, - "INPUT_METHOD_SERVICE", "Ljava/lang/String;"); - jobject INPUT_METHOD_SERVICE = lJNIEnv->GetStaticObjectField(ClassContext, - FieldINPUT_METHOD_SERVICE); + "INPUT_METHOD_SERVICE", + "Ljava/lang/String;"); + jobject INPUT_METHOD_SERVICE = lJNIEnv->GetStaticObjectField(ClassContext, FieldINPUT_METHOD_SERVICE); lJNIEnv->DeleteLocalRef(ClassContext); // Runs getSystemService(Context.INPUT_METHOD_SERVICE) - jclass ClassInputMethodManager = - lJNIEnv->FindClass("android/view/inputmethod/InputMethodManager"); - jmethodID MethodGetSystemService = lJNIEnv->GetMethodID(ClassNativeActivity, - "getSystemService", "(Ljava/lang/String;)Ljava/lang/Object;"); - jobject lInputMethodManager = lJNIEnv->CallObjectMethod(lNativeActivity, - MethodGetSystemService, INPUT_METHOD_SERVICE); + jclass ClassInputMethodManager = lJNIEnv->FindClass("android/view/inputmethod/InputMethodManager"); + jmethodID MethodGetSystemService = lJNIEnv->GetMethodID(ClassNativeActivity, + "getSystemService", + "(Ljava/lang/String;)Ljava/lang/Object;"); + jobject lInputMethodManager = lJNIEnv->CallObjectMethod(lNativeActivity, MethodGetSystemService, INPUT_METHOD_SERVICE); lJNIEnv->DeleteLocalRef(INPUT_METHOD_SERVICE); // Runs getWindow().getDecorView() - jmethodID MethodGetWindow = lJNIEnv->GetMethodID(ClassNativeActivity, - "getWindow", "()Landroid/view/Window;"); - jobject lWindow = lJNIEnv->CallObjectMethod(lNativeActivity, MethodGetWindow); - jclass ClassWindow = lJNIEnv->FindClass("android/view/Window"); - jmethodID MethodGetDecorView = lJNIEnv->GetMethodID(ClassWindow, - "getDecorView", "()Landroid/view/View;"); - jobject lDecorView = lJNIEnv->CallObjectMethod(lWindow, MethodGetDecorView); + jmethodID MethodGetWindow = lJNIEnv->GetMethodID(ClassNativeActivity, "getWindow", "()Landroid/view/Window;"); + jobject lWindow = lJNIEnv->CallObjectMethod(lNativeActivity, MethodGetWindow); + jclass ClassWindow = lJNIEnv->FindClass("android/view/Window"); + jmethodID MethodGetDecorView = lJNIEnv->GetMethodID(ClassWindow, "getDecorView", "()Landroid/view/View;"); + jobject lDecorView = lJNIEnv->CallObjectMethod(lWindow, MethodGetDecorView); lJNIEnv->DeleteLocalRef(lWindow); lJNIEnv->DeleteLocalRef(ClassWindow); @@ -104,25 +103,23 @@ void InputImpl::setVirtualKeyboardVisible(bool visible) { // Runs lInputMethodManager.showSoftInput(...) jmethodID MethodShowSoftInput = lJNIEnv->GetMethodID(ClassInputMethodManager, - "showSoftInput", "(Landroid/view/View;I)Z"); - lJNIEnv->CallBooleanMethod(lInputMethodManager, - MethodShowSoftInput, lDecorView, lFlags); + "showSoftInput", + "(Landroid/view/View;I)Z"); + lJNIEnv->CallBooleanMethod(lInputMethodManager, MethodShowSoftInput, lDecorView, lFlags); } else { // Runs lWindow.getViewToken() - jclass ClassView = lJNIEnv->FindClass("android/view/View"); - jmethodID MethodGetWindowToken = lJNIEnv->GetMethodID(ClassView, - "getWindowToken", "()Landroid/os/IBinder;"); - jobject lBinder = lJNIEnv->CallObjectMethod(lDecorView, - MethodGetWindowToken); + jclass ClassView = lJNIEnv->FindClass("android/view/View"); + jmethodID MethodGetWindowToken = lJNIEnv->GetMethodID(ClassView, "getWindowToken", "()Landroid/os/IBinder;"); + jobject lBinder = lJNIEnv->CallObjectMethod(lDecorView, MethodGetWindowToken); lJNIEnv->DeleteLocalRef(ClassView); // lInputMethodManager.hideSoftInput(...) jmethodID MethodHideSoftInput = lJNIEnv->GetMethodID(ClassInputMethodManager, - "hideSoftInputFromWindow", "(Landroid/os/IBinder;I)Z"); - lJNIEnv->CallBooleanMethod(lInputMethodManager, - MethodHideSoftInput, lBinder, lFlags); + "hideSoftInputFromWindow", + "(Landroid/os/IBinder;I)Z"); + lJNIEnv->CallBooleanMethod(lInputMethodManager, MethodHideSoftInput, lBinder, lFlags); lJNIEnv->DeleteLocalRef(lBinder); } lJNIEnv->DeleteLocalRef(ClassNativeActivity); @@ -138,7 +135,7 @@ bool InputImpl::isMouseButtonPressed(Mouse::Button button) { ALooper_pollAll(0, nullptr, nullptr, nullptr); - ActivityStates& states = getActivity(); + ActivityStates& states = getActivity(); std::scoped_lock lock(states.mutex); return states.isButtonPressed[button]; @@ -150,7 +147,7 @@ Vector2i InputImpl::getMousePosition() { ALooper_pollAll(0, nullptr, nullptr, nullptr); - ActivityStates& states = getActivity(); + ActivityStates& states = getActivity(); std::scoped_lock lock(states.mutex); return states.mousePosition; @@ -183,7 +180,7 @@ bool InputImpl::isTouchDown(unsigned int finger) { ALooper_pollAll(0, nullptr, nullptr, nullptr); - ActivityStates& states = getActivity(); + ActivityStates& states = getActivity(); std::scoped_lock lock(states.mutex); return states.touchEvents.find(static_cast(finger)) != states.touchEvents.end(); @@ -195,7 +192,7 @@ Vector2i InputImpl::getTouchPosition(unsigned int finger) { ALooper_pollAll(0, nullptr, nullptr, nullptr); - ActivityStates& states = getActivity(); + ActivityStates& states = getActivity(); std::scoped_lock lock(states.mutex); return states.touchEvents.find(static_cast(finger))->second; diff --git a/src/SFML/Window/Android/InputImpl.hpp b/src/SFML/Window/Android/InputImpl.hpp index d2783e15a..86c8c575a 100644 --- a/src/SFML/Window/Android/InputImpl.hpp +++ b/src/SFML/Window/Android/InputImpl.hpp @@ -43,7 +43,6 @@ namespace priv class InputImpl { public: - //////////////////////////////////////////////////////////// /// \brief Check if a key is pressed /// diff --git a/src/SFML/Window/Android/JoystickImpl.cpp b/src/SFML/Window/Android/JoystickImpl.cpp index 802e6f85b..847fd5e20 100644 --- a/src/SFML/Window/Android/JoystickImpl.cpp +++ b/src/SFML/Window/Android/JoystickImpl.cpp @@ -39,7 +39,6 @@ void JoystickImpl::initialize() } - //////////////////////////////////////////////////////////// void JoystickImpl::cleanup() { diff --git a/src/SFML/Window/Android/JoystickImpl.hpp b/src/SFML/Window/Android/JoystickImpl.hpp index 91384e18d..0709d7b88 100644 --- a/src/SFML/Window/Android/JoystickImpl.hpp +++ b/src/SFML/Window/Android/JoystickImpl.hpp @@ -37,7 +37,6 @@ namespace priv class JoystickImpl { public: - //////////////////////////////////////////////////////////// /// \brief Perform the global initialization of the joystick module /// @@ -101,7 +100,6 @@ public: [[nodiscard]] JoystickState update(); private: - //////////////////////////////////////////////////////////// // Member data //////////////////////////////////////////////////////////// diff --git a/src/SFML/Window/Android/SensorImpl.cpp b/src/SFML/Window/Android/SensorImpl.cpp index 8215e856f..027d5e3db 100644 --- a/src/SFML/Window/Android/SensorImpl.cpp +++ b/src/SFML/Window/Android/SensorImpl.cpp @@ -25,14 +25,15 @@ //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// -#include #include +#include + #include #if defined(__clang__) - #pragma clang diagnostic ignored "-Wdeprecated-declarations" +#pragma clang diagnostic ignored "-Wdeprecated-declarations" #elif defined(__GNUC__) - #pragma GCC diagnostic ignored "-Wdeprecated-declarations" +#pragma GCC diagnostic ignored "-Wdeprecated-declarations" #endif // Define missing constants @@ -42,11 +43,11 @@ namespace { - ALooper* looper; - ASensorManager* sensorManager; - ASensorEventQueue* sensorEventQueue; - sf::Vector3f sensorData[sf::Sensor::Count]; -} +ALooper* looper; +ASensorManager* sensorManager; +ASensorEventQueue* sensorEventQueue; +sf::Vector3f sensorData[sf::Sensor::Count]; +} // namespace namespace sf @@ -59,16 +60,15 @@ void SensorImpl::initialize() // Get the looper associated with this thread looper = ALooper_forThread(); - // Get the unique sensor manager - #if ANDROID_API >= 26 || __ANDROID_API__ >= 26 - sensorManager = ASensorManager_getInstanceForPackage(nullptr); - #else - sensorManager = ASensorManager_getInstance(); - #endif +// Get the unique sensor manager +#if ANDROID_API >= 26 || __ANDROID_API__ >= 26 + sensorManager = ASensorManager_getInstanceForPackage(nullptr); +#else + sensorManager = ASensorManager_getInstance(); +#endif // Create the sensor events queue and attach it to the looper - sensorEventQueue = ASensorManager_createEventQueue(sensorManager, looper, - 1, &processSensorEvents, nullptr); + sensorEventQueue = ASensorManager_createEventQueue(sensorManager, looper, 1, &processSensorEvents, nullptr); } @@ -85,7 +85,7 @@ bool SensorImpl::isAvailable(Sensor::Type sensor) { const ASensor* available = getDefaultSensor(sensor); - return available? true : false; + return available ? true : false; } @@ -143,9 +143,12 @@ void SensorImpl::setEnabled(bool enabled) ASensor const* SensorImpl::getDefaultSensor(Sensor::Type sensor) { // Find the Android sensor type - static int types[] = {ASENSOR_TYPE_ACCELEROMETER, ASENSOR_TYPE_GYROSCOPE, - ASENSOR_TYPE_MAGNETIC_FIELD, ASENSOR_TYPE_GRAVITY, ASENSOR_TYPE_LINEAR_ACCELERATION, - ASENSOR_TYPE_ORIENTATION}; + static int types[] = {ASENSOR_TYPE_ACCELEROMETER, + ASENSOR_TYPE_GYROSCOPE, + ASENSOR_TYPE_MAGNETIC_FIELD, + ASENSOR_TYPE_GRAVITY, + ASENSOR_TYPE_LINEAR_ACCELERATION, + ASENSOR_TYPE_ORIENTATION}; int type = types[sensor]; @@ -162,47 +165,47 @@ int SensorImpl::processSensorEvents(int /* fd */, int /* events */, void* /* sen while (ASensorEventQueue_getEvents(sensorEventQueue, &event, 1) > 0) { unsigned int type = Sensor::Count; - Vector3f data; + Vector3f data; switch (event.type) { case ASENSOR_TYPE_ACCELEROMETER: - type = Sensor::Accelerometer; + type = Sensor::Accelerometer; data.x = event.acceleration.x; data.y = event.acceleration.y; data.z = event.acceleration.z; break; case ASENSOR_TYPE_GYROSCOPE: - type = Sensor::Gyroscope; + type = Sensor::Gyroscope; data.x = event.vector.x; data.y = event.vector.y; data.z = event.vector.z; break; case ASENSOR_TYPE_MAGNETIC_FIELD: - type = Sensor::Magnetometer; + type = Sensor::Magnetometer; data.x = event.magnetic.x; data.y = event.magnetic.y; data.z = event.magnetic.z; break; case ASENSOR_TYPE_GRAVITY: - type = Sensor::Gravity; + type = Sensor::Gravity; data.x = event.vector.x; data.y = event.vector.y; data.z = event.vector.z; break; case ASENSOR_TYPE_LINEAR_ACCELERATION: - type = Sensor::UserAcceleration; + type = Sensor::UserAcceleration; data.x = event.acceleration.x; data.y = event.acceleration.y; data.z = event.acceleration.z; break; case ASENSOR_TYPE_ORIENTATION: - type = Sensor::Orientation; + type = Sensor::Orientation; data.x = event.vector.x; data.y = event.vector.y; data.z = event.vector.z; diff --git a/src/SFML/Window/Android/SensorImpl.hpp b/src/SFML/Window/Android/SensorImpl.hpp index d74953f0b..5bf1961ff 100644 --- a/src/SFML/Window/Android/SensorImpl.hpp +++ b/src/SFML/Window/Android/SensorImpl.hpp @@ -29,6 +29,7 @@ // Headers //////////////////////////////////////////////////////////// #include + #include @@ -43,7 +44,6 @@ namespace priv class SensorImpl { public: - //////////////////////////////////////////////////////////// /// \brief Perform the global initialization of the sensor module /// @@ -99,7 +99,6 @@ public: void setEnabled(bool enabled); private: - //////////////////////////////////////////////////////////// /// \brief Get the default Android sensor matching the sensor type /// diff --git a/src/SFML/Window/Android/VideoModeImpl.cpp b/src/SFML/Window/Android/VideoModeImpl.cpp index 046e3ca0e..6dd78cfb4 100644 --- a/src/SFML/Window/Android/VideoModeImpl.cpp +++ b/src/SFML/Window/Android/VideoModeImpl.cpp @@ -25,10 +25,11 @@ //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// -#include #include -#include #include +#include +#include + #include namespace sf @@ -53,7 +54,7 @@ VideoMode VideoModeImpl::getDesktopMode() { // Get the activity states priv::ActivityStates& states = priv::getActivity(); - std::scoped_lock lock(states.mutex); + std::scoped_lock lock(states.mutex); return VideoMode(Vector2u(states.screenSize)); } diff --git a/src/SFML/Window/Android/WindowImplAndroid.cpp b/src/SFML/Window/Android/WindowImplAndroid.cpp index 586a610ba..de14a6567 100644 --- a/src/SFML/Window/Android/WindowImplAndroid.cpp +++ b/src/SFML/Window/Android/WindowImplAndroid.cpp @@ -26,18 +26,20 @@ //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// -#include // important to be included first (conflict with None) +#include #include #include -#include +#include + +#include + #include #include -#include // Define missing constants for older API levels #if __ANDROID_API__ < 13 - #define AMOTION_EVENT_ACTION_HOVER_MOVE 0x00000007 - #define AMOTION_EVENT_ACTION_SCROLL 0x00000008 +#define AMOTION_EVENT_ACTION_HOVER_MOVE 0x00000007 +#define AMOTION_EVENT_ACTION_SCROLL 0x00000008 #endif //////////////////////////////////////////////////////////// @@ -50,30 +52,33 @@ namespace priv WindowImplAndroid* WindowImplAndroid::singleInstance = nullptr; //////////////////////////////////////////////////////////// -WindowImplAndroid::WindowImplAndroid(WindowHandle /* handle */) -: m_size(0, 0) -, m_windowBeingCreated(false) -, m_windowBeingDestroyed(false) -, m_hasFocus(false) +WindowImplAndroid::WindowImplAndroid(WindowHandle /* handle */) : +m_size(0, 0), +m_windowBeingCreated(false), +m_windowBeingDestroyed(false), +m_hasFocus(false) { } //////////////////////////////////////////////////////////// -WindowImplAndroid::WindowImplAndroid(VideoMode mode, const String& /* title */, unsigned long style, const ContextSettings& /* settings */) -: m_size(mode.size) -, m_windowBeingCreated(false) -, m_windowBeingDestroyed(false) -, m_hasFocus(false) +WindowImplAndroid::WindowImplAndroid(VideoMode mode, + const String& /* title */, + unsigned long style, + const ContextSettings& /* settings */) : +m_size(mode.size), +m_windowBeingCreated(false), +m_windowBeingDestroyed(false), +m_hasFocus(false) { - ActivityStates& states = getActivity(); + ActivityStates& states = getActivity(); std::scoped_lock lock(states.mutex); - if (style& Style::Fullscreen) + if (style & Style::Fullscreen) states.fullscreen = true; WindowImplAndroid::singleInstance = this; - states.forwardEvent = forwardEvent; + states.forwardEvent = forwardEvent; // Register process event callback states.processEvent = processEvent; @@ -92,7 +97,7 @@ WindowImplAndroid::~WindowImplAndroid() //////////////////////////////////////////////////////////// WindowHandle WindowImplAndroid::getSystemHandle() const { - ActivityStates& states = getActivity(); + ActivityStates& states = getActivity(); std::scoped_lock lock(states.mutex); return states.window; @@ -105,7 +110,7 @@ void WindowImplAndroid::processEvents() // Process incoming OS events ALooper_pollAll(0, nullptr, nullptr, nullptr); - ActivityStates& states = getActivity(); + ActivityStates& states = getActivity(); std::scoped_lock lock(states.mutex); if (m_windowBeingCreated) @@ -227,12 +232,12 @@ void WindowImplAndroid::forwardEvent(const Event& event) WindowImplAndroid::singleInstance->m_size.x = static_cast(ANativeWindow_getWidth(states.window)); WindowImplAndroid::singleInstance->m_size.y = static_cast(ANativeWindow_getHeight(states.window)); WindowImplAndroid::singleInstance->m_windowBeingCreated = true; - WindowImplAndroid::singleInstance->m_hasFocus = true; + WindowImplAndroid::singleInstance->m_hasFocus = true; } else if (event.type == Event::LostFocus) { WindowImplAndroid::singleInstance->m_windowBeingDestroyed = true; - WindowImplAndroid::singleInstance->m_hasFocus = false; + WindowImplAndroid::singleInstance->m_hasFocus = false; } WindowImplAndroid::singleInstance->pushEvent(event); @@ -243,7 +248,7 @@ void WindowImplAndroid::forwardEvent(const Event& event) //////////////////////////////////////////////////////////// int WindowImplAndroid::processEvent(int /* fd */, int /* events */, void* /* data */) { - ActivityStates& states = getActivity(); + ActivityStates& states = getActivity(); std::scoped_lock lock(states.mutex); AInputEvent* _event = nullptr; @@ -260,7 +265,7 @@ int WindowImplAndroid::processEvent(int /* fd */, int /* events */, void* /* dat if (type == AINPUT_EVENT_TYPE_KEY) { int32_t action = AKeyEvent_getAction(_event); - int32_t key = AKeyEvent_getKeyCode(_event); + int32_t key = AKeyEvent_getKeyCode(_event); if ((action == AKEY_EVENT_ACTION_DOWN || action == AKEY_EVENT_ACTION_UP || action == AKEY_EVENT_ACTION_MULTIPLE) && key != AKEYCODE_VOLUME_UP && key != AKEYCODE_VOLUME_DOWN) @@ -304,7 +309,6 @@ int WindowImplAndroid::processEvent(int /* fd */, int /* events */, void* /* dat break; } } - } AInputQueue_finishEvent(states.inputQueue, _event, handled); @@ -325,59 +329,68 @@ int WindowImplAndroid::processScrollEvent(AInputEvent* _event, ActivityStates& s JavaVMAttachArgs lJavaVMAttachArgs; lJavaVMAttachArgs.version = JNI_VERSION_1_6; - lJavaVMAttachArgs.name = "NativeThread"; - lJavaVMAttachArgs.group = nullptr; + lJavaVMAttachArgs.name = "NativeThread"; + lJavaVMAttachArgs.group = nullptr; - lResult=lJavaVM->AttachCurrentThread(&lJNIEnv, &lJavaVMAttachArgs); + lResult = lJavaVM->AttachCurrentThread(&lJNIEnv, &lJavaVMAttachArgs); - if (lResult == JNI_ERR) { + if (lResult == JNI_ERR) + { err() << "Failed to initialize JNI, couldn't get the Unicode value" << std::endl; return 0; } // Retrieve everything we need to create this MotionEvent in Java - Int64 downTime = AMotionEvent_getDownTime(_event); - Int64 eventTime = AMotionEvent_getEventTime(_event); - Int32 action = AMotionEvent_getAction(_event); - float x = AMotionEvent_getX(_event, 0); - float y = AMotionEvent_getY(_event, 0); - float pressure = AMotionEvent_getPressure(_event, 0); - float size = AMotionEvent_getSize(_event, 0); - Int32 metaState = AMotionEvent_getMetaState(_event); + Int64 downTime = AMotionEvent_getDownTime(_event); + Int64 eventTime = AMotionEvent_getEventTime(_event); + Int32 action = AMotionEvent_getAction(_event); + float x = AMotionEvent_getX(_event, 0); + float y = AMotionEvent_getY(_event, 0); + float pressure = AMotionEvent_getPressure(_event, 0); + float size = AMotionEvent_getSize(_event, 0); + Int32 metaState = AMotionEvent_getMetaState(_event); float xPrecision = AMotionEvent_getXPrecision(_event); float yPrecision = AMotionEvent_getYPrecision(_event); - Int32 deviceId = AInputEvent_getDeviceId(_event); - Int32 edgeFlags = AMotionEvent_getEdgeFlags(_event); + Int32 deviceId = AInputEvent_getDeviceId(_event); + Int32 edgeFlags = AMotionEvent_getEdgeFlags(_event); // Create the MotionEvent object in Java trough its static constructor obtain() - jclass ClassMotionEvent = lJNIEnv->FindClass("android/view/MotionEvent"); - jmethodID StaticMethodObtain = lJNIEnv->GetStaticMethodID(ClassMotionEvent, "obtain", "(JJIFFFFIFFII)Landroid/view/MotionEvent;"); + jclass ClassMotionEvent = lJNIEnv->FindClass("android/view/MotionEvent"); + jmethodID StaticMethodObtain = lJNIEnv->GetStaticMethodID(ClassMotionEvent, + "obtain", + "(JJIFFFFIFFII)Landroid/view/MotionEvent;"); // Note: C standard compatibility, varargs // automatically promote floats to doubles // even though the function signature declares float - jobject ObjectMotionEvent = lJNIEnv->CallStaticObjectMethod( - ClassMotionEvent, StaticMethodObtain, downTime, - eventTime, action, static_cast(x), - static_cast(y), static_cast(pressure), - static_cast(size), metaState, - static_cast(xPrecision), static_cast(yPrecision), - deviceId, edgeFlags - ); + jobject ObjectMotionEvent = lJNIEnv->CallStaticObjectMethod(ClassMotionEvent, + StaticMethodObtain, + downTime, + eventTime, + action, + static_cast(x), + static_cast(y), + static_cast(pressure), + static_cast(size), + metaState, + static_cast(xPrecision), + static_cast(yPrecision), + deviceId, + edgeFlags); // Call its getAxisValue() method to get the delta value of our wheel move event jmethodID MethodGetAxisValue = lJNIEnv->GetMethodID(ClassMotionEvent, "getAxisValue", "(I)F"); - jfloat delta = lJNIEnv->CallFloatMethod(ObjectMotionEvent, MethodGetAxisValue, 0x00000001); + jfloat delta = lJNIEnv->CallFloatMethod(ObjectMotionEvent, MethodGetAxisValue, 0x00000001); lJNIEnv->DeleteLocalRef(ClassMotionEvent); lJNIEnv->DeleteLocalRef(ObjectMotionEvent); // Create and send our mouse wheel event Event event; - event.type = Event::MouseWheelScrolled; + event.type = Event::MouseWheelScrolled; event.mouseWheelScroll.wheel = Mouse::VerticalWheel; event.mouseWheelScroll.delta = static_cast(delta); - event.mouseWheelScroll.x = static_cast(AMotionEvent_getX(_event, 0)); - event.mouseWheelScroll.y = static_cast(AMotionEvent_getY(_event, 0)); + event.mouseWheelScroll.x = static_cast(AMotionEvent_getX(_event, 0)); + event.mouseWheelScroll.y = static_cast(AMotionEvent_getY(_event, 0)); forwardEvent(event); @@ -393,7 +406,7 @@ int WindowImplAndroid::processKeyEvent(AInputEvent* _event, ActivityStates& /* s { int32_t action = AKeyEvent_getAction(_event); - int32_t key = AKeyEvent_getKeyCode(_event); + int32_t key = AKeyEvent_getKeyCode(_event); int32_t metakey = AKeyEvent_getMetaState(_event); Event event; @@ -404,48 +417,48 @@ int WindowImplAndroid::processKeyEvent(AInputEvent* _event, ActivityStates& /* s switch (action) { - case AKEY_EVENT_ACTION_DOWN: - event.type = Event::KeyPressed; - forwardEvent(event); - return 1; - case AKEY_EVENT_ACTION_UP: - event.type = Event::KeyReleased; - forwardEvent(event); - - if (Uint32 unicode = static_cast(getUnicode(_event))) - { - event.type = Event::TextEntered; - event.text.unicode = static_cast(unicode); + case AKEY_EVENT_ACTION_DOWN: + event.type = Event::KeyPressed; forwardEvent(event); - } - return 1; - case AKEY_EVENT_ACTION_MULTIPLE: - // Since complex inputs don't get separate key down/up events - // both have to be faked at once - event.type = Event::KeyPressed; - forwardEvent(event); - event.type = Event::KeyReleased; - forwardEvent(event); - - // This requires some special treatment, since this might represent - // a repetition of key presses or a complete sequence - if (key == AKEYCODE_UNKNOWN) - { - // This is a unique sequence, which is not yet exposed in the NDK - // https://code.google.com/p/android/issues/detail?id=33998 - return 0; - } - else if (Uint32 unicode = static_cast(getUnicode(_event))) // This is a repeated sequence - { - event.type = Event::TextEntered; - event.text.unicode = static_cast(unicode); - - int32_t repeats = AKeyEvent_getRepeatCount(_event); - for (int32_t i = 0; i < repeats; ++i) - forwardEvent(event); return 1; - } - break; + case AKEY_EVENT_ACTION_UP: + event.type = Event::KeyReleased; + forwardEvent(event); + + if (Uint32 unicode = static_cast(getUnicode(_event))) + { + event.type = Event::TextEntered; + event.text.unicode = static_cast(unicode); + forwardEvent(event); + } + return 1; + case AKEY_EVENT_ACTION_MULTIPLE: + // Since complex inputs don't get separate key down/up events + // both have to be faked at once + event.type = Event::KeyPressed; + forwardEvent(event); + event.type = Event::KeyReleased; + forwardEvent(event); + + // This requires some special treatment, since this might represent + // a repetition of key presses or a complete sequence + if (key == AKEYCODE_UNKNOWN) + { + // This is a unique sequence, which is not yet exposed in the NDK + // https://code.google.com/p/android/issues/detail?id=33998 + return 0; + } + else if (Uint32 unicode = static_cast(getUnicode(_event))) // This is a repeated sequence + { + event.type = Event::TextEntered; + event.text.unicode = static_cast(unicode); + + int32_t repeats = AKeyEvent_getRepeatCount(_event); + for (int32_t i = 0; i < repeats; ++i) + forwardEvent(event); + return 1; + } + break; } return 0; } @@ -485,14 +498,14 @@ int WindowImplAndroid::processMotionEvent(AInputEvent* _event, ActivityStates& s continue; event.touch.finger = static_cast(id); - event.touch.x = x; - event.touch.y = y; + event.touch.x = x; + event.touch.y = y; states.touchEvents[id] = Vector2i(event.touch.x, event.touch.y); } forwardEvent(event); - } + } return 1; } @@ -503,8 +516,8 @@ int WindowImplAndroid::processPointerEvent(bool isDown, AInputEvent* _event, Act int32_t device = AInputEvent_getSource(_event); int32_t action = AMotionEvent_getAction(_event); - size_t index = (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT; - int32_t id = AMotionEvent_getPointerId(_event, index); + size_t index = (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT; + int32_t id = AMotionEvent_getPointerId(_event, index); int x = static_cast(AMotionEvent_getX(_event, index)); int y = static_cast(AMotionEvent_getY(_event, index)); @@ -515,20 +528,20 @@ int WindowImplAndroid::processPointerEvent(bool isDown, AInputEvent* _event, Act { if (device == AINPUT_SOURCE_MOUSE) { - event.type = Event::MouseButtonPressed; + event.type = Event::MouseButtonPressed; event.mouseButton.button = static_cast(id); - event.mouseButton.x = x; - event.mouseButton.y = y; + event.mouseButton.x = x; + event.mouseButton.y = y; if (id >= 0 && id < Mouse::ButtonCount) states.isButtonPressed[id] = true; } else if (static_cast(device) & AINPUT_SOURCE_TOUCHSCREEN) { - event.type = Event::TouchBegan; + event.type = Event::TouchBegan; event.touch.finger = static_cast(id); - event.touch.x = x; - event.touch.y = y; + event.touch.x = x; + event.touch.y = y; states.touchEvents[id] = Vector2i(event.touch.x, event.touch.y); } @@ -537,20 +550,20 @@ int WindowImplAndroid::processPointerEvent(bool isDown, AInputEvent* _event, Act { if (device == AINPUT_SOURCE_MOUSE) { - event.type = Event::MouseButtonReleased; + event.type = Event::MouseButtonReleased; event.mouseButton.button = static_cast(id); - event.mouseButton.x = x; - event.mouseButton.y = y; + event.mouseButton.x = x; + event.mouseButton.y = y; if (id >= 0 && id < Mouse::ButtonCount) states.isButtonPressed[id] = false; } else if (static_cast(device) & AINPUT_SOURCE_TOUCHSCREEN) { - event.type = Event::TouchEnded; + event.type = Event::TouchEnded; event.touch.finger = static_cast(id); - event.touch.x = x; - event.touch.y = y; + event.touch.x = x; + event.touch.y = y; states.touchEvents.erase(id); } @@ -689,7 +702,7 @@ Keyboard::Key WindowImplAndroid::androidKeyToSF(int32_t key) int WindowImplAndroid::getUnicode(AInputEvent* event) { // Retrieve activity states - ActivityStates& states = getActivity(); + ActivityStates& states = getActivity(); std::scoped_lock lock(states.mutex); // Initializes JNI @@ -700,34 +713,45 @@ int WindowImplAndroid::getUnicode(AInputEvent* event) JavaVMAttachArgs lJavaVMAttachArgs; lJavaVMAttachArgs.version = JNI_VERSION_1_6; - lJavaVMAttachArgs.name = "NativeThread"; - lJavaVMAttachArgs.group = nullptr; + lJavaVMAttachArgs.name = "NativeThread"; + lJavaVMAttachArgs.group = nullptr; - lResult=lJavaVM->AttachCurrentThread(&lJNIEnv, &lJavaVMAttachArgs); + lResult = lJavaVM->AttachCurrentThread(&lJNIEnv, &lJavaVMAttachArgs); if (lResult == JNI_ERR) err() << "Failed to initialize JNI, couldn't get the Unicode value" << std::endl; // Retrieve key data from the input event - jlong downTime = AKeyEvent_getDownTime(event); + jlong downTime = AKeyEvent_getDownTime(event); jlong eventTime = AKeyEvent_getEventTime(event); - jint action = AKeyEvent_getAction(event); - jint code = AKeyEvent_getKeyCode(event); - jint repeat = AKeyEvent_getRepeatCount(event); // not sure! - jint metaState = AKeyEvent_getMetaState(event); - jint deviceId = AInputEvent_getDeviceId(event); - jint scancode = AKeyEvent_getScanCode(event); - jint flags = AKeyEvent_getFlags(event); - jint source = AInputEvent_getSource(event); + jint action = AKeyEvent_getAction(event); + jint code = AKeyEvent_getKeyCode(event); + jint repeat = AKeyEvent_getRepeatCount(event); // not sure! + jint metaState = AKeyEvent_getMetaState(event); + jint deviceId = AInputEvent_getDeviceId(event); + jint scancode = AKeyEvent_getScanCode(event); + jint flags = AKeyEvent_getFlags(event); + jint source = AInputEvent_getSource(event); // Construct a KeyEvent object from the event data - jclass ClassKeyEvent = lJNIEnv->FindClass("android/view/KeyEvent"); + jclass ClassKeyEvent = lJNIEnv->FindClass("android/view/KeyEvent"); jmethodID KeyEventConstructor = lJNIEnv->GetMethodID(ClassKeyEvent, "", "(JJIIIIIIII)V"); - jobject ObjectKeyEvent = lJNIEnv->NewObject(ClassKeyEvent, KeyEventConstructor, downTime, eventTime, action, code, repeat, metaState, deviceId, scancode, flags, source); + jobject ObjectKeyEvent = lJNIEnv->NewObject(ClassKeyEvent, + KeyEventConstructor, + downTime, + eventTime, + action, + code, + repeat, + metaState, + deviceId, + scancode, + flags, + source); // Call its getUnicodeChar() method to get the Unicode value jmethodID MethodGetUnicode = lJNIEnv->GetMethodID(ClassKeyEvent, "getUnicodeChar", "(I)I"); - int unicode = lJNIEnv->CallIntMethod(ObjectKeyEvent, MethodGetUnicode, metaState); + int unicode = lJNIEnv->CallIntMethod(ObjectKeyEvent, MethodGetUnicode, metaState); lJNIEnv->DeleteLocalRef(ClassKeyEvent); lJNIEnv->DeleteLocalRef(ObjectKeyEvent); diff --git a/src/SFML/Window/Android/WindowImplAndroid.hpp b/src/SFML/Window/Android/WindowImplAndroid.hpp index dee5fc446..1d99a5435 100644 --- a/src/SFML/Window/Android/WindowImplAndroid.hpp +++ b/src/SFML/Window/Android/WindowImplAndroid.hpp @@ -28,10 +28,11 @@ //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// +#include +#include #include #include -#include -#include + #include @@ -46,7 +47,6 @@ namespace priv class WindowImplAndroid : public WindowImpl { public: - //////////////////////////////////////////////////////////// /// \brief Construct the window implementation from an existing control /// @@ -184,11 +184,10 @@ public: //////////////////////////////////////////////////////////// bool hasFocus() const override; - static void forwardEvent(const Event& event); + static void forwardEvent(const Event& event); static WindowImplAndroid* singleInstance; protected: - //////////////////////////////////////////////////////////// /// \brief Process incoming events from the operating system /// @@ -196,7 +195,6 @@ protected: void processEvents() override; private: - //////////////////////////////////////////////////////////// /// \brief Process messages from the looper associated with the main thread /// @@ -235,9 +233,9 @@ private: static int getUnicode(AInputEvent* event); Vector2u m_size; - bool m_windowBeingCreated; - bool m_windowBeingDestroyed; - bool m_hasFocus; + bool m_windowBeingCreated; + bool m_windowBeingDestroyed; + bool m_hasFocus; }; } // namespace priv diff --git a/src/SFML/Window/Clipboard.cpp b/src/SFML/Window/Clipboard.cpp index b4447a967..496c53f9e 100644 --- a/src/SFML/Window/Clipboard.cpp +++ b/src/SFML/Window/Clipboard.cpp @@ -25,9 +25,9 @@ //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// +#include #include #include -#include namespace sf diff --git a/src/SFML/Window/ClipboardImpl.hpp b/src/SFML/Window/ClipboardImpl.hpp index 5b4f0b8fe..3dfc92666 100644 --- a/src/SFML/Window/ClipboardImpl.hpp +++ b/src/SFML/Window/ClipboardImpl.hpp @@ -31,19 +31,20 @@ #include #if defined(SFML_SYSTEM_WINDOWS) - #include -#elif defined(SFML_SYSTEM_LINUX) || defined(SFML_SYSTEM_FREEBSD) || defined(SFML_SYSTEM_OPENBSD) || defined(SFML_SYSTEM_NETBSD) - #if defined(SFML_USE_DRM) - #include - #else - #include - #endif +#include +#elif defined(SFML_SYSTEM_LINUX) || defined(SFML_SYSTEM_FREEBSD) || defined(SFML_SYSTEM_OPENBSD) || \ + defined(SFML_SYSTEM_NETBSD) +#if defined(SFML_USE_DRM) +#include +#else +#include +#endif #elif defined(SFML_SYSTEM_MACOS) - #include +#include #elif defined(SFML_SYSTEM_IOS) - #include +#include #elif defined(SFML_SYSTEM_ANDROID) - #include +#include #endif #endif // SFML_CLIPBOARDIMPL_HPP diff --git a/src/SFML/Window/Context.cpp b/src/SFML/Window/Context.cpp index 75f0f7fbd..99edf7792 100644 --- a/src/SFML/Window/Context.cpp +++ b/src/SFML/Window/Context.cpp @@ -25,27 +25,27 @@ //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// +#include #include #include -#include + #include namespace { - // A nested named namespace is used here to allow unity builds of SFML. - namespace ContextImpl - { - // This per-thread variable holds the current context for each thread - thread_local sf::Context* currentContext(nullptr); - } -} +// A nested named namespace is used here to allow unity builds of SFML. +namespace ContextImpl +{ +// This per-thread variable holds the current context for each thread +thread_local sf::Context* currentContext(nullptr); +} // namespace ContextImpl +} // namespace namespace sf { //////////////////////////////////////////////////////////// -Context::Context() -: m_context(priv::GlContext::create()) +Context::Context() : m_context(priv::GlContext::create()) { if (!setActive(true)) { @@ -118,8 +118,8 @@ GlFunctionPointer Context::getFunction(const char* name) //////////////////////////////////////////////////////////// -Context::Context(const ContextSettings& settings, const Vector2u& size) -: m_context(priv::GlContext::create(settings, size)) +Context::Context(const ContextSettings& settings, const Vector2u& size) : +m_context(priv::GlContext::create(settings, size)) { if (!setActive(true)) { diff --git a/src/SFML/Window/Cursor.cpp b/src/SFML/Window/Cursor.cpp index c148857c8..0f98dccf8 100644 --- a/src/SFML/Window/Cursor.cpp +++ b/src/SFML/Window/Cursor.cpp @@ -25,19 +25,18 @@ //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// +#include #include #include -#include + #include namespace sf { //////////////////////////////////////////////////////////// -Cursor::Cursor() : -m_impl(std::make_unique()) +Cursor::Cursor() : m_impl(std::make_unique()) { - } @@ -69,4 +68,3 @@ const priv::CursorImpl& Cursor::getImpl() const } } // namespace sf - diff --git a/src/SFML/Window/CursorImpl.hpp b/src/SFML/Window/CursorImpl.hpp index 0cf31e372..601f9de3c 100644 --- a/src/SFML/Window/CursorImpl.hpp +++ b/src/SFML/Window/CursorImpl.hpp @@ -31,19 +31,20 @@ #include #if defined(SFML_SYSTEM_WINDOWS) - #include -#elif defined(SFML_SYSTEM_LINUX) || defined(SFML_SYSTEM_FREEBSD) || defined(SFML_SYSTEM_OPENBSD) || defined(SFML_SYSTEM_NETBSD) - #if defined(SFML_USE_DRM) - #include - #else - #include - #endif +#include +#elif defined(SFML_SYSTEM_LINUX) || defined(SFML_SYSTEM_FREEBSD) || defined(SFML_SYSTEM_OPENBSD) || \ + defined(SFML_SYSTEM_NETBSD) +#if defined(SFML_USE_DRM) +#include +#else +#include +#endif #elif defined(SFML_SYSTEM_MACOS) - #include +#include #elif defined(SFML_SYSTEM_IOS) - #include +#include #elif defined(SFML_SYSTEM_ANDROID) - #include +#include #endif diff --git a/src/SFML/Window/DRM/ClipboardImpl.hpp b/src/SFML/Window/DRM/ClipboardImpl.hpp index 250a39b09..6e5f6bed3 100644 --- a/src/SFML/Window/DRM/ClipboardImpl.hpp +++ b/src/SFML/Window/DRM/ClipboardImpl.hpp @@ -42,7 +42,6 @@ namespace priv class ClipboardImpl { public: - //////////////////////////////////////////////////////////// /// \brief Get the content of the clipboard as string data /// diff --git a/src/SFML/Window/DRM/CursorImpl.cpp b/src/SFML/Window/DRM/CursorImpl.cpp index e1e602313..69dae386a 100644 --- a/src/SFML/Window/DRM/CursorImpl.cpp +++ b/src/SFML/Window/DRM/CursorImpl.cpp @@ -26,6 +26,7 @@ // Headers //////////////////////////////////////////////////////////// #include + #include diff --git a/src/SFML/Window/DRM/CursorImpl.hpp b/src/SFML/Window/DRM/CursorImpl.hpp index 5d24c324d..3165e7942 100644 --- a/src/SFML/Window/DRM/CursorImpl.hpp +++ b/src/SFML/Window/DRM/CursorImpl.hpp @@ -28,8 +28,8 @@ //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// -#include #include +#include #include // Prevent conflict with macro None from Xlib @@ -44,7 +44,6 @@ namespace priv class CursorImpl { public: - //////////////////////////////////////////////////////////// /// \brief Default constructor /// @@ -82,7 +81,6 @@ public: bool loadFromSystem(Cursor::Type type); private: - friend class WindowImplDRM; //////////////////////////////////////////////////////////// diff --git a/src/SFML/Window/DRM/DRMContext.cpp b/src/SFML/Window/DRM/DRMContext.cpp index c15d9b0d4..0a1b7ded1 100644 --- a/src/SFML/Window/DRM/DRMContext.cpp +++ b/src/SFML/Window/DRM/DRMContext.cpp @@ -26,11 +26,12 @@ //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// -#include -#include #include #include #include +#include +#include + #include #include #include @@ -39,153 +40,152 @@ namespace { - bool initialized = false; - drm drmNode; - drmEventContext drmEventCtx; - pollfd pollFD; - gbm_device* gbmDevice = nullptr; - int contextCount = 0; - EGLDisplay display = EGL_NO_DISPLAY; - int waitingForFlip = 0; +bool initialized = false; +drm drmNode; +drmEventContext drmEventCtx; +pollfd pollFD; +gbm_device* gbmDevice = nullptr; +int contextCount = 0; +EGLDisplay display = EGL_NO_DISPLAY; +int waitingForFlip = 0; - static void pageFlipHandler(int /* fd */, unsigned int /* frame */, - unsigned int /* sec */, unsigned int /* usec */, void* data) - { - int* temp = static_cast(data); - *temp = 0; - } +static void pageFlipHandler(int /* fd */, unsigned int /* frame */, unsigned int /* sec */, unsigned int /* usec */, void* data) +{ + int* temp = static_cast(data); + *temp = 0; +} - static bool waitForFlip(int timeout) +static bool waitForFlip(int timeout) +{ + while (waitingForFlip) { - while (waitingForFlip) + pollFD.revents = 0; + + if (poll(&pollFD, 1, timeout) < 0) + return false; + + if (pollFD.revents & (POLLHUP | POLLERR)) + return false; + + if (pollFD.revents & POLLIN) { - pollFD.revents = 0; - - if (poll(&pollFD, 1, timeout) < 0) - return false; - - if (pollFD.revents & (POLLHUP | POLLERR)) - return false; - - if (pollFD.revents & POLLIN) - { - drmHandleEvent(drmNode.fd, &drmEventCtx); - } - else - { - return false; - } + drmHandleEvent(drmNode.fd, &drmEventCtx); } - return true; - } - - void cleanup() - { - if (!initialized) - return; - - drmModeSetCrtc(drmNode.fd, - drmNode.original_crtc->crtc_id, - drmNode.original_crtc->buffer_id, - drmNode.original_crtc->x, - drmNode.original_crtc->y, - &drmNode.connector_id, - 1, - &drmNode.original_crtc->mode); - - drmModeFreeConnector(drmNode.saved_connector); - drmModeFreeEncoder(drmNode.saved_encoder); - drmModeFreeCrtc(drmNode.original_crtc); - - eglTerminate(display); - display = EGL_NO_DISPLAY; - - gbm_device_destroy(gbmDevice); - gbmDevice = nullptr; - - close(drmNode.fd); - - drmNode.fd = -1; - drmNode.mode = 0; - - std::memset(&pollFD, 0, sizeof(pollfd)); - std::memset(&drmEventCtx, 0, sizeof(drmEventContext)); - - waitingForFlip = 0; - - initialized = false; - } - - void checkInit() - { - if (initialized) - return; - - // Use environment variable "SFML_DRM_DEVICE" (or nullptr if not set) - char* deviceString = std::getenv("SFML_DRM_DEVICE"); - if (deviceString && !*deviceString) - deviceString = nullptr; - - // Use environment variable "SFML_DRM_MODE" (or nullptr if not set) - char* modeString = std::getenv("SFML_DRM_MODE"); - - // Use environment variable "SFML_DRM_REFRESH" (or 0 if not set) - // Use in combination with mode to request specific refresh rate for the mode - // if multiple refresh rates for same mode might be supported - unsigned int refreshRate = 0; - char* refreshString = std::getenv("SFML_DRM_REFRESH"); - - if (refreshString) - refreshRate = static_cast(atoi(refreshString)); - - if (init_drm(&drmNode, - deviceString, // device - modeString, // requested mode - refreshRate) < 0) // screen refresh rate + else { - sf::err() << "Error initializing DRM" << std::endl; - return; + return false; } + } + return true; +} - gbmDevice = gbm_create_device(drmNode.fd); +void cleanup() +{ + if (!initialized) + return; - std::atexit(cleanup); - initialized = true; + drmModeSetCrtc(drmNode.fd, + drmNode.original_crtc->crtc_id, + drmNode.original_crtc->buffer_id, + drmNode.original_crtc->x, + drmNode.original_crtc->y, + &drmNode.connector_id, + 1, + &drmNode.original_crtc->mode); - pollFD.fd = drmNode.fd; - pollFD.events = POLLIN; - drmEventCtx.version = 2; - drmEventCtx.page_flip_handler = pageFlipHandler; + drmModeFreeConnector(drmNode.saved_connector); + drmModeFreeEncoder(drmNode.saved_encoder); + drmModeFreeCrtc(drmNode.original_crtc); + + eglTerminate(display); + display = EGL_NO_DISPLAY; + + gbm_device_destroy(gbmDevice); + gbmDevice = nullptr; + + close(drmNode.fd); + + drmNode.fd = -1; + drmNode.mode = 0; + + std::memset(&pollFD, 0, sizeof(pollfd)); + std::memset(&drmEventCtx, 0, sizeof(drmEventContext)); + + waitingForFlip = 0; + + initialized = false; +} + +void checkInit() +{ + if (initialized) + return; + + // Use environment variable "SFML_DRM_DEVICE" (or nullptr if not set) + char* deviceString = std::getenv("SFML_DRM_DEVICE"); + if (deviceString && !*deviceString) + deviceString = nullptr; + + // Use environment variable "SFML_DRM_MODE" (or nullptr if not set) + char* modeString = std::getenv("SFML_DRM_MODE"); + + // Use environment variable "SFML_DRM_REFRESH" (or 0 if not set) + // Use in combination with mode to request specific refresh rate for the mode + // if multiple refresh rates for same mode might be supported + unsigned int refreshRate = 0; + char* refreshString = std::getenv("SFML_DRM_REFRESH"); + + if (refreshString) + refreshRate = static_cast(atoi(refreshString)); + + if (init_drm(&drmNode, + deviceString, // device + modeString, // requested mode + refreshRate) < 0) // screen refresh rate + { + sf::err() << "Error initializing DRM" << std::endl; + return; } + gbmDevice = gbm_create_device(drmNode.fd); - EGLDisplay getInitializedDisplay() + std::atexit(cleanup); + initialized = true; + + pollFD.fd = drmNode.fd; + pollFD.events = POLLIN; + drmEventCtx.version = 2; + drmEventCtx.page_flip_handler = pageFlipHandler; +} + + +EGLDisplay getInitializedDisplay() +{ + checkInit(); + + if (display == EGL_NO_DISPLAY) { - checkInit(); + display = eglCheck(eglGetDisplay(reinterpret_cast(gbmDevice))); - if (display == EGL_NO_DISPLAY) - { - display = eglCheck(eglGetDisplay(reinterpret_cast(gbmDevice))); - - EGLint major, minor; - eglCheck(eglInitialize(display, &major, &minor)); + EGLint major, minor; + eglCheck(eglInitialize(display, &major, &minor)); #if defined(SFML_OPENGL_ES) - if (!eglBindAPI(EGL_OPENGL_ES_API)) - { - sf::err() << "failed to bind api EGL_OPENGL_ES_API" << std::endl; - } -#else - if (!eglBindAPI(EGL_OPENGL_API)) - { - sf::err() << "failed to bind api EGL_OPENGL_API" << std::endl; - } -#endif + if (!eglBindAPI(EGL_OPENGL_ES_API)) + { + sf::err() << "failed to bind api EGL_OPENGL_ES_API" << std::endl; } - - return display; +#else + if (!eglBindAPI(EGL_OPENGL_API)) + { + sf::err() << "failed to bind api EGL_OPENGL_API" << std::endl; + } +#endif } + + return display; } +} // namespace namespace sf @@ -194,16 +194,16 @@ namespace priv { //////////////////////////////////////////////////////////// DRMContext::DRMContext(DRMContext* shared) : -m_display (EGL_NO_DISPLAY), -m_context (EGL_NO_CONTEXT), -m_surface (EGL_NO_SURFACE), -m_config (nullptr), -m_currentBO (nullptr), -m_nextBO (nullptr), -m_gbmSurface (nullptr), -m_size (0, 0), -m_shown (false), -m_scanOut (false) +m_display(EGL_NO_DISPLAY), +m_context(EGL_NO_CONTEXT), +m_surface(EGL_NO_SURFACE), +m_config(nullptr), +m_currentBO(nullptr), +m_nextBO(nullptr), +m_gbmSurface(nullptr), +m_size(0, 0), +m_shown(false), +m_scanOut(false) { contextCount++; @@ -226,16 +226,16 @@ m_scanOut (false) //////////////////////////////////////////////////////////// DRMContext::DRMContext(DRMContext* shared, const ContextSettings& settings, const WindowImpl& owner, unsigned int bitsPerPixel) : -m_display (EGL_NO_DISPLAY), -m_context (EGL_NO_CONTEXT), -m_surface (EGL_NO_SURFACE), -m_config (nullptr), -m_currentBO (nullptr), -m_nextBO (nullptr), -m_gbmSurface (nullptr), -m_size (0, 0), -m_shown (false), -m_scanOut (false) +m_display(EGL_NO_DISPLAY), +m_context(EGL_NO_CONTEXT), +m_surface(EGL_NO_SURFACE), +m_config(nullptr), +m_currentBO(nullptr), +m_nextBO(nullptr), +m_gbmSurface(nullptr), +m_size(0, 0), +m_shown(false), +m_scanOut(false) { contextCount++; @@ -256,16 +256,16 @@ m_scanOut (false) //////////////////////////////////////////////////////////// DRMContext::DRMContext(DRMContext* shared, const ContextSettings& settings, const Vector2u& size) : -m_display (EGL_NO_DISPLAY), -m_context (EGL_NO_CONTEXT), -m_surface (EGL_NO_SURFACE), -m_config (nullptr), -m_currentBO (nullptr), -m_nextBO (nullptr), -m_gbmSurface (nullptr), -m_size (0, 0), -m_shown (false), -m_scanOut (false) +m_display(EGL_NO_DISPLAY), +m_context(EGL_NO_CONTEXT), +m_surface(EGL_NO_SURFACE), +m_config(nullptr), +m_currentBO(nullptr), +m_nextBO(nullptr), +m_gbmSurface(nullptr), +m_size(0, 0), +m_shown(false), +m_scanOut(false) { contextCount++; @@ -375,8 +375,7 @@ void DRMContext::display() // If first time, need to first call drmModeSetCrtc() if (!m_shown) { - if (drmModeSetCrtc(drmNode.fd, drmNode.crtc_id, fb->fb_id, 0, 0, - &drmNode.connector_id, 1, drmNode.mode)) + if (drmModeSetCrtc(drmNode.fd, drmNode.crtc_id, fb->fb_id, 0, 0, &drmNode.connector_id, 1, drmNode.mode)) { err() << "Failed to set mode: " << std::strerror(errno) << std::endl; std::abort(); @@ -385,8 +384,7 @@ void DRMContext::display() } // Do page flip - if (!drmModePageFlip(drmNode.fd, drmNode.crtc_id, fb->fb_id, - DRM_MODE_PAGE_FLIP_EVENT, &waitingForFlip)) + if (!drmModePageFlip(drmNode.fd, drmNode.crtc_id, fb->fb_id, DRM_MODE_PAGE_FLIP_EVENT, &waitingForFlip)) waitingForFlip = 1; } @@ -401,11 +399,7 @@ void DRMContext::setVerticalSyncEnabled(bool enabled) //////////////////////////////////////////////////////////// void DRMContext::createContext(DRMContext* shared) { - const EGLint contextVersion[] = - { - EGL_CONTEXT_CLIENT_VERSION, 1, - EGL_NONE - }; + const EGLint contextVersion[] = {EGL_CONTEXT_CLIENT_VERSION, 1, EGL_NONE}; EGLContext toShared; @@ -433,12 +427,7 @@ void DRMContext::createSurface(const Vector2u& size, unsigned int /*bpp*/, bool if (m_scanOut) flags |= GBM_BO_USE_SCANOUT; - m_gbmSurface = gbm_surface_create( - gbmDevice, - size.x, - size.y, - GBM_FORMAT_ARGB8888, - flags); + m_gbmSurface = gbm_surface_create(gbmDevice, size.x, size.y, GBM_FORMAT_ARGB8888, flags); if (!m_gbmSurface) { @@ -448,7 +437,8 @@ void DRMContext::createSurface(const Vector2u& size, unsigned int /*bpp*/, bool m_size = size; - m_surface = eglCheck(eglCreateWindowSurface(m_display, m_config, reinterpret_cast(m_gbmSurface), nullptr)); + m_surface = eglCheck( + eglCreateWindowSurface(m_display, m_config, reinterpret_cast(m_gbmSurface), nullptr)); if (m_surface == EGL_NO_SURFACE) { @@ -476,26 +466,35 @@ EGLConfig DRMContext::getBestConfig(EGLDisplay display, unsigned int bitsPerPixe { // Set our video settings constraint const EGLint attributes[] = - { - EGL_BUFFER_SIZE, static_cast(bitsPerPixel), - EGL_DEPTH_SIZE, static_cast(settings.depthBits), - EGL_STENCIL_SIZE, static_cast(settings.stencilBits), - EGL_SAMPLE_BUFFERS, static_cast(settings.antialiasingLevel), - EGL_BLUE_SIZE, 8, - EGL_GREEN_SIZE, 8, - EGL_RED_SIZE, 8, - EGL_ALPHA_SIZE, 8, + { EGL_BUFFER_SIZE, + static_cast(bitsPerPixel), + EGL_DEPTH_SIZE, + static_cast(settings.depthBits), + EGL_STENCIL_SIZE, + static_cast(settings.stencilBits), + EGL_SAMPLE_BUFFERS, + static_cast(settings.antialiasingLevel), + EGL_BLUE_SIZE, + 8, + EGL_GREEN_SIZE, + 8, + EGL_RED_SIZE, + 8, + EGL_ALPHA_SIZE, + 8, - EGL_SURFACE_TYPE, EGL_WINDOW_BIT, + EGL_SURFACE_TYPE, + EGL_WINDOW_BIT, #if defined(SFML_OPENGL_ES) - EGL_RENDERABLE_TYPE, EGL_OPENGL_ES_BIT, + EGL_RENDERABLE_TYPE, + EGL_OPENGL_ES_BIT, #else - EGL_RENDERABLE_TYPE, EGL_OPENGL_BIT, + EGL_RENDERABLE_TYPE, + EGL_OPENGL_BIT, #endif - EGL_NONE - }; + EGL_NONE }; - EGLint configCount; + EGLint configCount; EGLConfig configs[1]; // Ask EGL for the best config matching our video settings @@ -520,8 +519,8 @@ void DRMContext::updateSettings() eglCheck(eglGetConfigAttrib(m_display, m_config, EGL_SAMPLES, &tmp)); m_settings.antialiasingLevel = static_cast(tmp); - m_settings.majorVersion = 1; - m_settings.minorVersion = 1; + m_settings.majorVersion = 1; + m_settings.minorVersion = 1; m_settings.attributeFlags = ContextSettings::Default; } diff --git a/src/SFML/Window/DRM/DRMContext.hpp b/src/SFML/Window/DRM/DRMContext.hpp index a7472ae99..4f006f267 100644 --- a/src/SFML/Window/DRM/DRMContext.hpp +++ b/src/SFML/Window/DRM/DRMContext.hpp @@ -29,11 +29,12 @@ //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// +#include #include #include #include #include -#include + #include #define EGL_NO_X11 #define MESA_EGL_NO_X11_HEADERS @@ -51,7 +52,6 @@ class WindowImplDRM; class DRMContext : public GlContext { public: - //////////////////////////////////////////////////////////// /// \brief Create a new context, not associated to a window /// @@ -169,7 +169,6 @@ public: static GlFunctionPointer getFunction(const char* name); protected: - friend class VideoModeImpl; friend class WindowImplDRM; @@ -180,7 +179,6 @@ protected: static drm* getDRM(); private: - //////////////////////////////////////////////////////////// /// \brief Helper to copy the picked EGL configuration /// @@ -190,17 +188,17 @@ private: //////////////////////////////////////////////////////////// // Member data //////////////////////////////////////////////////////////// - EGLDisplay m_display; ///< The internal EGL display - EGLContext m_context; ///< The internal EGL context - EGLSurface m_surface; ///< The internal EGL surface - EGLConfig m_config; ///< The internal EGL config + EGLDisplay m_display; ///< The internal EGL display + EGLContext m_context; ///< The internal EGL context + EGLSurface m_surface; ///< The internal EGL surface + EGLConfig m_config; ///< The internal EGL config - gbm_bo* m_currentBO; - gbm_bo* m_nextBO; + gbm_bo* m_currentBO; + gbm_bo* m_nextBO; gbm_surface* m_gbmSurface; - Vector2u m_size; - bool m_shown; - bool m_scanOut; + Vector2u m_size; + bool m_shown; + bool m_scanOut; }; } // namespace priv diff --git a/src/SFML/Window/DRM/InputImplUDev.cpp b/src/SFML/Window/DRM/InputImplUDev.cpp index 8b0435b52..8ec8a9f56 100644 --- a/src/SFML/Window/DRM/InputImplUDev.cpp +++ b/src/SFML/Window/DRM/InputImplUDev.cpp @@ -25,8 +25,9 @@ //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// -#include #include +#include + #include #include #include @@ -44,389 +45,400 @@ namespace { - struct TouchSlot +struct TouchSlot +{ + int oldId; + int id; + sf::Vector2i pos; + + TouchSlot() : oldId(-1), id(-1), pos(0, 0) { - int oldId; - int id; - sf::Vector2i pos; - - TouchSlot() : - oldId(-1), - id(-1), - pos(0, 0) - { - } - }; - - std::recursive_mutex inputMutex; // threadsafe? maybe... - sf::Vector2i mousePos; // current mouse position - - std::vector fileDescriptors; // list of open file descriptors for /dev/input - std::vector mouseMap(sf::Mouse::ButtonCount, false); // track whether keys are down - std::vector keyMap(sf::Keyboard::KeyCount, false); // track whether mouse buttons are down - - int touchFd = -1; // file descriptor we have seen MT events on; assumes only 1 - std::vector touchSlots; // track the state of each touch "slot" - int currentSlot = 0; // which slot are we currently updating? - - std::queue eventQueue; // events received and waiting to be consumed - const int MAX_QUEUE = 64; // The maximum size we let eventQueue grow to - - termios newTerminalConfig, oldTerminalConfig; // Terminal configurations - - bool altDown() { return (keyMap[sf::Keyboard::LAlt] || keyMap[sf::Keyboard::RAlt]); } - bool controlDown() { return (keyMap[sf::Keyboard::LControl] || keyMap[sf::Keyboard::RControl]); } - bool shiftDown() { return (keyMap[sf::Keyboard::LShift] || keyMap[sf::Keyboard::RShift]); } - bool systemDown() { return (keyMap[sf::Keyboard::LSystem] || keyMap[sf::Keyboard::RSystem]); } - - void uninitFileDescriptors() - { - for (std::vector::iterator itr = fileDescriptors.begin(); itr != fileDescriptors.end(); ++itr) - close(*itr); } +}; -#define BITS_PER_LONG (sizeof(unsigned long) * 8) -#define NBITS(x) (((x - 1) / BITS_PER_LONG) + 1) -#define OFF(x) (x % BITS_PER_LONG) -#define LONG(x) (x / BITS_PER_LONG) -#define TEST_BIT(bit, array) ((array[LONG(bit)] >> OFF(bit)) & 1) +std::recursive_mutex inputMutex; // threadsafe? maybe... +sf::Vector2i mousePos; // current mouse position - // Only keep fileDescriptors that we think are a keyboard, mouse or touchpad/touchscreen - // Joysticks are handled in /src/SFML/Window/Unix/JoystickImpl.cpp - bool keepFileDescriptor(int fileDesc) +std::vector fileDescriptors; // list of open file descriptors for /dev/input +std::vector mouseMap(sf::Mouse::ButtonCount, false); // track whether keys are down +std::vector keyMap(sf::Keyboard::KeyCount, false); // track whether mouse buttons are down + +int touchFd = -1; // file descriptor we have seen MT events on; assumes only 1 +std::vector touchSlots; // track the state of each touch "slot" +int currentSlot = 0; // which slot are we currently updating? + +std::queue eventQueue; // events received and waiting to be consumed +const int MAX_QUEUE = 64; // The maximum size we let eventQueue grow to + +termios newTerminalConfig, oldTerminalConfig; // Terminal configurations + +bool altDown() +{ + return (keyMap[sf::Keyboard::LAlt] || keyMap[sf::Keyboard::RAlt]); +} +bool controlDown() +{ + return (keyMap[sf::Keyboard::LControl] || keyMap[sf::Keyboard::RControl]); +} +bool shiftDown() +{ + return (keyMap[sf::Keyboard::LShift] || keyMap[sf::Keyboard::RShift]); +} +bool systemDown() +{ + return (keyMap[sf::Keyboard::LSystem] || keyMap[sf::Keyboard::RSystem]); +} + +void uninitFileDescriptors() +{ + for (std::vector::iterator itr = fileDescriptors.begin(); itr != fileDescriptors.end(); ++itr) + close(*itr); +} + +#define BITS_PER_LONG (sizeof(unsigned long) * 8) +#define NBITS(x) (((x - 1) / BITS_PER_LONG) + 1) +#define OFF(x) (x % BITS_PER_LONG) +#define LONG(x) (x / BITS_PER_LONG) +#define TEST_BIT(bit, array) ((array[LONG(bit)] >> OFF(bit)) & 1) + +// Only keep fileDescriptors that we think are a keyboard, mouse or touchpad/touchscreen +// Joysticks are handled in /src/SFML/Window/Unix/JoystickImpl.cpp +bool keepFileDescriptor(int fileDesc) +{ + unsigned long bitmask_ev[NBITS(EV_MAX)]; + unsigned long bitmask_key[NBITS(KEY_MAX)]; + unsigned long bitmask_abs[NBITS(ABS_MAX)]; + unsigned long bitmask_rel[NBITS(REL_MAX)]; + + ioctl(fileDesc, EVIOCGBIT(0, sizeof(bitmask_ev)), &bitmask_ev); + ioctl(fileDesc, EVIOCGBIT(EV_KEY, sizeof(bitmask_key)), &bitmask_key); + ioctl(fileDesc, EVIOCGBIT(EV_ABS, sizeof(bitmask_abs)), &bitmask_abs); + ioctl(fileDesc, EVIOCGBIT(EV_REL, sizeof(bitmask_rel)), &bitmask_rel); + + // This is the keyboard test used by SDL. + // The first 32 bits are ESC, numbers and Q to D; If we have any of those, + // consider it a keyboard device; do not test for KEY_RESERVED, though + bool is_keyboard = (bitmask_key[0] & 0xFFFFFFFE); + + bool is_abs = TEST_BIT(EV_ABS, bitmask_ev) && TEST_BIT(ABS_X, bitmask_abs) && TEST_BIT(ABS_Y, bitmask_abs); + + bool is_rel = TEST_BIT(EV_REL, bitmask_ev) && TEST_BIT(REL_X, bitmask_rel) && TEST_BIT(REL_Y, bitmask_rel); + + bool is_mouse = (is_abs || is_rel) && TEST_BIT(BTN_MOUSE, bitmask_key); + + bool is_touch = is_abs && (TEST_BIT(BTN_TOOL_FINGER, bitmask_key) || TEST_BIT(BTN_TOUCH, bitmask_key)); + + return is_keyboard || is_mouse || is_touch; +} + +void initFileDescriptors() +{ + static bool initialized = false; + if (initialized) + return; + + initialized = true; + + for (int i = 0; i < 32; i++) { - unsigned long bitmask_ev[NBITS(EV_MAX)]; - unsigned long bitmask_key[NBITS(KEY_MAX)]; - unsigned long bitmask_abs[NBITS(ABS_MAX)]; - unsigned long bitmask_rel[NBITS(REL_MAX)]; + std::string name("/dev/input/event"); + std::ostringstream stream; + stream << i; + name += stream.str(); - ioctl(fileDesc, EVIOCGBIT(0, sizeof(bitmask_ev)), &bitmask_ev); - ioctl(fileDesc, EVIOCGBIT(EV_KEY, sizeof(bitmask_key)), &bitmask_key); - ioctl(fileDesc, EVIOCGBIT(EV_ABS, sizeof(bitmask_abs)), &bitmask_abs); - ioctl(fileDesc, EVIOCGBIT(EV_REL, sizeof(bitmask_rel)), &bitmask_rel); + int tempFD = open(name.c_str(), O_RDONLY | O_NONBLOCK); - // This is the keyboard test used by SDL. - // The first 32 bits are ESC, numbers and Q to D; If we have any of those, - // consider it a keyboard device; do not test for KEY_RESERVED, though - bool is_keyboard = (bitmask_key[0] & 0xFFFFFFFE); - - bool is_abs = TEST_BIT(EV_ABS, bitmask_ev) - && TEST_BIT(ABS_X, bitmask_abs) && TEST_BIT(ABS_Y, bitmask_abs); - - bool is_rel = TEST_BIT(EV_REL, bitmask_ev) - && TEST_BIT(REL_X, bitmask_rel) && TEST_BIT(REL_Y, bitmask_rel); - - bool is_mouse = (is_abs || is_rel) && TEST_BIT(BTN_MOUSE, bitmask_key); - - bool is_touch = is_abs && (TEST_BIT(BTN_TOOL_FINGER, bitmask_key) || TEST_BIT(BTN_TOUCH, bitmask_key)); - - return is_keyboard || is_mouse || is_touch; - } - - void initFileDescriptors() - { - static bool initialized = false; - if (initialized) - return; - - initialized = true; - - for (int i = 0; i < 32; i++) + if (tempFD < 0) { - std::string name("/dev/input/event"); - std::ostringstream stream; - stream << i; - name += stream.str(); + if (errno != ENOENT) + sf::err() << "Error opening " << name << ": " << std::strerror(errno) << std::endl; - int tempFD = open(name.c_str(), O_RDONLY | O_NONBLOCK); - - if (tempFD < 0) - { - if (errno != ENOENT) - sf::err() << "Error opening " << name << ": " << std::strerror(errno) << std::endl; - - continue; - } - - if (keepFileDescriptor(tempFD)) - fileDescriptors.push_back(tempFD); - else - close(tempFD); + continue; } - std::atexit(uninitFileDescriptors); + if (keepFileDescriptor(tempFD)) + fileDescriptors.push_back(tempFD); + else + close(tempFD); } - sf::Mouse::Button toMouseButton(int code) - { - switch (code) - { - case BTN_LEFT: return sf::Mouse::Left; - case BTN_RIGHT: return sf::Mouse::Right; - case BTN_MIDDLE: return sf::Mouse::Middle; - case BTN_SIDE: return sf::Mouse::XButton1; - case BTN_EXTRA: return sf::Mouse::XButton2; + std::atexit(uninitFileDescriptors); +} - default: - return sf::Mouse::ButtonCount; - } +sf::Mouse::Button toMouseButton(int code) +{ + switch (code) + { + case BTN_LEFT: + return sf::Mouse::Left; + case BTN_RIGHT: + return sf::Mouse::Right; + case BTN_MIDDLE: + return sf::Mouse::Middle; + case BTN_SIDE: + return sf::Mouse::XButton1; + case BTN_EXTRA: + return sf::Mouse::XButton2; + + default: + return sf::Mouse::ButtonCount; } +} - sf::Keyboard::Key toKey(int code) +sf::Keyboard::Key toKey(int code) +{ + switch (code) { - switch (code) - { - // clang-format off - case KEY_ESC: return sf::Keyboard::Escape; - case KEY_1: return sf::Keyboard::Num1; - case KEY_2: return sf::Keyboard::Num2; - case KEY_3: return sf::Keyboard::Num3; - case KEY_4: return sf::Keyboard::Num4; - case KEY_5: return sf::Keyboard::Num5; - case KEY_6: return sf::Keyboard::Num6; - case KEY_7: return sf::Keyboard::Num7; - case KEY_8: return sf::Keyboard::Num8; - case KEY_9: return sf::Keyboard::Num9; - case KEY_0: return sf::Keyboard::Num0; - case KEY_MINUS: return sf::Keyboard::Hyphen; - case KEY_EQUAL: return sf::Keyboard::Equal; - case KEY_BACKSPACE: return sf::Keyboard::Backspace; - case KEY_TAB: return sf::Keyboard::Tab; - case KEY_Q: return sf::Keyboard::Q; - case KEY_W: return sf::Keyboard::W; - case KEY_E: return sf::Keyboard::E; - case KEY_R: return sf::Keyboard::R; - case KEY_T: return sf::Keyboard::T; - case KEY_Y: return sf::Keyboard::Y; - case KEY_U: return sf::Keyboard::U; - case KEY_I: return sf::Keyboard::I; - case KEY_O: return sf::Keyboard::O; - case KEY_P: return sf::Keyboard::P; - case KEY_LEFTBRACE: return sf::Keyboard::LBracket; - case KEY_RIGHTBRACE: return sf::Keyboard::RBracket; - case KEY_KPENTER: - case KEY_ENTER: return sf::Keyboard::Enter; - case KEY_LEFTCTRL: return sf::Keyboard::LControl; - case KEY_A: return sf::Keyboard::A; - case KEY_S: return sf::Keyboard::S; - case KEY_D: return sf::Keyboard::D; - case KEY_F: return sf::Keyboard::F; - case KEY_G: return sf::Keyboard::G; - case KEY_H: return sf::Keyboard::H; - case KEY_J: return sf::Keyboard::J; - case KEY_K: return sf::Keyboard::K; - case KEY_L: return sf::Keyboard::L; - case KEY_SEMICOLON: return sf::Keyboard::Semicolon; - case KEY_APOSTROPHE: return sf::Keyboard::Quote; - case KEY_GRAVE: return sf::Keyboard::Tilde; - case KEY_LEFTSHIFT: return sf::Keyboard::LShift; - case KEY_BACKSLASH: return sf::Keyboard::Backslash; - case KEY_Z: return sf::Keyboard::Z; - case KEY_X: return sf::Keyboard::X; - case KEY_C: return sf::Keyboard::C; - case KEY_V: return sf::Keyboard::V; - case KEY_B: return sf::Keyboard::B; - case KEY_N: return sf::Keyboard::N; - case KEY_M: return sf::Keyboard::M; - case KEY_COMMA: return sf::Keyboard::Comma; - case KEY_DOT: return sf::Keyboard::Period; - case KEY_SLASH: return sf::Keyboard::Slash; - case KEY_RIGHTSHIFT: return sf::Keyboard::RShift; - case KEY_KPASTERISK: return sf::Keyboard::Multiply; - case KEY_LEFTALT: return sf::Keyboard::LAlt; - case KEY_SPACE: return sf::Keyboard::Space; - case KEY_F1: return sf::Keyboard::F1; - case KEY_F2: return sf::Keyboard::F2; - case KEY_F3: return sf::Keyboard::F3; - case KEY_F4: return sf::Keyboard::F4; - case KEY_F5: return sf::Keyboard::F5; - case KEY_F6: return sf::Keyboard::F6; - case KEY_F7: return sf::Keyboard::F7; - case KEY_F8: return sf::Keyboard::F8; - case KEY_F9: return sf::Keyboard::F9; - case KEY_F10: return sf::Keyboard::F10; - case KEY_F11: return sf::Keyboard::F11; - case KEY_F12: return sf::Keyboard::F12; - case KEY_F13: return sf::Keyboard::F13; - case KEY_F14: return sf::Keyboard::F14; - case KEY_F15: return sf::Keyboard::F15; - case KEY_KP7: return sf::Keyboard::Numpad7; - case KEY_KP8: return sf::Keyboard::Numpad8; - case KEY_KP9: return sf::Keyboard::Numpad9; - case KEY_KPMINUS: return sf::Keyboard::Subtract; - case KEY_KP4: return sf::Keyboard::Numpad4; - case KEY_KP5: return sf::Keyboard::Numpad5; - case KEY_KP6: return sf::Keyboard::Numpad6; - case KEY_KPPLUS: return sf::Keyboard::Add; - case KEY_KP1: return sf::Keyboard::Numpad1; - case KEY_KP2: return sf::Keyboard::Numpad2; - case KEY_KP3: return sf::Keyboard::Numpad3; - case KEY_KP0: return sf::Keyboard::Numpad0; - case KEY_KPDOT: return sf::Keyboard::Delete; - case KEY_RIGHTCTRL: return sf::Keyboard::RControl; - case KEY_KPSLASH: return sf::Keyboard::Divide; - case KEY_RIGHTALT: return sf::Keyboard::RAlt; - case KEY_HOME: return sf::Keyboard::Home; - case KEY_UP: return sf::Keyboard::Up; - case KEY_PAGEUP: return sf::Keyboard::PageUp; - case KEY_LEFT: return sf::Keyboard::Left; - case KEY_RIGHT: return sf::Keyboard::Right; - case KEY_END: return sf::Keyboard::End; - case KEY_DOWN: return sf::Keyboard::Down; - case KEY_PAGEDOWN: return sf::Keyboard::PageDown; - case KEY_INSERT: return sf::Keyboard::Insert; - case KEY_DELETE: return sf::Keyboard::Delete; - case KEY_PAUSE: return sf::Keyboard::Pause; - case KEY_LEFTMETA: return sf::Keyboard::LSystem; - case KEY_RIGHTMETA: return sf::Keyboard::RSystem; + // clang-format off + case KEY_ESC: return sf::Keyboard::Escape; + case KEY_1: return sf::Keyboard::Num1; + case KEY_2: return sf::Keyboard::Num2; + case KEY_3: return sf::Keyboard::Num3; + case KEY_4: return sf::Keyboard::Num4; + case KEY_5: return sf::Keyboard::Num5; + case KEY_6: return sf::Keyboard::Num6; + case KEY_7: return sf::Keyboard::Num7; + case KEY_8: return sf::Keyboard::Num8; + case KEY_9: return sf::Keyboard::Num9; + case KEY_0: return sf::Keyboard::Num0; + case KEY_MINUS: return sf::Keyboard::Hyphen; + case KEY_EQUAL: return sf::Keyboard::Equal; + case KEY_BACKSPACE: return sf::Keyboard::Backspace; + case KEY_TAB: return sf::Keyboard::Tab; + case KEY_Q: return sf::Keyboard::Q; + case KEY_W: return sf::Keyboard::W; + case KEY_E: return sf::Keyboard::E; + case KEY_R: return sf::Keyboard::R; + case KEY_T: return sf::Keyboard::T; + case KEY_Y: return sf::Keyboard::Y; + case KEY_U: return sf::Keyboard::U; + case KEY_I: return sf::Keyboard::I; + case KEY_O: return sf::Keyboard::O; + case KEY_P: return sf::Keyboard::P; + case KEY_LEFTBRACE: return sf::Keyboard::LBracket; + case KEY_RIGHTBRACE: return sf::Keyboard::RBracket; + case KEY_KPENTER: + case KEY_ENTER: return sf::Keyboard::Enter; + case KEY_LEFTCTRL: return sf::Keyboard::LControl; + case KEY_A: return sf::Keyboard::A; + case KEY_S: return sf::Keyboard::S; + case KEY_D: return sf::Keyboard::D; + case KEY_F: return sf::Keyboard::F; + case KEY_G: return sf::Keyboard::G; + case KEY_H: return sf::Keyboard::H; + case KEY_J: return sf::Keyboard::J; + case KEY_K: return sf::Keyboard::K; + case KEY_L: return sf::Keyboard::L; + case KEY_SEMICOLON: return sf::Keyboard::Semicolon; + case KEY_APOSTROPHE: return sf::Keyboard::Quote; + case KEY_GRAVE: return sf::Keyboard::Tilde; + case KEY_LEFTSHIFT: return sf::Keyboard::LShift; + case KEY_BACKSLASH: return sf::Keyboard::Backslash; + case KEY_Z: return sf::Keyboard::Z; + case KEY_X: return sf::Keyboard::X; + case KEY_C: return sf::Keyboard::C; + case KEY_V: return sf::Keyboard::V; + case KEY_B: return sf::Keyboard::B; + case KEY_N: return sf::Keyboard::N; + case KEY_M: return sf::Keyboard::M; + case KEY_COMMA: return sf::Keyboard::Comma; + case KEY_DOT: return sf::Keyboard::Period; + case KEY_SLASH: return sf::Keyboard::Slash; + case KEY_RIGHTSHIFT: return sf::Keyboard::RShift; + case KEY_KPASTERISK: return sf::Keyboard::Multiply; + case KEY_LEFTALT: return sf::Keyboard::LAlt; + case KEY_SPACE: return sf::Keyboard::Space; + case KEY_F1: return sf::Keyboard::F1; + case KEY_F2: return sf::Keyboard::F2; + case KEY_F3: return sf::Keyboard::F3; + case KEY_F4: return sf::Keyboard::F4; + case KEY_F5: return sf::Keyboard::F5; + case KEY_F6: return sf::Keyboard::F6; + case KEY_F7: return sf::Keyboard::F7; + case KEY_F8: return sf::Keyboard::F8; + case KEY_F9: return sf::Keyboard::F9; + case KEY_F10: return sf::Keyboard::F10; + case KEY_F11: return sf::Keyboard::F11; + case KEY_F12: return sf::Keyboard::F12; + case KEY_F13: return sf::Keyboard::F13; + case KEY_F14: return sf::Keyboard::F14; + case KEY_F15: return sf::Keyboard::F15; + case KEY_KP7: return sf::Keyboard::Numpad7; + case KEY_KP8: return sf::Keyboard::Numpad8; + case KEY_KP9: return sf::Keyboard::Numpad9; + case KEY_KPMINUS: return sf::Keyboard::Subtract; + case KEY_KP4: return sf::Keyboard::Numpad4; + case KEY_KP5: return sf::Keyboard::Numpad5; + case KEY_KP6: return sf::Keyboard::Numpad6; + case KEY_KPPLUS: return sf::Keyboard::Add; + case KEY_KP1: return sf::Keyboard::Numpad1; + case KEY_KP2: return sf::Keyboard::Numpad2; + case KEY_KP3: return sf::Keyboard::Numpad3; + case KEY_KP0: return sf::Keyboard::Numpad0; + case KEY_KPDOT: return sf::Keyboard::Delete; + case KEY_RIGHTCTRL: return sf::Keyboard::RControl; + case KEY_KPSLASH: return sf::Keyboard::Divide; + case KEY_RIGHTALT: return sf::Keyboard::RAlt; + case KEY_HOME: return sf::Keyboard::Home; + case KEY_UP: return sf::Keyboard::Up; + case KEY_PAGEUP: return sf::Keyboard::PageUp; + case KEY_LEFT: return sf::Keyboard::Left; + case KEY_RIGHT: return sf::Keyboard::Right; + case KEY_END: return sf::Keyboard::End; + case KEY_DOWN: return sf::Keyboard::Down; + case KEY_PAGEDOWN: return sf::Keyboard::PageDown; + case KEY_INSERT: return sf::Keyboard::Insert; + case KEY_DELETE: return sf::Keyboard::Delete; + case KEY_PAUSE: return sf::Keyboard::Pause; + case KEY_LEFTMETA: return sf::Keyboard::LSystem; + case KEY_RIGHTMETA: return sf::Keyboard::RSystem; - case KEY_RESERVED: - case KEY_SYSRQ: - case KEY_CAPSLOCK: - case KEY_NUMLOCK: - case KEY_SCROLLLOCK: - default: - return sf::Keyboard::Unknown; + case KEY_RESERVED: + case KEY_SYSRQ: + case KEY_CAPSLOCK: + case KEY_NUMLOCK: + case KEY_SCROLLLOCK: + default: + return sf::Keyboard::Unknown; // clang-format on - } } +} - void pushEvent(sf::Event& event) +void pushEvent(sf::Event& event) +{ + if (eventQueue.size() >= MAX_QUEUE) + eventQueue.pop(); + + eventQueue.push(event); +} + +TouchSlot& atSlot(int idx) +{ + if (idx >= static_cast(touchSlots.size())) + touchSlots.resize(static_cast(idx + 1)); + return touchSlots.at(static_cast(idx)); +} + +void processSlots() +{ + for (std::vector::iterator slot = touchSlots.begin(); slot != touchSlots.end(); ++slot) { - if (eventQueue.size() >= MAX_QUEUE) - eventQueue.pop(); + sf::Event event; - eventQueue.push(event); - } + event.touch.x = slot->pos.x; + event.touch.y = slot->pos.y; - TouchSlot& atSlot(int idx) - { - if (idx >= static_cast(touchSlots.size())) - touchSlots.resize(static_cast(idx + 1)); - return touchSlots.at(static_cast(idx)); - } - - void processSlots() - { - for (std::vector::iterator slot = touchSlots.begin(); slot != touchSlots.end(); ++slot) + if (slot->oldId == slot->id) { - sf::Event event; - - event.touch.x = slot->pos.x; - event.touch.y = slot->pos.y; - - if (slot->oldId == slot->id) + event.type = sf::Event::TouchMoved; + event.touch.finger = static_cast(slot->id); + pushEvent(event); + } + else + { + if (slot->oldId != -1) { - event.type = sf::Event::TouchMoved; + event.type = sf::Event::TouchEnded; + event.touch.finger = static_cast(slot->oldId); + pushEvent(event); + } + if (slot->id != -1) + { + event.type = sf::Event::TouchBegan; event.touch.finger = static_cast(slot->id); pushEvent(event); } - else - { - if (slot->oldId != -1) - { - event.type = sf::Event::TouchEnded; - event.touch.finger = static_cast(slot->oldId); - pushEvent(event); - } - if (slot->id != -1) - { - event.type = sf::Event::TouchBegan; - event.touch.finger = static_cast(slot->id); - pushEvent(event); - } - slot->oldId = slot->id; - } + slot->oldId = slot->id; } } +} - bool eventProcess(sf::Event& event) +bool eventProcess(sf::Event& event) +{ + std::scoped_lock lock(inputMutex); + + // Ensure that we are initialized + initFileDescriptors(); + + // This is for handling the Backspace and DEL text events, which we + // generate based on keystrokes (and not stdin) + static unsigned int doDeferredText = 0; + if (doDeferredText) { - std::scoped_lock lock(inputMutex); + event.type = sf::Event::TextEntered; + event.text.unicode = doDeferredText; + doDeferredText = 0; + return true; + } - // Ensure that we are initialized - initFileDescriptors(); + ssize_t bytesRead; - // This is for handling the Backspace and DEL text events, which we - // generate based on keystrokes (and not stdin) - static unsigned int doDeferredText = 0; - if (doDeferredText) + // Check all the open file descriptors for the next event + for (std::vector::iterator itr = fileDescriptors.begin(); itr != fileDescriptors.end(); ++itr) + { + input_event inputEvent; + bytesRead = read(*itr, &inputEvent, sizeof(inputEvent)); + + while (bytesRead > 0) { - event.type = sf::Event::TextEntered; - event.text.unicode = doDeferredText; - doDeferredText = 0; - return true; - } - - ssize_t bytesRead; - - // Check all the open file descriptors for the next event - for (std::vector::iterator itr = fileDescriptors.begin(); itr != fileDescriptors.end(); ++itr) - { - input_event inputEvent; - bytesRead = read(*itr, &inputEvent, sizeof(inputEvent)); - - while (bytesRead > 0) + if (inputEvent.type == EV_KEY) { - if (inputEvent.type == EV_KEY) + sf::Mouse::Button mb = toMouseButton(inputEvent.code); + if (mb != sf::Mouse::ButtonCount) { - sf::Mouse::Button mb = toMouseButton(inputEvent.code); - if (mb != sf::Mouse::ButtonCount) + event.type = inputEvent.value ? sf::Event::MouseButtonPressed : sf::Event::MouseButtonReleased; + event.mouseButton.button = mb; + event.mouseButton.x = mousePos.x; + event.mouseButton.y = mousePos.y; + + mouseMap[mb] = inputEvent.value; + return true; + } + else + { + sf::Keyboard::Key kb = toKey(inputEvent.code); + + unsigned int special = 0; + if ((kb == sf::Keyboard::Delete) || (kb == sf::Keyboard::Backspace)) + special = (kb == sf::Keyboard::Delete) ? 127 : 8; + + if (inputEvent.value == 2) { - event.type = inputEvent.value ? sf::Event::MouseButtonPressed : sf::Event::MouseButtonReleased; - event.mouseButton.button = mb; - event.mouseButton.x = mousePos.x; - event.mouseButton.y = mousePos.y; - - mouseMap[mb] = inputEvent.value; - return true; - } - else - { - sf::Keyboard::Key kb = toKey(inputEvent.code); - - unsigned int special = 0; - if ((kb == sf::Keyboard::Delete) - || (kb == sf::Keyboard::Backspace)) - special = (kb == sf::Keyboard::Delete) ? 127 : 8; - - if (inputEvent.value == 2) + // key repeat events + // + if (special) { - // key repeat events - // - if (special) - { - event.type = sf::Event::TextEntered; - event.text.unicode = special; - return true; - } - } - else if (kb != sf::Keyboard::Unknown) - { - // key down and key up events - // - event.type = inputEvent.value ? sf::Event::KeyPressed : sf::Event::KeyReleased; - event.key.code = kb; - event.key.alt = altDown(); - event.key.control = controlDown(); - event.key.shift = shiftDown(); - event.key.system = systemDown(); - - keyMap[kb] = inputEvent.value; - - if (special && inputEvent.value) - doDeferredText = special; - + event.type = sf::Event::TextEntered; + event.text.unicode = special; return true; } } - } - else if (inputEvent.type == EV_REL) - { - bool posChange = false; - switch (inputEvent.code) + else if (kb != sf::Keyboard::Unknown) { + // key down and key up events + // + event.type = inputEvent.value ? sf::Event::KeyPressed : sf::Event::KeyReleased; + event.key.code = kb; + event.key.alt = altDown(); + event.key.control = controlDown(); + event.key.shift = shiftDown(); + event.key.system = systemDown(); + + keyMap[kb] = inputEvent.value; + + if (special && inputEvent.value) + doDeferredText = special; + + return true; + } + } + } + else if (inputEvent.type == EV_REL) + { + bool posChange = false; + switch (inputEvent.code) + { case REL_X: mousePos.x += inputEvent.value; posChange = true; @@ -438,120 +450,119 @@ namespace break; case REL_WHEEL: - event.type = sf::Event::MouseWheelScrolled; + event.type = sf::Event::MouseWheelScrolled; event.mouseWheelScroll.delta = static_cast(inputEvent.value); - event.mouseWheelScroll.x = mousePos.x; - event.mouseWheelScroll.y = mousePos.y; + event.mouseWheelScroll.x = mousePos.x; + event.mouseWheelScroll.y = mousePos.y; return true; - } - - if (posChange) - { - event.type = sf::Event::MouseMoved; - event.mouseMove.x = mousePos.x; - event.mouseMove.y = mousePos.y; - return true; - } } - else if (inputEvent.type == EV_ABS) + + if (posChange) + { + event.type = sf::Event::MouseMoved; + event.mouseMove.x = mousePos.x; + event.mouseMove.y = mousePos.y; + return true; + } + } + else if (inputEvent.type == EV_ABS) + { + switch (inputEvent.code) { - switch (inputEvent.code) - { case ABS_MT_SLOT: currentSlot = inputEvent.value; - touchFd = *itr; + touchFd = *itr; break; case ABS_MT_TRACKING_ID: atSlot(currentSlot).id = inputEvent.value; - touchFd = *itr; + touchFd = *itr; break; case ABS_MT_POSITION_X: atSlot(currentSlot).pos.x = inputEvent.value; - touchFd = *itr; + touchFd = *itr; break; case ABS_MT_POSITION_Y: atSlot(currentSlot).pos.y = inputEvent.value; - touchFd = *itr; + touchFd = *itr; break; - } } - else if (inputEvent.type == EV_SYN && inputEvent.code == SYN_REPORT && - *itr == touchFd) - { - // This pushes events directly to the queue, because it - // can generate more than one event. - processSlots(); - } - - bytesRead = read(*itr, &inputEvent, sizeof(inputEvent)); + } + else if (inputEvent.type == EV_SYN && inputEvent.code == SYN_REPORT && *itr == touchFd) + { + // This pushes events directly to the queue, because it + // can generate more than one event. + processSlots(); } - if ((bytesRead < 0) && (errno != EAGAIN)) - sf::err() << " Error: " << std::strerror(errno) << std::endl; + bytesRead = read(*itr, &inputEvent, sizeof(inputEvent)); } - // Finally check if there is a Text event on stdin - // - // We only clear the ICANON flag for the time of reading + if ((bytesRead < 0) && (errno != EAGAIN)) + sf::err() << " Error: " << std::strerror(errno) << std::endl; + } - newTerminalConfig.c_lflag &= ~(tcflag_t)ICANON; - tcsetattr(STDIN_FILENO, TCSANOW, &newTerminalConfig); + // Finally check if there is a Text event on stdin + // + // We only clear the ICANON flag for the time of reading - timeval timeout; - timeout.tv_sec = 0; - timeout.tv_usec = 0; + newTerminalConfig.c_lflag &= ~(tcflag_t)ICANON; + tcsetattr(STDIN_FILENO, TCSANOW, &newTerminalConfig); - unsigned char code = 0; + timeval timeout; + timeout.tv_sec = 0; + timeout.tv_usec = 0; - fd_set readFDSet; + unsigned char code = 0; + + fd_set readFDSet; + FD_ZERO(&readFDSet); + FD_SET(STDIN_FILENO, &readFDSet); + int ready = select(STDIN_FILENO + 1, &readFDSet, nullptr, nullptr, &timeout); + + if (ready > 0 && FD_ISSET(STDIN_FILENO, &readFDSet)) + bytesRead = read(STDIN_FILENO, &code, 1); + + if ((code == 127) || (code == 8)) // Suppress 127 (DEL) to 8 (BACKSPACE) + code = 0; + else if (code == 27) // ESC + { + // Suppress ANSI escape sequences FD_ZERO(&readFDSet); FD_SET(STDIN_FILENO, &readFDSet); - int ready = select(STDIN_FILENO + 1, &readFDSet, nullptr, nullptr, &timeout); - + ready = select(STDIN_FILENO + 1, &readFDSet, nullptr, nullptr, &timeout); if (ready > 0 && FD_ISSET(STDIN_FILENO, &readFDSet)) - bytesRead = read(STDIN_FILENO, &code, 1); - - if ((code == 127) || (code == 8)) // Suppress 127 (DEL) to 8 (BACKSPACE) - code = 0; - else if (code == 27) // ESC { - // Suppress ANSI escape sequences - FD_ZERO(&readFDSet); - FD_SET(STDIN_FILENO, &readFDSet); - ready = select(STDIN_FILENO + 1, &readFDSet, nullptr, nullptr, &timeout); - if (ready > 0 && FD_ISSET(STDIN_FILENO, &readFDSet)) - { - unsigned char tempBuffer[16]; - bytesRead = read(STDIN_FILENO, tempBuffer, 16); - code = 0; - } + unsigned char tempBuffer[16]; + bytesRead = read(STDIN_FILENO, tempBuffer, 16); + code = 0; } - - newTerminalConfig.c_lflag |= ICANON; - tcsetattr(STDIN_FILENO, TCSANOW, &newTerminalConfig); - - if (code > 0) - { - // TODO: Proper unicode handling - event.type = sf::Event::TextEntered; - event.text.unicode = code; - return true; - } - - // No events available - return false; } - // assumes inputMutex is locked - void update() + newTerminalConfig.c_lflag |= ICANON; + tcsetattr(STDIN_FILENO, TCSANOW, &newTerminalConfig); + + if (code > 0) { - sf::Event event; - while (eventProcess(event)) - { - pushEvent(event); - } + // TODO: Proper unicode handling + event.type = sf::Event::TextEntered; + event.text.unicode = code; + return true; + } + + // No events available + return false; +} + +// assumes inputMutex is locked +void update() +{ + sf::Event event; + while (eventProcess(event)) + { + pushEvent(event); } } +} // namespace namespace sf { diff --git a/src/SFML/Window/DRM/InputImplUDev.hpp b/src/SFML/Window/DRM/InputImplUDev.hpp index 4838dbf10..9fed957a8 100644 --- a/src/SFML/Window/DRM/InputImplUDev.hpp +++ b/src/SFML/Window/DRM/InputImplUDev.hpp @@ -28,9 +28,9 @@ //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// +#include #include #include -#include namespace sf @@ -44,7 +44,6 @@ namespace priv class InputImpl { public: - //////////////////////////////////////////////////////////// /// \brief Check if a key is pressed /// @@ -161,7 +160,6 @@ public: static Vector2i getTouchPosition(unsigned int finger, const WindowBase& relativeTo); private: - friend class WindowImplDRM; //////////////////////////////////////////////////////////// diff --git a/src/SFML/Window/DRM/VideoModeImpl.cpp b/src/SFML/Window/DRM/VideoModeImpl.cpp index 66356b4c2..3409e2cb8 100644 --- a/src/SFML/Window/DRM/VideoModeImpl.cpp +++ b/src/SFML/Window/DRM/VideoModeImpl.cpp @@ -25,9 +25,10 @@ //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// -#include -#include #include +#include +#include + #include @@ -40,14 +41,13 @@ std::vector VideoModeImpl::getFullscreenModes() { std::vector modes; - drm* drm = sf::priv::DRMContext::getDRM(); + drm* drm = sf::priv::DRMContext::getDRM(); drmModeConnectorPtr conn = drm->saved_connector; if (conn) { for (int i = 0; i < conn->count_modes; i++) - modes.push_back( - VideoMode({conn->modes[i].hdisplay, conn->modes[i].vdisplay})); + modes.push_back(VideoMode({conn->modes[i].hdisplay, conn->modes[i].vdisplay})); } else modes.push_back(getDesktopMode()); @@ -59,7 +59,7 @@ std::vector VideoModeImpl::getFullscreenModes() //////////////////////////////////////////////////////////// VideoMode VideoModeImpl::getDesktopMode() { - drm* drm = sf::priv::DRMContext::getDRM(); + drm* drm = sf::priv::DRMContext::getDRM(); drmModeModeInfoPtr ptr = drm->mode; if (ptr) return VideoMode({ptr->hdisplay, ptr->vdisplay}); diff --git a/src/SFML/Window/DRM/WindowImplDRM.cpp b/src/SFML/Window/DRM/WindowImplDRM.cpp index 805be5a92..6e4978209 100644 --- a/src/SFML/Window/DRM/WindowImplDRM.cpp +++ b/src/SFML/Window/DRM/WindowImplDRM.cpp @@ -25,12 +25,13 @@ //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// -#include +#include #include #include +#include #include #include -#include + #include @@ -39,8 +40,7 @@ namespace sf namespace priv { //////////////////////////////////////////////////////////// -WindowImplDRM::WindowImplDRM(WindowHandle /*handle*/) : -m_size(0, 0) +WindowImplDRM::WindowImplDRM(WindowHandle /*handle*/) : m_size(0, 0) { sf::priv::InputImpl::setTerminalConfig(); } diff --git a/src/SFML/Window/DRM/WindowImplDRM.hpp b/src/SFML/Window/DRM/WindowImplDRM.hpp index 2ce27731a..551e55a6e 100644 --- a/src/SFML/Window/DRM/WindowImplDRM.hpp +++ b/src/SFML/Window/DRM/WindowImplDRM.hpp @@ -42,7 +42,6 @@ namespace priv class WindowImplDRM : public WindowImpl { public: - //////////////////////////////////////////////////////////// /// \brief Construct the window implementation from an existing control /// @@ -181,7 +180,6 @@ public: virtual bool hasFocus() const override; protected: - //////////////////////////////////////////////////////////// /// \brief Process incoming events from the operating system /// @@ -189,7 +187,6 @@ protected: virtual void processEvents() override; private: - //////////////////////////////////////////////////////////// // Member data //////////////////////////////////////////////////////////// diff --git a/src/SFML/Window/EGLCheck.cpp b/src/SFML/Window/EGLCheck.cpp index b7324789e..8dd991bc1 100644 --- a/src/SFML/Window/EGLCheck.cpp +++ b/src/SFML/Window/EGLCheck.cpp @@ -26,11 +26,13 @@ //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// -#include #include +#include + #include -#include + #include +#include namespace sf @@ -46,15 +48,15 @@ void eglCheckError(const std::filesystem::path& file, unsigned int line, const c if (errorCode != EGL_SUCCESS) { - std::string error = "unknown error"; - std::string description = "no description"; + std::string error = "unknown error"; + std::string description = "no description"; // Decode the error code returned switch (errorCode) { case EGL_NOT_INITIALIZED: { - error = "EGL_NOT_INITIALIZED"; + error = "EGL_NOT_INITIALIZED"; description = "EGL is not initialized, or could not be initialized, for the specified display"; break; } @@ -62,33 +64,34 @@ void eglCheckError(const std::filesystem::path& file, unsigned int line, const c case EGL_BAD_ACCESS: { error = "EGL_BAD_ACCESS"; - description = "EGL cannot access a requested resource (for example, a context is bound in another thread)"; + description = + "EGL cannot access a requested resource (for example, a context is bound in another thread)"; break; } case EGL_BAD_ALLOC: { - error = "EGL_BAD_ALLOC"; + error = "EGL_BAD_ALLOC"; description = "EGL failed to allocate resources for the requested operation"; break; } case EGL_BAD_ATTRIBUTE: { - error = "EGL_BAD_ATTRIBUTE"; + error = "EGL_BAD_ATTRIBUTE"; description = "an unrecognized attribute or attribute value was passed in an attribute list"; break; } case EGL_BAD_CONTEXT: { - error = "EGL_BAD_CONTEXT"; + error = "EGL_BAD_CONTEXT"; description = "an EGLContext argument does not name a valid EGLContext"; break; } case EGL_BAD_CONFIG: { - error = "EGL_BAD_CONFIG"; + error = "EGL_BAD_CONFIG"; description = "an EGLConfig argument does not name a valid EGLConfig"; break; } @@ -96,14 +99,17 @@ void eglCheckError(const std::filesystem::path& file, unsigned int line, const c case EGL_BAD_CURRENT_SURFACE: { error = "EGL_BAD_CURRENT_SURFACE"; - description = "the current surface of the calling thread is a window, pbuffer, or pixmap that is no longer valid"; + description = + "the current surface of the calling thread is a window, pbuffer, or pixmap that is no longer valid"; break; } case EGL_BAD_DISPLAY: { error = "EGL_BAD_DISPLAY"; - description = "an EGLDisplay argument does not name a valid EGLDisplay; or, EGL is not initialized on the specified EGLDisplay"; + description = + "an EGLDisplay argument does not name a valid EGLDisplay; or, EGL is not initialized on the " + "specified EGLDisplay"; break; } @@ -111,34 +117,38 @@ void eglCheckError(const std::filesystem::path& file, unsigned int line, const c case EGL_BAD_SURFACE: { error = "EGL_BAD_SURFACE"; - description = "an EGLSurface argument does not name a valid surface (window, pbuffer, or pixmap) configured for rendering"; + description = + "an EGLSurface argument does not name a valid surface (window, pbuffer, or pixmap) configured for " + "rendering"; break; } case EGL_BAD_MATCH: { error = "EGL_BAD_MATCH"; - description = "arguments are inconsistent; for example, an otherwise valid context requires buffers (e.g. depth or stencil) not allocated by an otherwise valid surface"; + description = + "arguments are inconsistent; for example, an otherwise valid context requires buffers (e.g. depth " + "or stencil) not allocated by an otherwise valid surface"; break; } case EGL_BAD_PARAMETER: { - error = "EGL_BAD_PARAMETER"; + error = "EGL_BAD_PARAMETER"; description = "one or more argument values are invalid"; break; } case EGL_BAD_NATIVE_PIXMAP: { - error = "EGL_BAD_NATIVE_PIXMAP"; + error = "EGL_BAD_NATIVE_PIXMAP"; description = "an EGLNativePixmapType argument does not refer to a valid native pixmap"; break; } case EGL_BAD_NATIVE_WINDOW: { - error = "EGL_BAD_NATIVE_WINDOW"; + error = "EGL_BAD_NATIVE_WINDOW"; description = "an EGLNativeWindowType argument does not refer to a valid native window"; break; } @@ -146,16 +156,16 @@ void eglCheckError(const std::filesystem::path& file, unsigned int line, const c case EGL_CONTEXT_LOST: { error = "EGL_CONTEXT_LOST"; - description = "a power management event has occurred. The application must destroy all contexts and reinitialize client API state and objects to continue rendering"; + description = + "a power management event has occurred. The application must destroy all contexts and reinitialize " + "client API state and objects to continue rendering"; break; } } // Log the error - err() << "An internal EGL call failed in " - << file.filename() << " (" << line << ") : " - << "\nExpression:\n " << expression - << "\nError description:\n " << error << "\n " << description << '\n' + err() << "An internal EGL call failed in " << file.filename() << " (" << line << ") : " + << "\nExpression:\n " << expression << "\nError description:\n " << error << "\n " << description << '\n' << std::endl; } } diff --git a/src/SFML/Window/EGLCheck.hpp b/src/SFML/Window/EGLCheck.hpp index 771e69b7d..ec7d9185e 100644 --- a/src/SFML/Window/EGLCheck.hpp +++ b/src/SFML/Window/EGLCheck.hpp @@ -29,6 +29,7 @@ // Headers //////////////////////////////////////////////////////////// #include + #include @@ -41,14 +42,19 @@ namespace priv //////////////////////////////////////////////////////////// #ifdef SFML_DEBUG - // In debug mode, perform a test on every EGL call - // The do-while loop is needed so that glCheck can be used as a single statement in if/else branches - #define eglCheck(expr) do { expr; sf::priv::eglCheckError(__FILE__, __LINE__, #expr); } while (false) +// In debug mode, perform a test on every EGL call +// The do-while loop is needed so that glCheck can be used as a single statement in if/else branches +#define eglCheck(expr) \ + do \ + { \ + expr; \ + sf::priv::eglCheckError(__FILE__, __LINE__, #expr); \ + } while (false) #else - // Else, we don't add any overhead - #define eglCheck(x) (x) +// Else, we don't add any overhead +#define eglCheck(x) (x) #endif diff --git a/src/SFML/Window/EglContext.cpp b/src/SFML/Window/EglContext.cpp index 5a31501b2..ffc4c6def 100644 --- a/src/SFML/Window/EglContext.cpp +++ b/src/SFML/Window/EglContext.cpp @@ -26,17 +26,18 @@ //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// -#include -#include #include #include +#include +#include + #include #include #ifdef SFML_SYSTEM_ANDROID - #include +#include #endif #if defined(SFML_SYSTEM_LINUX) && !defined(SFML_USE_DRM) - #include +#include #endif // We check for this definition in order to avoid multiple definitions of GLAD @@ -49,51 +50,51 @@ namespace { - // A nested named namespace is used here to allow unity builds of SFML. - namespace EglContextImpl - { - EGLDisplay getInitializedDisplay() - { +// A nested named namespace is used here to allow unity builds of SFML. +namespace EglContextImpl +{ +EGLDisplay getInitializedDisplay() +{ #if defined(SFML_SYSTEM_ANDROID) - // On Android, its native activity handles this for us - sf::priv::ActivityStates& states = sf::priv::getActivity(); - std::scoped_lock lock(states.mutex); + // On Android, its native activity handles this for us + sf::priv::ActivityStates& states = sf::priv::getActivity(); + std::scoped_lock lock(states.mutex); - return states.display; + return states.display; #endif - static EGLDisplay display = EGL_NO_DISPLAY; + static EGLDisplay display = EGL_NO_DISPLAY; - if (display == EGL_NO_DISPLAY) - { - eglCheck(display = eglGetDisplay(EGL_DEFAULT_DISPLAY)); - eglCheck(eglInitialize(display, nullptr, nullptr)); - } + if (display == EGL_NO_DISPLAY) + { + eglCheck(display = eglGetDisplay(EGL_DEFAULT_DISPLAY)); + eglCheck(eglInitialize(display, nullptr, nullptr)); + } - return display; - } + return display; +} - //////////////////////////////////////////////////////////// - void ensureInit() - { - static bool initialized = false; - if (!initialized) - { - initialized = true; +//////////////////////////////////////////////////////////// +void ensureInit() +{ + static bool initialized = false; + if (!initialized) + { + initialized = true; - // We don't check the return value since the extension - // flags are cleared even if loading fails - gladLoaderLoadEGL(EGL_NO_DISPLAY); + // We don't check the return value since the extension + // flags are cleared even if loading fails + gladLoaderLoadEGL(EGL_NO_DISPLAY); - // Continue loading with a display - gladLoaderLoadEGL(getInitializedDisplay()); - } - } + // Continue loading with a display + gladLoaderLoadEGL(getInitializedDisplay()); } } +} // namespace EglContextImpl +} // namespace namespace sf @@ -102,10 +103,10 @@ namespace priv { //////////////////////////////////////////////////////////// EglContext::EglContext(EglContext* shared) : -m_display (EGL_NO_DISPLAY), -m_context (EGL_NO_CONTEXT), -m_surface (EGL_NO_SURFACE), -m_config (nullptr) +m_display(EGL_NO_DISPLAY), +m_context(EGL_NO_CONTEXT), +m_surface(EGL_NO_SURFACE), +m_config(nullptr) { EglContextImpl::ensureInit(); @@ -118,11 +119,7 @@ m_config (nullptr) // Note: The EGL specs say that attrib_list can be a null pointer when passed to eglCreatePbufferSurface, // but this is resulting in a segfault. Bug in Android? - EGLint attrib_list[] = { - EGL_WIDTH, 1, - EGL_HEIGHT,1, - EGL_NONE - }; + EGLint attrib_list[] = {EGL_WIDTH, 1, EGL_HEIGHT, 1, EGL_NONE}; eglCheck(m_surface = eglCreatePbufferSurface(m_display, m_config, attrib_list)); @@ -132,18 +129,21 @@ m_config (nullptr) //////////////////////////////////////////////////////////// -EglContext::EglContext(EglContext* shared, const ContextSettings& settings, [[maybe_unused]] const WindowImpl& owner, unsigned int bitsPerPixel) : -m_display (EGL_NO_DISPLAY), -m_context (EGL_NO_CONTEXT), -m_surface (EGL_NO_SURFACE), -m_config (nullptr) +EglContext::EglContext(EglContext* shared, + const ContextSettings& settings, + [[maybe_unused]] const WindowImpl& owner, + unsigned int bitsPerPixel) : +m_display(EGL_NO_DISPLAY), +m_context(EGL_NO_CONTEXT), +m_surface(EGL_NO_SURFACE), +m_config(nullptr) { EglContextImpl::ensureInit(); #ifdef SFML_SYSTEM_ANDROID // On Android, we must save the created context - ActivityStates& states = getActivity(); + ActivityStates& states = getActivity(); std::scoped_lock lock(states.mutex); states.context = this; @@ -171,14 +171,16 @@ m_config (nullptr) //////////////////////////////////////////////////////////// EglContext::EglContext(EglContext* /*shared*/, const ContextSettings& /*settings*/, const Vector2u& /*size*/) : -m_display (EGL_NO_DISPLAY), -m_context (EGL_NO_CONTEXT), -m_surface (EGL_NO_SURFACE), -m_config (nullptr) +m_display(EGL_NO_DISPLAY), +m_context(EGL_NO_CONTEXT), +m_surface(EGL_NO_SURFACE), +m_config(nullptr) { EglContextImpl::ensureInit(); - sf::err() << "Warning: context has not been initialized. The constructor EglContext(shared, settings, size) is currently not implemented." << std::endl; + sf::err() << "Warning: context has not been initialized. The constructor EglContext(shared, settings, size) is " + "currently not implemented." + << std::endl; } @@ -259,10 +261,7 @@ void EglContext::setVerticalSyncEnabled(bool enabled) //////////////////////////////////////////////////////////// void EglContext::createContext(EglContext* shared) { - const EGLint contextVersion[] = { - EGL_CONTEXT_CLIENT_VERSION, 1, - EGL_NONE - }; + const EGLint contextVersion[] = {EGL_CONTEXT_CLIENT_VERSION, 1, EGL_NONE}; EGLContext toShared; @@ -303,18 +302,24 @@ EGLConfig EglContext::getBestConfig(EGLDisplay display, unsigned int bitsPerPixe EglContextImpl::ensureInit(); // Set our video settings constraint - const EGLint attributes[] = { - EGL_BUFFER_SIZE, static_cast(bitsPerPixel), - EGL_DEPTH_SIZE, static_cast(settings.depthBits), - EGL_STENCIL_SIZE, static_cast(settings.stencilBits), - EGL_SAMPLE_BUFFERS, settings.antialiasingLevel ? 1 : 0, - EGL_SAMPLES, static_cast(settings.antialiasingLevel), - EGL_SURFACE_TYPE, EGL_WINDOW_BIT | EGL_PBUFFER_BIT, - EGL_RENDERABLE_TYPE, EGL_OPENGL_ES_BIT, - EGL_NONE - }; + const EGLint attributes[] = + {EGL_BUFFER_SIZE, + static_cast(bitsPerPixel), + EGL_DEPTH_SIZE, + static_cast(settings.depthBits), + EGL_STENCIL_SIZE, + static_cast(settings.stencilBits), + EGL_SAMPLE_BUFFERS, + settings.antialiasingLevel ? 1 : 0, + EGL_SAMPLES, + static_cast(settings.antialiasingLevel), + EGL_SURFACE_TYPE, + EGL_WINDOW_BIT | EGL_PBUFFER_BIT, + EGL_RENDERABLE_TYPE, + EGL_OPENGL_ES_BIT, + EGL_NONE}; - EGLint configCount; + EGLint configCount; EGLConfig configs[1]; // Ask EGL for the best config matching our video settings @@ -330,7 +335,7 @@ EGLConfig EglContext::getBestConfig(EGLDisplay display, unsigned int bitsPerPixe void EglContext::updateSettings() { EGLBoolean result = EGL_FALSE; - EGLint tmp = 0; + EGLint tmp = 0; // Update the internal context settings with the current config eglCheck(result = eglGetConfigAttrib(m_display, m_config, EGL_DEPTH_SIZE, &tmp)); @@ -354,8 +359,8 @@ void EglContext::updateSettings() m_settings.antialiasingLevel = static_cast(tmp); - m_settings.majorVersion = 1; - m_settings.minorVersion = 1; + m_settings.majorVersion = 1; + m_settings.minorVersion = 1; m_settings.attributeFlags = ContextSettings::Default; } @@ -390,7 +395,7 @@ XVisualInfo EglContext::selectBestVisual(::Display* XDisplay, unsigned int bitsP // Get X11 visuals compatible with this EGL config XVisualInfo *availableVisuals, bestVisual; - int visualCount = 0; + int visualCount = 0; availableVisuals = XGetVisualInfo(XDisplay, VisualIDMask, &vTemplate, &visualCount); diff --git a/src/SFML/Window/EglContext.hpp b/src/SFML/Window/EglContext.hpp index f3abc6f48..42b7348dd 100644 --- a/src/SFML/Window/EglContext.hpp +++ b/src/SFML/Window/EglContext.hpp @@ -28,14 +28,15 @@ //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// -#include #include #include #include +#include #include // Prevent conflict with macro None from Xlib + #include #if defined(SFML_SYSTEM_LINUX) && !defined(SFML_USE_DRM) - #include +#include #endif namespace sf @@ -45,7 +46,6 @@ namespace priv class EglContext : public GlContext { public: - //////////////////////////////////////////////////////////// /// \brief Create a new context, not associated to a window /// @@ -179,7 +179,6 @@ public: #endif private: - //////////////////////////////////////////////////////////// /// \brief Helper to copy the picked EGL configuration //////////////////////////////////////////////////////////// @@ -188,11 +187,10 @@ private: //////////////////////////////////////////////////////////// // Member data //////////////////////////////////////////////////////////// - EGLDisplay m_display; //!< The internal EGL display - EGLContext m_context; //!< The internal EGL context - EGLSurface m_surface; //!< The internal EGL surface - EGLConfig m_config; //!< The internal EGL config - + EGLDisplay m_display; //!< The internal EGL display + EGLContext m_context; //!< The internal EGL context + EGLSurface m_surface; //!< The internal EGL surface + EGLConfig m_config; //!< The internal EGL config }; } // namespace priv diff --git a/src/SFML/Window/FreeBSD/JoystickImpl.cpp b/src/SFML/Window/FreeBSD/JoystickImpl.cpp index 2bf4fca33..dc9c09175 100644 --- a/src/SFML/Window/FreeBSD/JoystickImpl.cpp +++ b/src/SFML/Window/FreeBSD/JoystickImpl.cpp @@ -27,13 +27,14 @@ // Headers //////////////////////////////////////////////////////////// #include -#include + +#include #include #include -#include -#include -#include #include +#include +#include +#include #include //////////////////////////////////////////////////////////// @@ -49,111 +50,118 @@ namespace { - std::unordered_map plugged; - std::unordered_map > hatValueMap; +std::unordered_map plugged; +std::unordered_map> hatValueMap; - bool isJoystick(const char *name) +bool isJoystick(const char* name) +{ + int file = ::open(name, O_RDONLY | O_NONBLOCK); + + if (file < 0) + return false; + + report_desc_t desc = hid_get_report_desc(file); + + if (!desc) { - int file = ::open(name, O_RDONLY | O_NONBLOCK); + ::close(file); + return false; + } - if (file < 0) - return false; + int id = hid_get_report_id(file); + hid_data_t data = hid_start_parse(desc, 1 << hid_input, id); - report_desc_t desc = hid_get_report_desc(file); - - if (!desc) - { - ::close(file); - return false; - } - - int id = hid_get_report_id(file); - hid_data_t data = hid_start_parse(desc, 1 << hid_input, id); - - if (!data) - { - hid_dispose_report_desc(desc); - ::close(file); - return false; - } - - hid_item_t item; - - // Assume it isn't - bool result = false; - - while (hid_get_item(data, &item) > 0) - { - if ((item.kind == hid_collection) && (HID_PAGE(item.usage) == HUP_GENERIC_DESKTOP)) - { - if ((HID_USAGE(item.usage) == HUG_JOYSTICK) || (HID_USAGE(item.usage) == HUG_GAME_PAD)) - { - result = true; - } - } - } - - hid_end_parse(data); + if (!data) + { hid_dispose_report_desc(desc); ::close(file); - - return result; + return false; } - void updatePluggedList() + hid_item_t item; + + // Assume it isn't + bool result = false; + + while (hid_get_item(data, &item) > 0) { - /* - * Devices /dev/uhid are shared between joystick and any other - * human interface device. We need to iterate over all found devices - * and check if they are joysticks. The index of JoystickImpl::open - * does not match the /dev/uhid device! - */ - DIR* directory = opendir("/dev"); - - if (directory) + if ((item.kind == hid_collection) && (HID_PAGE(item.usage) == HUP_GENERIC_DESKTOP)) { - int joystickCount = 0; - struct dirent* directoryEntry = readdir(directory); - - while (directoryEntry && joystickCount < sf::Joystick::Count) + if ((HID_USAGE(item.usage) == HUG_JOYSTICK) || (HID_USAGE(item.usage) == HUG_GAME_PAD)) { - if (!std::strncmp(directoryEntry->d_name, "uhid", 4)) - { - std::string name("/dev/"); - name += directoryEntry->d_name; + result = true; + } + } + } - if (isJoystick(name.c_str())) - plugged[static_cast(joystickCount++)] = name; - } + hid_end_parse(data); + hid_dispose_report_desc(desc); + ::close(file); - directoryEntry = readdir(directory); + return result; +} + +void updatePluggedList() +{ + /* + * Devices /dev/uhid are shared between joystick and any other + * human interface device. We need to iterate over all found devices + * and check if they are joysticks. The index of JoystickImpl::open + * does not match the /dev/uhid device! + */ + DIR* directory = opendir("/dev"); + + if (directory) + { + int joystickCount = 0; + struct dirent* directoryEntry = readdir(directory); + + while (directoryEntry && joystickCount < sf::Joystick::Count) + { + if (!std::strncmp(directoryEntry->d_name, "uhid", 4)) + { + std::string name("/dev/"); + name += directoryEntry->d_name; + + if (isJoystick(name.c_str())) + plugged[static_cast(joystickCount++)] = name; } - closedir(directory); + directoryEntry = readdir(directory); } - } - int usageToAxis(int usage) - { - switch (usage) - { - case HUG_X: return sf::Joystick::X; - case HUG_Y: return sf::Joystick::Y; - case HUG_Z: return sf::Joystick::Z; - case HUG_RZ: return sf::Joystick::R; - case HUG_RX: return sf::Joystick::U; - case HUG_RY: return sf::Joystick::V; - default: return -1; - } - } - - void hatValueToSfml(int value, sf::priv::JoystickState& state) - { - state.axes[sf::Joystick::PovX] = static_cast(hatValueMap[value].first); - state.axes[sf::Joystick::PovY] = static_cast(hatValueMap[value].second); + closedir(directory); } } +int usageToAxis(int usage) +{ + switch (usage) + { + case HUG_X: + return sf::Joystick::X; + case HUG_Y: + return sf::Joystick::Y; + case HUG_Z: + return sf::Joystick::Z; + case HUG_RZ: + return sf::Joystick::R; + case HUG_RX: + return sf::Joystick::U; + case HUG_RY: + return sf::Joystick::V; + default: + return -1; + } +} + +void hatValueToSfml(int value, sf::priv::JoystickState& state) +{ + state.axes[sf::Joystick::PovX] = static_cast(hatValueMap[value].first); + state.axes[sf::Joystick::PovY] = static_cast(hatValueMap[value].second); +} +} // namespace + namespace sf { @@ -168,16 +176,16 @@ void JoystickImpl::initialize() updatePluggedList(); // Map of hat values - hatValueMap[0] = std::make_pair( 0, 0); // center + hatValueMap[0] = std::make_pair(0, 0); // center - hatValueMap[1] = std::make_pair( 0, -100); // top - hatValueMap[3] = std::make_pair( 100, 0); // right - hatValueMap[5] = std::make_pair( 0, 100); // bottom - hatValueMap[7] = std::make_pair(-100, 0); // left + hatValueMap[1] = std::make_pair(0, -100); // top + hatValueMap[3] = std::make_pair(100, 0); // right + hatValueMap[5] = std::make_pair(0, 100); // bottom + hatValueMap[7] = std::make_pair(-100, 0); // left - hatValueMap[2] = std::make_pair( 100, -100); // top-right - hatValueMap[4] = std::make_pair( 100, 100); // bottom-right - hatValueMap[6] = std::make_pair(-100, 100); // bottom-left + hatValueMap[2] = std::make_pair(100, -100); // top-right + hatValueMap[4] = std::make_pair(100, 100); // bottom-right + hatValueMap[6] = std::make_pair(-100, 100); // bottom-left hatValueMap[8] = std::make_pair(-100, -100); // top-left } @@ -244,7 +252,7 @@ void JoystickImpl::close() JoystickCaps JoystickImpl::getCapabilities() const { JoystickCaps caps; - hid_item_t item; + hid_item_t item; hid_data_t data = hid_start_parse(m_desc, 1 << hid_input, m_id); @@ -300,7 +308,7 @@ JoystickState JoystickImpl::JoystickImpl::update() if (!data) continue; - int buttonIndex = 0; + int buttonIndex = 0; hid_item_t item; while (hid_get_item(data, &item)) @@ -316,7 +324,7 @@ JoystickState JoystickImpl::JoystickImpl::update() else if (usage == HUP_GENERIC_DESKTOP) { int value = hid_get_data(m_buffer.data(), &item); - int axis = usageToAxis(usage); + int axis = usageToAxis(usage); if (usage == HUG_HAT_SWITCH) { @@ -327,7 +335,7 @@ JoystickState JoystickImpl::JoystickImpl::update() int minimum = item.logical_minimum; int maximum = item.logical_maximum; - value = (value - minimum) * 200 / (maximum - minimum) - 100; + value = (value - minimum) * 200 / (maximum - minimum) - 100; m_state.axes[axis] = static_cast(value); } } diff --git a/src/SFML/Window/FreeBSD/JoystickImpl.hpp b/src/SFML/Window/FreeBSD/JoystickImpl.hpp index 15c2535d5..f2efafe85 100644 --- a/src/SFML/Window/FreeBSD/JoystickImpl.hpp +++ b/src/SFML/Window/FreeBSD/JoystickImpl.hpp @@ -44,7 +44,6 @@ namespace priv class JoystickImpl { public: - //////////////////////////////////////////////////////////// /// \brief Perform the global initialization of the joystick module /// @@ -108,7 +107,6 @@ public: [[nodiscard]] JoystickState update(); private: - //////////////////////////////////////////////////////////// // Member data //////////////////////////////////////////////////////////// diff --git a/src/SFML/Window/GlContext.cpp b/src/SFML/Window/GlContext.cpp index 27d13662d..bcdf1c7e4 100644 --- a/src/SFML/Window/GlContext.cpp +++ b/src/SFML/Window/GlContext.cpp @@ -25,12 +25,18 @@ //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// -#include +#include #include #include -#include +#include + #include + #include +#include +#include +#include +#include #include #include #include @@ -40,292 +46,282 @@ #include #include #include -#include -#include -#include -#include #if defined(SFML_SYSTEM_WINDOWS) - #if defined(SFML_OPENGL_ES) +#if defined(SFML_OPENGL_ES) - using ContextType = sf::priv::EglContext; +using ContextType = sf::priv::EglContext; - #else +#else - #include - using ContextType = sf::priv::WglContext; +#include +using ContextType = sf::priv::WglContext; - #endif +#endif -#elif defined(SFML_SYSTEM_LINUX) || defined(SFML_SYSTEM_FREEBSD) || defined(SFML_SYSTEM_OPENBSD) || defined(SFML_SYSTEM_NETBSD) +#elif defined(SFML_SYSTEM_LINUX) || defined(SFML_SYSTEM_FREEBSD) || defined(SFML_SYSTEM_OPENBSD) || \ + defined(SFML_SYSTEM_NETBSD) - #if defined(SFML_OPENGL_ES) +#if defined(SFML_OPENGL_ES) - using ContextType = sf::priv::EglContext; +using ContextType = sf::priv::EglContext; - #elif defined(SFML_USE_DRM) +#elif defined(SFML_USE_DRM) - #include - using ContextType = sf::priv::DRMContext; +#include +using ContextType = sf::priv::DRMContext; - #else +#else - #include - using ContextType = sf::priv::GlxContext; +#include +using ContextType = sf::priv::GlxContext; - #endif +#endif #elif defined(SFML_SYSTEM_MACOS) - #include - using ContextType = sf::priv::SFContext; +#include +using ContextType = sf::priv::SFContext; #elif defined(SFML_SYSTEM_IOS) - #include - using ContextType = sf::priv::EaglContext; +#include +using ContextType = sf::priv::EaglContext; #elif defined(SFML_SYSTEM_ANDROID) - using ContextType = sf::priv::EglContext; +using ContextType = sf::priv::EglContext; #endif #if defined(SFML_SYSTEM_WINDOWS) - using glEnableFuncType = void (APIENTRY *)(GLenum); - using glGetErrorFuncType = GLenum (APIENTRY *)(); - using glGetIntegervFuncType = void (APIENTRY *)(GLenum, GLint*); - using glGetStringFuncType = const GLubyte* (APIENTRY *)(GLenum); - using glGetStringiFuncType = const GLubyte* (APIENTRY *)(GLenum, GLuint); - using glIsEnabledFuncType = GLboolean (APIENTRY *)(GLenum); +using glEnableFuncType = void(APIENTRY*)(GLenum); +using glGetErrorFuncType = GLenum(APIENTRY*)(); +using glGetIntegervFuncType = void(APIENTRY*)(GLenum, GLint*); +using glGetStringFuncType = const GLubyte*(APIENTRY*)(GLenum); +using glGetStringiFuncType = const GLubyte*(APIENTRY*)(GLenum, GLuint); +using glIsEnabledFuncType = GLboolean(APIENTRY*)(GLenum); #else - using glEnableFuncType = void (*)(GLenum); - using glGetErrorFuncType = GLenum (*)(); - using glGetIntegervFuncType = void (*)(GLenum, GLint*); - using glGetStringFuncType = const GLubyte* (*)(GLenum); - using glGetStringiFuncType = const GLubyte* (*)(GLenum, GLuint); - using glIsEnabledFuncType = GLboolean (*)(GLenum); +using glEnableFuncType = void (*)(GLenum); +using glGetErrorFuncType = GLenum (*)(); +using glGetIntegervFuncType = void (*)(GLenum, GLint*); +using glGetStringFuncType = const GLubyte* (*)(GLenum); +using glGetStringiFuncType = const GLubyte* (*)(GLenum, GLuint); +using glIsEnabledFuncType = GLboolean (*)(GLenum); #endif #if !defined(GL_MULTISAMPLE) - #define GL_MULTISAMPLE 0x809D +#define GL_MULTISAMPLE 0x809D #endif #if !defined(GL_MAJOR_VERSION) - #define GL_MAJOR_VERSION 0x821B +#define GL_MAJOR_VERSION 0x821B #endif #if !defined(GL_MINOR_VERSION) - #define GL_MINOR_VERSION 0x821C +#define GL_MINOR_VERSION 0x821C #endif #if !defined(GL_NUM_EXTENSIONS) - #define GL_NUM_EXTENSIONS 0x821D +#define GL_NUM_EXTENSIONS 0x821D #endif #if !defined(GL_CONTEXT_FLAGS) - #define GL_CONTEXT_FLAGS 0x821E +#define GL_CONTEXT_FLAGS 0x821E #endif #if !defined(GL_FRAMEBUFFER_SRGB) - #define GL_FRAMEBUFFER_SRGB 0x8DB9 +#define GL_FRAMEBUFFER_SRGB 0x8DB9 #endif #if !defined(GL_CONTEXT_FLAG_DEBUG_BIT) - #define GL_CONTEXT_FLAG_DEBUG_BIT 0x00000002 +#define GL_CONTEXT_FLAG_DEBUG_BIT 0x00000002 #endif #if !defined(GL_CONTEXT_PROFILE_MASK) - #define GL_CONTEXT_PROFILE_MASK 0x9126 +#define GL_CONTEXT_PROFILE_MASK 0x9126 #endif #if !defined(GL_CONTEXT_CORE_PROFILE_BIT) - #define GL_CONTEXT_CORE_PROFILE_BIT 0x00000001 +#define GL_CONTEXT_CORE_PROFILE_BIT 0x00000001 #endif #if !defined(GL_CONTEXT_COMPATIBILITY_PROFILE_BIT) - #define GL_CONTEXT_COMPATIBILITY_PROFILE_BIT 0x00000002 +#define GL_CONTEXT_COMPATIBILITY_PROFILE_BIT 0x00000002 #endif namespace { - // A nested named namespace is used here to allow unity builds of SFML. - namespace GlContextImpl +// A nested named namespace is used here to allow unity builds of SFML. +namespace GlContextImpl +{ +// AMD drivers have issues with internal synchronization +// We need to make sure that no operating system context +// or pixel format operations are performed simultaneously +// This mutex is also used to protect the shared context +// from being locked on multiple threads and for managing +// the resource count +std::recursive_mutex mutex; + +// OpenGL resources counter +unsigned int resourceCount = 0; + +// This per-thread variable holds the current context for each thread +thread_local sf::priv::GlContext* currentContext(nullptr); + +// The hidden, inactive context that will be shared with all other contexts +std::unique_ptr sharedContext; + +// Unique identifier, used for identifying contexts when managing unshareable OpenGL resources +sf::Uint64 id = 1; // start at 1, zero is "no context" + +// Set containing callback functions to be called whenever a +// context is going to be destroyed +// Unshareable OpenGL resources rely on this to clean up properly +// whenever a context containing them is destroyed +using ContextDestroyCallbacks = std::unordered_map; +ContextDestroyCallbacks contextDestroyCallbacks; + +// This structure contains all the state necessary to +// track TransientContext usage +struct TransientContext +{ + //////////////////////////////////////////////////////////// + /// \brief Constructor + /// + //////////////////////////////////////////////////////////// + TransientContext() : referenceCount(0), context(nullptr), sharedContextLock(), useSharedContext(false) { - // AMD drivers have issues with internal synchronization - // We need to make sure that no operating system context - // or pixel format operations are performed simultaneously - // This mutex is also used to protect the shared context - // from being locked on multiple threads and for managing - // the resource count - std::recursive_mutex mutex; - - // OpenGL resources counter - unsigned int resourceCount = 0; - - // This per-thread variable holds the current context for each thread - thread_local sf::priv::GlContext* currentContext(nullptr); - - // The hidden, inactive context that will be shared with all other contexts - std::unique_ptr sharedContext; - - // Unique identifier, used for identifying contexts when managing unshareable OpenGL resources - sf::Uint64 id = 1; // start at 1, zero is "no context" - - // Set containing callback functions to be called whenever a - // context is going to be destroyed - // Unshareable OpenGL resources rely on this to clean up properly - // whenever a context containing them is destroyed - using ContextDestroyCallbacks = std::unordered_map; - ContextDestroyCallbacks contextDestroyCallbacks; - - // This structure contains all the state necessary to - // track TransientContext usage - struct TransientContext + if (resourceCount == 0) { - //////////////////////////////////////////////////////////// - /// \brief Constructor - /// - //////////////////////////////////////////////////////////// - TransientContext() : - referenceCount (0), - context (nullptr), - sharedContextLock(), - useSharedContext (false) - { - if (resourceCount == 0) - { - context = std::make_unique(); - } - else if (!currentContext) - { - sharedContextLock.emplace(mutex); - useSharedContext = true; - sharedContext->setActive(true); - } - } - - //////////////////////////////////////////////////////////// - /// \brief Destructor - /// - //////////////////////////////////////////////////////////// - ~TransientContext() - { - if (useSharedContext) - sharedContext->setActive(false); - - sharedContextLock.reset(); - context.reset(); - } - - //////////////////////////////////////////////////////////// - /// \brief Deleted copy constructor - /// - //////////////////////////////////////////////////////////// - TransientContext(const TransientContext&) = delete; - - //////////////////////////////////////////////////////////// - /// \brief Deleted copy assignment - /// - //////////////////////////////////////////////////////////// - TransientContext& operator=(const TransientContext&) = delete; - - /////////////////////////////////////////////////////////// - // Member data - //////////////////////////////////////////////////////////// - unsigned int referenceCount; - std::unique_ptr context; - std::optional> sharedContextLock; - bool useSharedContext; - }; - - // This per-thread variable tracks if and how a transient - // context is currently being used on the current thread - thread_local std::unique_ptr transientContext; - - // Supported OpenGL extensions - std::vector extensions; - - // Load our extensions vector with the supported extensions - void loadExtensions() - { - extensions.clear(); - - auto glGetErrorFunc = reinterpret_cast(sf::priv::GlContext::getFunction("glGetError")); - auto glGetIntegervFunc = reinterpret_cast(sf::priv::GlContext::getFunction("glGetIntegerv")); - auto glGetStringFunc = reinterpret_cast(sf::priv::GlContext::getFunction("glGetString")); - - if (!glGetErrorFunc || !glGetIntegervFunc || !glGetStringFunc) - return; - - // Check whether a >= 3.0 context is available - int majorVersion = 0; - glGetIntegervFunc(GL_MAJOR_VERSION, &majorVersion); - - auto glGetStringiFunc = reinterpret_cast(sf::priv::GlContext::getFunction("glGetStringi")); - - if (glGetErrorFunc() == GL_INVALID_ENUM || !glGetStringiFunc) - { - // Try to load the < 3.0 way - const char* extensionString = reinterpret_cast(glGetStringFunc(GL_EXTENSIONS)); - - do - { - const char* extension = extensionString; - - while (*extensionString && (*extensionString != ' ')) - ++extensionString; - - extensions.emplace_back(extension, extensionString); - } - while (*extensionString++); - } - else - { - // Try to load the >= 3.0 way - int numExtensions = 0; - glGetIntegervFunc(GL_NUM_EXTENSIONS, &numExtensions); - - if (numExtensions) - { - for (unsigned int i = 0; i < static_cast(numExtensions); ++i) - { - const char* extensionString = reinterpret_cast(glGetStringiFunc(GL_EXTENSIONS, i)); - extensions.emplace_back(extensionString); - } - } - } + context = std::make_unique(); } - - // Helper to parse OpenGL version strings - bool parseVersionString(const char* version, const char* prefix, unsigned int &major, unsigned int &minor) + else if (!currentContext) { - std::size_t prefixLength = std::strlen(prefix); + sharedContextLock.emplace(mutex); + useSharedContext = true; + sharedContext->setActive(true); + } + } - if ((std::strlen(version) >= (prefixLength + 3)) && - (std::strncmp(version, prefix, prefixLength) == 0) && - std::isdigit(version[prefixLength]) && - (version[prefixLength + 1] == '.') && - std::isdigit(version[prefixLength + 2])) + //////////////////////////////////////////////////////////// + /// \brief Destructor + /// + //////////////////////////////////////////////////////////// + ~TransientContext() + { + if (useSharedContext) + sharedContext->setActive(false); + + sharedContextLock.reset(); + context.reset(); + } + + //////////////////////////////////////////////////////////// + /// \brief Deleted copy constructor + /// + //////////////////////////////////////////////////////////// + TransientContext(const TransientContext&) = delete; + + //////////////////////////////////////////////////////////// + /// \brief Deleted copy assignment + /// + //////////////////////////////////////////////////////////// + TransientContext& operator=(const TransientContext&) = delete; + + /////////////////////////////////////////////////////////// + // Member data + //////////////////////////////////////////////////////////// + unsigned int referenceCount; + std::unique_ptr context; + std::optional> sharedContextLock; + bool useSharedContext; +}; + +// This per-thread variable tracks if and how a transient +// context is currently being used on the current thread +thread_local std::unique_ptr transientContext; + +// Supported OpenGL extensions +std::vector extensions; + +// Load our extensions vector with the supported extensions +void loadExtensions() +{ + extensions.clear(); + + auto glGetErrorFunc = reinterpret_cast(sf::priv::GlContext::getFunction("glGetError")); + auto glGetIntegervFunc = reinterpret_cast(sf::priv::GlContext::getFunction("glGetIntegerv")); + auto glGetStringFunc = reinterpret_cast(sf::priv::GlContext::getFunction("glGetString")); + + if (!glGetErrorFunc || !glGetIntegervFunc || !glGetStringFunc) + return; + + // Check whether a >= 3.0 context is available + int majorVersion = 0; + glGetIntegervFunc(GL_MAJOR_VERSION, &majorVersion); + + auto glGetStringiFunc = reinterpret_cast(sf::priv::GlContext::getFunction("glGetStringi")); + + if (glGetErrorFunc() == GL_INVALID_ENUM || !glGetStringiFunc) + { + // Try to load the < 3.0 way + const char* extensionString = reinterpret_cast(glGetStringFunc(GL_EXTENSIONS)); + + do + { + const char* extension = extensionString; + + while (*extensionString && (*extensionString != ' ')) + ++extensionString; + + extensions.emplace_back(extension, extensionString); + } while (*extensionString++); + } + else + { + // Try to load the >= 3.0 way + int numExtensions = 0; + glGetIntegervFunc(GL_NUM_EXTENSIONS, &numExtensions); + + if (numExtensions) + { + for (unsigned int i = 0; i < static_cast(numExtensions); ++i) { - major = static_cast(version[prefixLength] - '0'); - minor = static_cast(version[prefixLength + 2] - '0'); - - return true; + const char* extensionString = reinterpret_cast(glGetStringiFunc(GL_EXTENSIONS, i)); + extensions.emplace_back(extensionString); } - - return false; } } } +// Helper to parse OpenGL version strings +bool parseVersionString(const char* version, const char* prefix, unsigned int& major, unsigned int& minor) +{ + std::size_t prefixLength = std::strlen(prefix); + + if ((std::strlen(version) >= (prefixLength + 3)) && (std::strncmp(version, prefix, prefixLength) == 0) && + std::isdigit(version[prefixLength]) && (version[prefixLength + 1] == '.') && + std::isdigit(version[prefixLength + 2])) + { + major = static_cast(version[prefixLength] - '0'); + minor = static_cast(version[prefixLength + 2] - '0'); + + return true; + } + + return false; +} +} // namespace GlContextImpl +} // namespace + namespace sf { @@ -334,11 +330,11 @@ namespace priv //////////////////////////////////////////////////////////// void GlContext::initResource() { + using GlContextImpl::currentContext; + using GlContextImpl::loadExtensions; using GlContextImpl::mutex; using GlContextImpl::resourceCount; - using GlContextImpl::currentContext; using GlContextImpl::sharedContext; - using GlContextImpl::loadExtensions; // Protect from concurrent access std::scoped_lock lock(mutex); @@ -480,10 +476,10 @@ std::unique_ptr GlContext::create() //////////////////////////////////////////////////////////// std::unique_ptr GlContext::create(const ContextSettings& settings, const WindowImpl& owner, unsigned int bitsPerPixel) { + using GlContextImpl::loadExtensions; using GlContextImpl::mutex; using GlContextImpl::resourceCount; using GlContextImpl::sharedContext; - using GlContextImpl::loadExtensions; // Make sure that there's an active context (context creation may need extensions, and thus a valid context) assert(sharedContext != nullptr); @@ -494,8 +490,7 @@ std::unique_ptr GlContext::create(const ContextSettings& settings, co // Only in this situation we allow the user to indirectly re-create the shared context as a core context // Check if we need to convert our shared context into a core context - if ((resourceCount == 1) && - (settings.attributeFlags & ContextSettings::Core) && + if ((resourceCount == 1) && (settings.attributeFlags & ContextSettings::Core) && !(sharedContext->m_settings.attributeFlags & ContextSettings::Core)) { // Re-create our shared context as a core context @@ -532,10 +527,10 @@ std::unique_ptr GlContext::create(const ContextSettings& settings, co //////////////////////////////////////////////////////////// std::unique_ptr GlContext::create(const ContextSettings& settings, const Vector2u& size) { + using GlContextImpl::loadExtensions; using GlContextImpl::mutex; using GlContextImpl::resourceCount; using GlContextImpl::sharedContext; - using GlContextImpl::loadExtensions; // Make sure that there's an active context (context creation may need extensions, and thus a valid context) assert(sharedContext != nullptr); @@ -546,8 +541,7 @@ std::unique_ptr GlContext::create(const ContextSettings& settings, co // Only in this situation we allow the user to indirectly re-create the shared context as a core context // Check if we need to convert our shared context into a core context - if ((resourceCount == 1) && - (settings.attributeFlags & ContextSettings::Core) && + if ((resourceCount == 1) && (settings.attributeFlags & ContextSettings::Core) && !(sharedContext->m_settings.attributeFlags & ContextSettings::Core)) { // Re-create our shared context as a core context @@ -639,8 +633,8 @@ const ContextSettings& GlContext::getSettings() const //////////////////////////////////////////////////////////// bool GlContext::setActive(bool active) { - using GlContextImpl::mutex; using GlContextImpl::currentContext; + using GlContextImpl::mutex; using GlContextImpl::sharedContext; if (active) @@ -694,25 +688,32 @@ bool GlContext::setActive(bool active) //////////////////////////////////////////////////////////// -GlContext::GlContext() : -m_id(GlContextImpl::id++) +GlContext::GlContext() : m_id(GlContextImpl::id++) { // Nothing to do } //////////////////////////////////////////////////////////// -int GlContext::evaluateFormat(unsigned int bitsPerPixel, const ContextSettings& settings, int colorBits, int depthBits, int stencilBits, int antialiasing, bool accelerated, bool sRgb) +int GlContext::evaluateFormat( + unsigned int bitsPerPixel, + const ContextSettings& settings, + int colorBits, + int depthBits, + int stencilBits, + int antialiasing, + bool accelerated, + bool sRgb) { - int colorDiff = static_cast(bitsPerPixel) - colorBits; - int depthDiff = static_cast(settings.depthBits) - depthBits; - int stencilDiff = static_cast(settings.stencilBits) - stencilBits; + int colorDiff = static_cast(bitsPerPixel) - colorBits; + int depthDiff = static_cast(settings.depthBits) - depthBits; + int stencilDiff = static_cast(settings.stencilBits) - stencilBits; int antialiasingDiff = static_cast(settings.antialiasingLevel) - antialiasing; // Weight sub-scores so that better settings don't score equally as bad as worse settings - colorDiff *= ((colorDiff > 0) ? 100000 : 1); - depthDiff *= ((depthDiff > 0) ? 100000 : 1); - stencilDiff *= ((stencilDiff > 0) ? 100000 : 1); + colorDiff *= ((colorDiff > 0) ? 100000 : 1); + depthDiff *= ((depthDiff > 0) ? 100000 : 1); + stencilDiff *= ((stencilDiff > 0) ? 100000 : 1); antialiasingDiff *= ((antialiasingDiff > 0) ? 100000 : 1); // Aggregate the scores @@ -733,9 +734,9 @@ int GlContext::evaluateFormat(unsigned int bitsPerPixel, const ContextSettings& //////////////////////////////////////////////////////////// void GlContext::cleanupUnsharedResources() { - using GlContextImpl::currentContext; using GlContextImpl::ContextDestroyCallbacks; using GlContextImpl::contextDestroyCallbacks; + using GlContextImpl::currentContext; // Save the current context so we can restore it later GlContext* contextToRestore = currentContext; @@ -769,10 +770,10 @@ void GlContext::initialize(const ContextSettings& requestedSettings) // Try the new way first auto glGetIntegervFunc = reinterpret_cast(getFunction("glGetIntegerv")); - auto glGetErrorFunc = reinterpret_cast(getFunction("glGetError")); - auto glGetStringFunc = reinterpret_cast(getFunction("glGetString")); - auto glEnableFunc = reinterpret_cast(getFunction("glEnable")); - auto glIsEnabledFunc = reinterpret_cast(getFunction("glIsEnabled")); + auto glGetErrorFunc = reinterpret_cast(getFunction("glGetError")); + auto glGetStringFunc = reinterpret_cast(getFunction("glGetString")); + auto glEnableFunc = reinterpret_cast(getFunction("glEnable")); + auto glIsEnabledFunc = reinterpret_cast(getFunction("glIsEnabled")); if (!glGetIntegervFunc || !glGetErrorFunc || !glGetStringFunc || !glEnableFunc || !glIsEnabledFunc) { @@ -808,10 +809,11 @@ void GlContext::initialize(const ContextSettings& requestedSettings) if (!parseVersionString(version, "OpenGL ES-CL ", m_settings.majorVersion, m_settings.minorVersion) && !parseVersionString(version, "OpenGL ES-CM ", m_settings.majorVersion, m_settings.minorVersion) && - !parseVersionString(version, "OpenGL ES ", m_settings.majorVersion, m_settings.minorVersion) && - !parseVersionString(version, "", m_settings.majorVersion, m_settings.minorVersion)) + !parseVersionString(version, "OpenGL ES ", m_settings.majorVersion, m_settings.minorVersion) && + !parseVersionString(version, "", m_settings.majorVersion, m_settings.minorVersion)) { - err() << "Unable to parse OpenGL version string: " << std::quoted(version) << ", defaulting to 1.1" << std::endl; + err() << "Unable to parse OpenGL version string: " << std::quoted(version) << ", defaulting to 1.1" + << std::endl; } } else @@ -925,7 +927,7 @@ void GlContext::checkSettings(const ContextSettings& requestedSettings) } // Detect any known non-accelerated implementations and warn - const char* vendorName = reinterpret_cast(glGetStringFunc(GL_VENDOR)); + const char* vendorName = reinterpret_cast(glGetStringFunc(GL_VENDOR)); const char* rendererName = reinterpret_cast(glGetStringFunc(GL_RENDERER)); if (vendorName && rendererName) @@ -937,35 +939,27 @@ void GlContext::checkSettings(const ContextSettings& requestedSettings) } } - int version = static_cast(m_settings.majorVersion * 10u + m_settings.minorVersion); + int version = static_cast(m_settings.majorVersion * 10u + m_settings.minorVersion); int requestedVersion = static_cast(requestedSettings.majorVersion * 10u + requestedSettings.minorVersion); - if ((m_settings.attributeFlags != requestedSettings.attributeFlags) || - (version < requestedVersion) || - (m_settings.stencilBits < requestedSettings.stencilBits) || - (m_settings.antialiasingLevel < requestedSettings.antialiasingLevel) || - (m_settings.depthBits < requestedSettings.depthBits) || - (!m_settings.sRgbCapable && requestedSettings.sRgbCapable)) + if ((m_settings.attributeFlags != requestedSettings.attributeFlags) || (version < requestedVersion) || + (m_settings.stencilBits < requestedSettings.stencilBits) || + (m_settings.antialiasingLevel < requestedSettings.antialiasingLevel) || + (m_settings.depthBits < requestedSettings.depthBits) || (!m_settings.sRgbCapable && requestedSettings.sRgbCapable)) { err() << "Warning: The created OpenGL context does not fully meet the settings that were requested" << '\n' << "Requested: version = " << requestedSettings.majorVersion << "." << requestedSettings.minorVersion - << " ; depth bits = " << requestedSettings.depthBits - << " ; stencil bits = " << requestedSettings.stencilBits - << " ; AA level = " << requestedSettings.antialiasingLevel - << std::boolalpha + << " ; depth bits = " << requestedSettings.depthBits << " ; stencil bits = " << requestedSettings.stencilBits + << " ; AA level = " << requestedSettings.antialiasingLevel << std::boolalpha << " ; core = " << ((requestedSettings.attributeFlags & ContextSettings::Core) != 0) << " ; debug = " << ((requestedSettings.attributeFlags & ContextSettings::Debug) != 0) - << " ; sRGB = " << requestedSettings.sRgbCapable - << std::noboolalpha << '\n' + << " ; sRGB = " << requestedSettings.sRgbCapable << std::noboolalpha << '\n' << "Created: version = " << m_settings.majorVersion << "." << m_settings.minorVersion - << " ; depth bits = " << m_settings.depthBits - << " ; stencil bits = " << m_settings.stencilBits - << " ; AA level = " << m_settings.antialiasingLevel - << std::boolalpha + << " ; depth bits = " << m_settings.depthBits << " ; stencil bits = " << m_settings.stencilBits + << " ; AA level = " << m_settings.antialiasingLevel << std::boolalpha << " ; core = " << ((m_settings.attributeFlags & ContextSettings::Core) != 0) << " ; debug = " << ((m_settings.attributeFlags & ContextSettings::Debug) != 0) - << " ; sRGB = " << m_settings.sRgbCapable - << std::noboolalpha << std::endl; + << " ; sRGB = " << m_settings.sRgbCapable << std::noboolalpha << std::endl; } } diff --git a/src/SFML/Window/GlContext.hpp b/src/SFML/Window/GlContext.hpp index 976e19aa0..d376d9ede 100644 --- a/src/SFML/Window/GlContext.hpp +++ b/src/SFML/Window/GlContext.hpp @@ -29,9 +29,11 @@ // Headers //////////////////////////////////////////////////////////// #include + #include #include #include + #include @@ -48,7 +50,6 @@ class WindowImpl; class GlContext { public: - //////////////////////////////////////////////////////////// /// \brief Perform resource initialization /// @@ -241,7 +242,6 @@ public: virtual void setVerticalSyncEnabled(bool enabled) = 0; protected: - //////////////////////////////////////////////////////////// /// \brief Default constructor /// @@ -287,7 +287,14 @@ protected: /// \return Score of the configuration /// //////////////////////////////////////////////////////////// - static int evaluateFormat(unsigned int bitsPerPixel, const ContextSettings& settings, int colorBits, int depthBits, int stencilBits, int antialiasing, bool accelerated, bool sRgb); + static int evaluateFormat(unsigned int bitsPerPixel, + const ContextSettings& settings, + int colorBits, + int depthBits, + int stencilBits, + int antialiasing, + bool accelerated, + bool sRgb); //////////////////////////////////////////////////////////// // Member data @@ -295,7 +302,6 @@ protected: ContextSettings m_settings; //!< Creation settings of the context private: - //////////////////////////////////////////////////////////// /// \brief Perform various initializations after the context construction /// \param requestedSettings Requested settings during context creation diff --git a/src/SFML/Window/GlResource.cpp b/src/SFML/Window/GlResource.cpp index 76929774b..19ce22f96 100644 --- a/src/SFML/Window/GlResource.cpp +++ b/src/SFML/Window/GlResource.cpp @@ -25,8 +25,8 @@ //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// -#include #include +#include namespace sf diff --git a/src/SFML/Window/InputImpl.hpp b/src/SFML/Window/InputImpl.hpp index 9655f7078..9457d1338 100644 --- a/src/SFML/Window/InputImpl.hpp +++ b/src/SFML/Window/InputImpl.hpp @@ -31,19 +31,20 @@ #include #if defined(SFML_SYSTEM_WINDOWS) - #include -#elif defined(SFML_SYSTEM_LINUX) || defined(SFML_SYSTEM_FREEBSD) || defined(SFML_SYSTEM_OPENBSD) || defined(SFML_SYSTEM_NETBSD) - #if defined(SFML_USE_DRM) - #include - #else - #include - #endif +#include +#elif defined(SFML_SYSTEM_LINUX) || defined(SFML_SYSTEM_FREEBSD) || defined(SFML_SYSTEM_OPENBSD) || \ + defined(SFML_SYSTEM_NETBSD) +#if defined(SFML_USE_DRM) +#include +#else +#include +#endif #elif defined(SFML_SYSTEM_MACOS) - #include +#include #elif defined(SFML_SYSTEM_IOS) - #include +#include #elif defined(SFML_SYSTEM_ANDROID) - #include +#include #endif #endif // SFML_INPUTIMPL_HPP diff --git a/src/SFML/Window/Joystick.cpp b/src/SFML/Window/Joystick.cpp index 9aafe3641..a443ed48b 100644 --- a/src/SFML/Window/Joystick.cpp +++ b/src/SFML/Window/Joystick.cpp @@ -81,12 +81,8 @@ void Joystick::update() //////////////////////////////////////////////////////////// -Joystick::Identification::Identification() : -name ("No Joystick"), -vendorId (0), -productId(0) +Joystick::Identification::Identification() : name("No Joystick"), vendorId(0), productId(0) { - } } // namespace sf diff --git a/src/SFML/Window/JoystickImpl.hpp b/src/SFML/Window/JoystickImpl.hpp index 0399313cd..0e01f43b4 100644 --- a/src/SFML/Window/JoystickImpl.hpp +++ b/src/SFML/Window/JoystickImpl.hpp @@ -29,6 +29,7 @@ // Headers //////////////////////////////////////////////////////////// #include + #include @@ -65,35 +66,35 @@ struct JoystickState #if defined(SFML_SYSTEM_WINDOWS) - #include +#include #elif defined(SFML_SYSTEM_LINUX) - #include +#include #elif defined(SFML_SYSTEM_FREEBSD) - #include +#include #elif defined(SFML_SYSTEM_OPENBSD) - #include +#include #elif defined(SFML_SYSTEM_NETBSD) - #include +#include #elif defined(SFML_SYSTEM_MACOS) - #include +#include #elif defined(SFML_SYSTEM_IOS) - #include +#include #elif defined(SFML_SYSTEM_ANDROID) - #include +#include #endif diff --git a/src/SFML/Window/JoystickManager.hpp b/src/SFML/Window/JoystickManager.hpp index 9f149b3b4..f6a9d701c 100644 --- a/src/SFML/Window/JoystickManager.hpp +++ b/src/SFML/Window/JoystickManager.hpp @@ -43,7 +43,6 @@ namespace priv class JoystickManager { public: - //////////////////////////////////////////////////////////// /// \brief Get the global unique instance of the manager /// @@ -89,7 +88,6 @@ public: void update(); private: - //////////////////////////////////////////////////////////// /// \brief Default constructor /// diff --git a/src/SFML/Window/Keyboard.cpp b/src/SFML/Window/Keyboard.cpp index 764d2d6f6..34b3a1952 100644 --- a/src/SFML/Window/Keyboard.cpp +++ b/src/SFML/Window/Keyboard.cpp @@ -25,8 +25,8 @@ //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// -#include #include +#include namespace sf diff --git a/src/SFML/Window/Mouse.cpp b/src/SFML/Window/Mouse.cpp index 9589dad2f..00106bffd 100644 --- a/src/SFML/Window/Mouse.cpp +++ b/src/SFML/Window/Mouse.cpp @@ -25,8 +25,8 @@ //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// -#include #include +#include namespace sf diff --git a/src/SFML/Window/NetBSD/JoystickImpl.cpp b/src/SFML/Window/NetBSD/JoystickImpl.cpp index 7bf91e4c5..53dd5c6e0 100644 --- a/src/SFML/Window/NetBSD/JoystickImpl.cpp +++ b/src/SFML/Window/NetBSD/JoystickImpl.cpp @@ -27,13 +27,14 @@ // Headers //////////////////////////////////////////////////////////// #include -#include + +#include #include #include -#include -#include -#include #include +#include +#include +#include #include //////////////////////////////////////////////////////////// @@ -44,117 +45,124 @@ namespace { - std::unordered_map plugged; - std::unordered_map > hatValueMap; +std::unordered_map plugged; +std::unordered_map> hatValueMap; - bool isJoystick(const char *name) +bool isJoystick(const char* name) +{ + int file = ::open(name, O_RDONLY | O_NONBLOCK); + int id; + + if (file < 0) + return false; + + report_desc_t desc = hid_get_report_desc(file); + + if (!desc) { - int file = ::open(name, O_RDONLY | O_NONBLOCK); - int id; + ::close(file); + return false; + } - if (file < 0) - return false; + if (ioctl(file, USB_GET_REPORT_ID, &id) < 0) + { + ::close(file); + return false; + } - report_desc_t desc = hid_get_report_desc(file); + hid_data_t data = hid_start_parse(desc, 1 << hid_input, id); - if (!desc) - { - ::close(file); - return false; - } - - if (ioctl(file, USB_GET_REPORT_ID, &id) < 0) - { - ::close(file); - return false; - } - - hid_data_t data = hid_start_parse(desc, 1 << hid_input, id); - - if (!data) - { - hid_dispose_report_desc(desc); - ::close(file); - return false; - } - - hid_item_t item; - - // Assume it isn't - bool result = false; - - while (hid_get_item(data, &item) > 0) - { - if ((item.kind == hid_collection) && (HID_PAGE(item.usage) == HUP_GENERIC_DESKTOP)) - { - if ((HID_USAGE(item.usage) == HUG_JOYSTICK) || (HID_USAGE(item.usage) == HUG_GAME_PAD)) - { - result = true; - } - } - } - - hid_end_parse(data); + if (!data) + { hid_dispose_report_desc(desc); ::close(file); - - return result; + return false; } - void updatePluggedList() + hid_item_t item; + + // Assume it isn't + bool result = false; + + while (hid_get_item(data, &item) > 0) { - /* - * Devices /dev/uhid are shared between joystick and any other - * human interface device. We need to iterate over all found devices - * and check if they are joysticks. The index of JoystickImpl::open - * does not match the /dev/uhid device! - */ - DIR* directory = opendir("/dev"); - - if (directory) + if ((item.kind == hid_collection) && (HID_PAGE(item.usage) == HUP_GENERIC_DESKTOP)) { - int joystickCount = 0; - struct dirent* directoryEntry = readdir(directory); - - while (directoryEntry && joystickCount < sf::Joystick::Count) + if ((HID_USAGE(item.usage) == HUG_JOYSTICK) || (HID_USAGE(item.usage) == HUG_GAME_PAD)) { - if (!std::strncmp(directoryEntry->d_name, "uhid", 4)) - { - std::string name("/dev/"); - name += directoryEntry->d_name; + result = true; + } + } + } - if (isJoystick(name.c_str())) - plugged[joystickCount++] = name; - } + hid_end_parse(data); + hid_dispose_report_desc(desc); + ::close(file); - directoryEntry = readdir(directory); + return result; +} + +void updatePluggedList() +{ + /* + * Devices /dev/uhid are shared between joystick and any other + * human interface device. We need to iterate over all found devices + * and check if they are joysticks. The index of JoystickImpl::open + * does not match the /dev/uhid device! + */ + DIR* directory = opendir("/dev"); + + if (directory) + { + int joystickCount = 0; + struct dirent* directoryEntry = readdir(directory); + + while (directoryEntry && joystickCount < sf::Joystick::Count) + { + if (!std::strncmp(directoryEntry->d_name, "uhid", 4)) + { + std::string name("/dev/"); + name += directoryEntry->d_name; + + if (isJoystick(name.c_str())) + plugged[joystickCount++] = name; } - closedir(directory); + directoryEntry = readdir(directory); } - } - int usageToAxis(int usage) - { - switch (usage) - { - case HUG_X: return sf::Joystick::X; - case HUG_Y: return sf::Joystick::Y; - case HUG_Z: return sf::Joystick::Z; - case HUG_RZ: return sf::Joystick::R; - case HUG_RX: return sf::Joystick::U; - case HUG_RY: return sf::Joystick::V; - default: return -1; - } - } - - void hatValueToSfml(int value, sf::priv::JoystickState& state) - { - state.axes[sf::Joystick::PovX] = hatValueMap[value].first; - state.axes[sf::Joystick::PovY] = hatValueMap[value].second; + closedir(directory); } } +int usageToAxis(int usage) +{ + switch (usage) + { + case HUG_X: + return sf::Joystick::X; + case HUG_Y: + return sf::Joystick::Y; + case HUG_Z: + return sf::Joystick::Z; + case HUG_RZ: + return sf::Joystick::R; + case HUG_RX: + return sf::Joystick::U; + case HUG_RY: + return sf::Joystick::V; + default: + return -1; + } +} + +void hatValueToSfml(int value, sf::priv::JoystickState& state) +{ + state.axes[sf::Joystick::PovX] = hatValueMap[value].first; + state.axes[sf::Joystick::PovY] = hatValueMap[value].second; +} +} // namespace + namespace sf { @@ -169,16 +177,16 @@ void JoystickImpl::initialize() updatePluggedList(); // Map of hat values - hatValueMap[0] = std::make_pair( 0, 0); // center + hatValueMap[0] = std::make_pair(0, 0); // center - hatValueMap[1] = std::make_pair( 0, -100); // top - hatValueMap[3] = std::make_pair( 100, 0); // right - hatValueMap[5] = std::make_pair( 0, 100); // bottom - hatValueMap[7] = std::make_pair(-100, 0); // left + hatValueMap[1] = std::make_pair(0, -100); // top + hatValueMap[3] = std::make_pair(100, 0); // right + hatValueMap[5] = std::make_pair(0, 100); // bottom + hatValueMap[7] = std::make_pair(-100, 0); // left - hatValueMap[2] = std::make_pair( 100, -100); // top-right - hatValueMap[4] = std::make_pair( 100, 100); // bottom-right - hatValueMap[6] = std::make_pair(-100, 100); // bottom-left + hatValueMap[2] = std::make_pair(100, -100); // top-right + hatValueMap[4] = std::make_pair(100, 100); // bottom-right + hatValueMap[6] = std::make_pair(-100, 100); // bottom-left hatValueMap[8] = std::make_pair(-100, -100); // top-left } @@ -249,7 +257,7 @@ void JoystickImpl::close() JoystickCaps JoystickImpl::getCapabilities() const { JoystickCaps caps; - hid_item_t item; + hid_item_t item; hid_data_t data = hid_start_parse(m_desc, 1 << hid_input, m_id); @@ -305,7 +313,7 @@ JoystickState JoystickImpl::JoystickImpl::update() if (!data) continue; - int buttonIndex = 0; + int buttonIndex = 0; hid_item_t item; while (hid_get_item(data, &item)) @@ -321,7 +329,7 @@ JoystickState JoystickImpl::JoystickImpl::update() else if (usage == HUP_GENERIC_DESKTOP) { int value = hid_get_data(m_buffer.data(), &item); - int axis = usageToAxis(usage); + int axis = usageToAxis(usage); if (usage == HUG_HAT_SWITCH) { @@ -332,7 +340,7 @@ JoystickState JoystickImpl::JoystickImpl::update() int minimum = item.logical_minimum; int maximum = item.logical_maximum; - value = (value - minimum) * 200 / (maximum - minimum) - 100; + value = (value - minimum) * 200 / (maximum - minimum) - 100; m_state.axes[axis] = value; } } diff --git a/src/SFML/Window/NetBSD/JoystickImpl.hpp b/src/SFML/Window/NetBSD/JoystickImpl.hpp index 9700d182f..49ebc323f 100644 --- a/src/SFML/Window/NetBSD/JoystickImpl.hpp +++ b/src/SFML/Window/NetBSD/JoystickImpl.hpp @@ -45,7 +45,6 @@ namespace priv class JoystickImpl { public: - //////////////////////////////////////////////////////////// /// \brief Perform the global initialization of the joystick module /// @@ -109,7 +108,6 @@ public: [[nodiscard]] JoystickState update(); private: - //////////////////////////////////////////////////////////// // Member data //////////////////////////////////////////////////////////// diff --git a/src/SFML/Window/OSX/AutoreleasePoolWrapper.hpp b/src/SFML/Window/OSX/AutoreleasePoolWrapper.hpp index 67edde127..8ba5b1a5e 100644 --- a/src/SFML/Window/OSX/AutoreleasePoolWrapper.hpp +++ b/src/SFML/Window/OSX/AutoreleasePoolWrapper.hpp @@ -64,7 +64,6 @@ public: ~AutoreleasePool(); private: - //////////////////////////////////////////////////////////// // Member data //////////////////////////////////////////////////////////// diff --git a/src/SFML/Window/OSX/ClipboardImpl.hpp b/src/SFML/Window/OSX/ClipboardImpl.hpp index 531a38356..82bf30e24 100644 --- a/src/SFML/Window/OSX/ClipboardImpl.hpp +++ b/src/SFML/Window/OSX/ClipboardImpl.hpp @@ -40,7 +40,6 @@ namespace priv class ClipboardImpl { public: - //////////////////////////////////////////////////////////// /// \brief Get the content of the clipboard as string data /// @@ -72,4 +71,3 @@ public: #endif // SFML_CLIPBOARDIMPLCOCOA_HPP - diff --git a/src/SFML/Window/OSX/ClipboardImpl.mm b/src/SFML/Window/OSX/ClipboardImpl.mm index 8425944ef..4c98fcc10 100644 --- a/src/SFML/Window/OSX/ClipboardImpl.mm +++ b/src/SFML/Window/OSX/ClipboardImpl.mm @@ -25,9 +25,9 @@ //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// +#include #include #include -#include #import @@ -40,11 +40,11 @@ namespace priv String ClipboardImpl::getString() { AutoreleasePool pool; - NSPasteboard* pboard = [NSPasteboard generalPasteboard]; - NSString* data = [pboard stringForType:NSPasteboardTypeString]; + NSPasteboard* pboard = [NSPasteboard generalPasteboard]; + NSString* data = [pboard stringForType:NSPasteboardTypeString]; - char const* utf8 = [data cStringUsingEncoding:NSUTF8StringEncoding]; - NSUInteger length = [data lengthOfBytesUsingEncoding:NSUTF8StringEncoding]; + char const* utf8 = [data cStringUsingEncoding:NSUTF8StringEncoding]; + NSUInteger length = [data lengthOfBytesUsingEncoding:NSUTF8StringEncoding]; return String::fromUtf8(utf8, utf8 + length); } @@ -53,11 +53,9 @@ String ClipboardImpl::getString() //////////////////////////////////////////////////////////// void ClipboardImpl::setString(const String& text) { - AutoreleasePool pool; + AutoreleasePool pool; std::basic_string utf8 = text.toUtf8(); - NSString* data = [[NSString alloc] initWithBytes:utf8.data() - length:utf8.length() - encoding:NSUTF8StringEncoding]; + NSString* data = [[NSString alloc] initWithBytes:utf8.data() length:utf8.length() encoding:NSUTF8StringEncoding]; NSPasteboard* pboard = [NSPasteboard generalPasteboard]; [pboard declareTypes:@[NSPasteboardTypeString] owner:nil]; @@ -69,4 +67,3 @@ void ClipboardImpl::setString(const String& text) } // namespace priv } // namespace sf - diff --git a/src/SFML/Window/OSX/CursorImpl.hpp b/src/SFML/Window/OSX/CursorImpl.hpp index b1cc907e3..0bb8cdf75 100644 --- a/src/SFML/Window/OSX/CursorImpl.hpp +++ b/src/SFML/Window/OSX/CursorImpl.hpp @@ -29,8 +29,8 @@ //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// -#include #include +#include //////////////////////////////////////////////////////////// // Predefine OBJ-C classes @@ -58,7 +58,6 @@ namespace priv class CursorImpl { public: - //////////////////////////////////////////////////////////// /// \brief Default constructor /// @@ -104,7 +103,6 @@ public: bool loadFromSystem(Cursor::Type type); private: - friend class WindowImplCocoa; //////////////////////////////////////////////////////////// diff --git a/src/SFML/Window/OSX/CursorImpl.mm b/src/SFML/Window/OSX/CursorImpl.mm index 3cee96a59..a59379504 100644 --- a/src/SFML/Window/OSX/CursorImpl.mm +++ b/src/SFML/Window/OSX/CursorImpl.mm @@ -26,10 +26,10 @@ //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// -#include #include - +#include #import + #import namespace @@ -53,10 +53,8 @@ namespace priv { //////////////////////////////////////////////////////////// -CursorImpl::CursorImpl() : -m_cursor(nil) +CursorImpl::CursorImpl() : m_cursor(nil) { - } @@ -91,7 +89,7 @@ bool CursorImpl::loadFromPixels(const Uint8* pixels, Vector2u size, Vector2u hot bool CursorImpl::loadFromSystem(Cursor::Type type) { AutoreleasePool pool; - NSCursor* newCursor = nil; + NSCursor* newCursor = nil; // clang-format off switch (type) @@ -146,4 +144,3 @@ bool CursorImpl::loadFromSystem(Cursor::Type type) } // namespace priv } // namespace sf - diff --git a/src/SFML/Window/OSX/HIDInputManager.hpp b/src/SFML/Window/OSX/HIDInputManager.hpp index 8b60d9f47..1ad132bf8 100644 --- a/src/SFML/Window/OSX/HIDInputManager.hpp +++ b/src/SFML/Window/OSX/HIDInputManager.hpp @@ -31,6 +31,7 @@ //////////////////////////////////////////////////////////// #include #include + #include #include #include @@ -53,7 +54,6 @@ using IOHIDElements = std::vector; class HIDInputManager { public: - //////////////////////////////////////////////////////////// /// \brief Get the unique instance of the class /// @@ -75,7 +75,6 @@ public: bool isKeyPressed(Keyboard::Key key); public: - //////////////////////////////////////////////////////////// /// \brief Get the usb location ID of a given device /// @@ -119,7 +118,6 @@ public: static Keyboard::Key nonLocalizedKeys(UniChar virtualKeycode); private: - //////////////////////////////////////////////////////////// /// \brief Default constructor /// @@ -219,16 +217,15 @@ private: static UInt8 usageToVirtualCode(UInt32 usage); private: - //////////////////////////////////////////////////////////// // Member data //////////////////////////////////////////////////////////// - bool m_isValid; ///< If any error occurs this variable is false - CFDataRef m_layoutData; ///< CFData containing the layout - UCKeyboardLayout* m_layout; ///< Current Keyboard Layout - IOHIDManagerRef m_manager; ///< HID Manager + bool m_isValid; ///< If any error occurs this variable is false + CFDataRef m_layoutData; ///< CFData containing the layout + UCKeyboardLayout* m_layout; ///< Current Keyboard Layout + IOHIDManagerRef m_manager; ///< HID Manager - IOHIDElements m_keys[Keyboard::KeyCount]; ///< All the keys on any connected keyboard + IOHIDElements m_keys[Keyboard::KeyCount]; ///< All the keys on any connected keyboard //////////////////////////////////////////////////////////// /// m_keys' index corresponds to sf::Keyboard::Key enum. diff --git a/src/SFML/Window/OSX/HIDInputManager.mm b/src/SFML/Window/OSX/HIDInputManager.mm index c4cad28dc..b850369d6 100644 --- a/src/SFML/Window/OSX/HIDInputManager.mm +++ b/src/SFML/Window/OSX/HIDInputManager.mm @@ -26,8 +26,9 @@ //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// -#include #include +#include + #include #include @@ -56,8 +57,7 @@ long HIDInputManager::getLocationID(IOHIDDeviceRef device) long loc = 0; // Get a unique ID: its USB location ID - CFTypeRef typeRef = IOHIDDeviceGetProperty(device, - CFSTR(kIOHIDLocationIDKey)); + CFTypeRef typeRef = IOHIDDeviceGetProperty(device, CFSTR(kIOHIDLocationIDKey)); if (!typeRef || (CFGetTypeID(typeRef) != CFNumberGetTypeID())) return 0; @@ -74,7 +74,8 @@ long HIDInputManager::getLocationID(IOHIDDeviceRef device) CFDictionaryRef HIDInputManager::copyDevicesMask(UInt32 page, UInt32 usage) { // Create the dictionary. - CFMutableDictionaryRef dict = CFDictionaryCreateMutable(kCFAllocatorDefault, 2, + CFMutableDictionaryRef dict = CFDictionaryCreateMutable(kCFAllocatorDefault, + 2, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); @@ -93,15 +94,11 @@ CFDictionaryRef HIDInputManager::copyDevicesMask(UInt32 page, UInt32 usage) //////////////////////////////////////////////////////////// -HIDInputManager::HIDInputManager() : -m_isValid(true), -m_layoutData(0), -m_layout(0), -m_manager(0) +HIDInputManager::HIDInputManager() : m_isValid(true), m_layoutData(0), m_layout(0), m_manager(0) { // Get the current keyboard layout TISInputSourceRef tis = TISCopyCurrentKeyboardLayoutInputSource(); - m_layoutData = static_cast(TISGetInputSourceProperty(tis, kTISPropertyUnicodeKeyLayoutData)); + m_layoutData = static_cast(TISGetInputSourceProperty(tis, kTISPropertyUnicodeKeyLayoutData)); if (m_layoutData == 0) { @@ -180,9 +177,7 @@ void HIDInputManager::initializeKeyboard() //////////////////////////////////////////////////////////// void HIDInputManager::loadKeyboard(IOHIDDeviceRef keyboard) { - CFArrayRef keys = IOHIDDeviceCopyMatchingElements(keyboard, - nullptr, - kIOHIDOptionsTypeNone); + CFArrayRef keys = IOHIDDeviceCopyMatchingElements(keyboard, nullptr, kIOHIDOptionsTypeNone); if (keys == nullptr) { sf::err() << "We got a keyboard without any keys (1)" << std::endl; @@ -229,24 +224,24 @@ void HIDInputManager::loadKey(IOHIDElementRef key) // Now translate the virtual code to Unicode according to // the current keyboard layout - UInt32 deadKeyState = 0; + UInt32 deadKeyState = 0; // Unicode string length is usually less or equal to 4 - UniCharCount maxStringLength = 4; - UniCharCount actualStringLength = 0; + UniCharCount maxStringLength = 4; + UniCharCount actualStringLength = 0; std::vector unicodeString(maxStringLength); - OSStatus error; + OSStatus error; - error = UCKeyTranslate(m_layout, // current layout - virtualCode, // our key - kUCKeyActionDown, // or kUCKeyActionUp ? - 0x100, // no modifiers - LMGetKbdType(), // keyboard's type - kUCKeyTranslateNoDeadKeysBit,// some sort of option - &deadKeyState, // unused stuff - maxStringLength, // our memory limit - &actualStringLength, // length of what we get - unicodeString.data()); // what we get + error = UCKeyTranslate(m_layout, // current layout + virtualCode, // our key + kUCKeyActionDown, // or kUCKeyActionUp ? + 0x100, // no modifiers + LMGetKbdType(), // keyboard's type + kUCKeyTranslateNoDeadKeysBit, // some sort of option + &deadKeyState, // unused stuff + maxStringLength, // our memory limit + &actualStringLength, // length of what we get + unicodeString.data()); // what we get if (error == noErr) { @@ -300,9 +295,7 @@ void HIDInputManager::loadKey(IOHIDElementRef key) } /* if (error == noErr) */ else { - sf::err() << "Cannot translate the virtual key code, error: " - << error - << std::endl; + sf::err() << "Cannot translate the virtual key code, error: " << error << std::endl; } } @@ -876,4 +869,3 @@ Keyboard::Key HIDInputManager::nonLocalizedKeys(UniChar virtualKeycode) } // namespace priv } // namespace sf - diff --git a/src/SFML/Window/OSX/HIDJoystickManager.cpp b/src/SFML/Window/OSX/HIDJoystickManager.cpp index f97b6eb76..26a4b2221 100644 --- a/src/SFML/Window/OSX/HIDJoystickManager.cpp +++ b/src/SFML/Window/OSX/HIDJoystickManager.cpp @@ -34,10 +34,10 @@ //////////////////////////////////////////////////////////// namespace { - // Using a custom run loop mode solve some issues that appears when SFML - // is used with Cocoa. - const CFStringRef RunLoopMode = CFSTR("SFML_RUN_LOOP_MODE"); -} +// Using a custom run loop mode solve some issues that appears when SFML +// is used with Cocoa. +const CFStringRef RunLoopMode = CFSTR("SFML_RUN_LOOP_MODE"); +} // namespace namespace sf @@ -69,17 +69,13 @@ CFSetRef HIDJoystickManager::copyJoysticks() //////////////////////////////////////////////////////////// -HIDJoystickManager::HIDJoystickManager() : -m_manager(0), -m_joystickCount(0) +HIDJoystickManager::HIDJoystickManager() : m_manager(0), m_joystickCount(0) { m_manager = IOHIDManagerCreate(kCFAllocatorDefault, kIOHIDOptionsTypeNone); - CFDictionaryRef mask0 = HIDInputManager::copyDevicesMask(kHIDPage_GenericDesktop, - kHIDUsage_GD_Joystick); + CFDictionaryRef mask0 = HIDInputManager::copyDevicesMask(kHIDPage_GenericDesktop, kHIDUsage_GD_Joystick); - CFDictionaryRef mask1 = HIDInputManager::copyDevicesMask(kHIDPage_GenericDesktop, - kHIDUsage_GD_GamePad); + CFDictionaryRef mask1 = HIDInputManager::copyDevicesMask(kHIDPage_GenericDesktop, kHIDUsage_GD_GamePad); CFDictionaryRef maskArray[2]; maskArray[0] = mask0; @@ -96,9 +92,7 @@ m_joystickCount(0) IOHIDManagerRegisterDeviceMatchingCallback(m_manager, pluggedIn, this); IOHIDManagerRegisterDeviceRemovalCallback(m_manager, pluggedOut, this); - IOHIDManagerScheduleWithRunLoop(m_manager, - CFRunLoopGetCurrent(), - RunLoopMode); + IOHIDManagerScheduleWithRunLoop(m_manager, CFRunLoopGetCurrent(), RunLoopMode); IOHIDManagerOpen(m_manager, kIOHIDOptionsTypeNone); } @@ -107,9 +101,7 @@ m_joystickCount(0) //////////////////////////////////////////////////////////// HIDJoystickManager::~HIDJoystickManager() { - IOHIDManagerUnscheduleFromRunLoop(m_manager, - CFRunLoopGetCurrent(), - RunLoopMode); + IOHIDManagerUnscheduleFromRunLoop(m_manager, CFRunLoopGetCurrent(), RunLoopMode); IOHIDManagerRegisterDeviceMatchingCallback(m_manager, nullptr, 0); IOHIDManagerRegisterDeviceRemovalCallback(m_manager, nullptr, 0); @@ -149,4 +141,3 @@ void HIDJoystickManager::pluggedOut(void* context, IOReturn, void*, IOHIDDeviceR } // namespace priv } // namespace sf - diff --git a/src/SFML/Window/OSX/HIDJoystickManager.hpp b/src/SFML/Window/OSX/HIDJoystickManager.hpp index ccf5eb04f..1a9f2c688 100644 --- a/src/SFML/Window/OSX/HIDJoystickManager.hpp +++ b/src/SFML/Window/OSX/HIDJoystickManager.hpp @@ -46,7 +46,6 @@ namespace priv class HIDJoystickManager { public: - //////////////////////////////////////////////////////////// /// \brief Get the unique instance of the class /// @@ -58,7 +57,6 @@ public: static HIDJoystickManager& getInstance(); public: - //////////////////////////////////////////////////////////// /// \brief Get the number of currently connected joystick /// @@ -74,7 +72,6 @@ public: CFSetRef copyJoysticks(); private: - //////////////////////////////////////////////////////////// /// \brief Default constructor /// @@ -106,7 +103,6 @@ private: void update(); private: - //////////////////////////////////////////////////////////// /// \brief Private "plug-in" callback /// \note Only 'context' parameter is used. @@ -124,12 +120,11 @@ private: static void pluggedOut(void* context, IOReturn, void*, IOHIDDeviceRef); private: - //////////////////////////////////////////////////////////// // Member data //////////////////////////////////////////////////////////// - IOHIDManagerRef m_manager; ///< HID Manager - unsigned int m_joystickCount;///< Number of joysticks currently connected + IOHIDManagerRef m_manager; ///< HID Manager + unsigned int m_joystickCount; ///< Number of joysticks currently connected }; diff --git a/src/SFML/Window/OSX/InputImpl.hpp b/src/SFML/Window/OSX/InputImpl.hpp index ff2e696b6..a798d8fc6 100644 --- a/src/SFML/Window/OSX/InputImpl.hpp +++ b/src/SFML/Window/OSX/InputImpl.hpp @@ -44,7 +44,6 @@ namespace priv class InputImpl { public: - //////////////////////////////////////////////////////////// /// \brief Check if a key is pressed /// diff --git a/src/SFML/Window/OSX/InputImpl.mm b/src/SFML/Window/OSX/InputImpl.mm index 07148ee0c..f1fa437bc 100644 --- a/src/SFML/Window/OSX/InputImpl.mm +++ b/src/SFML/Window/OSX/InputImpl.mm @@ -26,16 +26,16 @@ //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// +#include +#include +#include +#include +#import #include #include -#include -#include -#include -#include -#include -#import #import +#include //////////////////////////////////////////////////////////// /// In order to keep track of the keyboard's state and mouse buttons' state @@ -72,7 +72,7 @@ SFOpenGLView* getSFOpenGLViewFromSFMLWindow(const WindowBase& window) // Subview doesn't match ? if (![view isKindOfClass:[SFOpenGLView class]]) { - if([view isKindOfClass:[NSView class]]) + if ([view isKindOfClass:[NSView class]]) { NSArray* subviews = [view subviews]; for (NSView* subview in subviews) @@ -83,17 +83,14 @@ SFOpenGLView* getSFOpenGLViewFromSFMLWindow(const WindowBase& window) break; } } - } else { - sf::err() << "The content view is not a valid SFOpenGLView" - << std::endl; + sf::err() << "The content view is not a valid SFOpenGLView" << std::endl; view = nil; } } - } else if ([nsHandle isKindOfClass:[NSView class]]) { @@ -116,8 +113,7 @@ SFOpenGLView* getSFOpenGLViewFromSFMLWindow(const WindowBase& window) { if (nsHandle != 0) sf::err() << "The system handle is neither a nor " - << "object. This shouldn't happen." - << std::endl; + << "object. This shouldn't happen." << std::endl; // Else: this probably means the SFML window was previously closed. } @@ -143,8 +139,8 @@ void InputImpl::setVirtualKeyboardVisible(bool /*visible*/) bool InputImpl::isMouseButtonPressed(Mouse::Button button) { AutoreleasePool pool; - NSUInteger state = [NSEvent pressedMouseButtons]; - NSUInteger flag = 1 << button; + NSUInteger state = [NSEvent pressedMouseButtons]; + NSUInteger flag = 1 << button; return (state & flag) != 0; } @@ -155,7 +151,7 @@ Vector2i InputImpl::getMousePosition() AutoreleasePool pool; // Reverse Y axis to match SFML coord. NSPoint pos = [NSEvent mouseLocation]; - pos.y = sf::VideoMode::getDesktopMode().size.y - pos.y; + pos.y = sf::VideoMode::getDesktopMode().size.y - pos.y; int scale = static_cast([[NSScreen mainScreen] backingScaleFactor]); return Vector2i(static_cast(pos.x), static_cast(pos.y)) * scale; @@ -166,7 +162,7 @@ Vector2i InputImpl::getMousePosition() Vector2i InputImpl::getMousePosition(const WindowBase& relativeTo) { AutoreleasePool pool; - SFOpenGLView* view = getSFOpenGLViewFromSFMLWindow(relativeTo); + SFOpenGLView* view = getSFOpenGLViewFromSFMLWindow(relativeTo); // No view ? if (view == nil) @@ -185,8 +181,8 @@ void InputImpl::setMousePosition(const Vector2i& position) { AutoreleasePool pool; // Here we don't need to reverse the coordinates. - int scale = static_cast([[NSScreen mainScreen] backingScaleFactor]); - CGPoint pos = CGPointMake(position.x / scale, position.y / scale); + int scale = static_cast([[NSScreen mainScreen] backingScaleFactor]); + CGPoint pos = CGPointMake(position.x / scale, position.y / scale); // Place the cursor. CGEventRef event = CGEventCreateMouseEvent(nullptr, @@ -203,16 +199,16 @@ void InputImpl::setMousePosition(const Vector2i& position) void InputImpl::setMousePosition(const Vector2i& position, const WindowBase& relativeTo) { AutoreleasePool pool; - SFOpenGLView* view = getSFOpenGLViewFromSFMLWindow(relativeTo); + SFOpenGLView* view = getSFOpenGLViewFromSFMLWindow(relativeTo); // No view ? if (view == nil) return; // Let SFOpenGLView compute the position in global coordinate - int scale = static_cast([view displayScaleFactor]); - NSPoint p = NSMakePoint(position.x / scale, position.y / scale); - p = [view computeGlobalPositionOfRelativePoint:p]; + int scale = static_cast([view displayScaleFactor]); + NSPoint p = NSMakePoint(position.x / scale, position.y / scale); + p = [view computeGlobalPositionOfRelativePoint:p]; setMousePosition(sf::Vector2i(static_cast(p.x), static_cast(p.y)) * scale); } diff --git a/src/SFML/Window/OSX/JoystickImpl.cpp b/src/SFML/Window/OSX/JoystickImpl.cpp index 14410c7da..4d7736cb3 100644 --- a/src/SFML/Window/OSX/JoystickImpl.cpp +++ b/src/SFML/Window/OSX/JoystickImpl.cpp @@ -26,69 +26,72 @@ //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// +#include #include #include #include #include -#include + #include namespace { - bool JoystickButtonSortPredicate(IOHIDElementRef b1, IOHIDElementRef b2) - { - return IOHIDElementGetUsage(b1) < IOHIDElementGetUsage(b2); - } - - // Convert a CFStringRef to std::string - std::string stringFromCFString(CFStringRef cfString) - { - CFIndex length = CFStringGetLength(cfString); - std::vector str(static_cast(length)); - CFIndex maxSize = CFStringGetMaximumSizeForEncoding(length, kCFStringEncodingUTF8); - CFStringGetCString(cfString, str.data(), maxSize, kCFStringEncodingUTF8); - return str.data(); - } - - // Get HID device property key as a string - std::string getDeviceString(IOHIDDeviceRef ref, CFStringRef prop, unsigned int index) - { - CFTypeRef typeRef = IOHIDDeviceGetProperty(ref, prop); - if (typeRef && (CFGetTypeID(typeRef) == CFStringGetTypeID())) - { - CFStringRef str = static_cast(typeRef); - return stringFromCFString(str); - } - - sf::err() << "Unable to read string value for property '" << stringFromCFString(prop) << "' for joystick at index " << index << std::endl; - return "Unknown Joystick"; - } - - - // Get HID device property key as an unsigned int - unsigned int getDeviceUint(IOHIDDeviceRef ref, CFStringRef prop, unsigned int index) - { - CFTypeRef typeRef = IOHIDDeviceGetProperty(ref, prop); - if (typeRef && (CFGetTypeID(typeRef) == CFNumberGetTypeID())) - { - SInt32 value; - CFNumberGetValue(static_cast(typeRef), kCFNumberSInt32Type, &value); - return static_cast(value); - } - - sf::err() << "Unable to read uint value for property '" << stringFromCFString(prop) << "' for joystick at index " << index << std::endl; - return 0; - } +bool JoystickButtonSortPredicate(IOHIDElementRef b1, IOHIDElementRef b2) +{ + return IOHIDElementGetUsage(b1) < IOHIDElementGetUsage(b2); } +// Convert a CFStringRef to std::string +std::string stringFromCFString(CFStringRef cfString) +{ + CFIndex length = CFStringGetLength(cfString); + std::vector str(static_cast(length)); + CFIndex maxSize = CFStringGetMaximumSizeForEncoding(length, kCFStringEncodingUTF8); + CFStringGetCString(cfString, str.data(), maxSize, kCFStringEncodingUTF8); + return str.data(); +} + +// Get HID device property key as a string +std::string getDeviceString(IOHIDDeviceRef ref, CFStringRef prop, unsigned int index) +{ + CFTypeRef typeRef = IOHIDDeviceGetProperty(ref, prop); + if (typeRef && (CFGetTypeID(typeRef) == CFStringGetTypeID())) + { + CFStringRef str = static_cast(typeRef); + return stringFromCFString(str); + } + + sf::err() << "Unable to read string value for property '" << stringFromCFString(prop) << "' for joystick at index " + << index << std::endl; + return "Unknown Joystick"; +} + + +// Get HID device property key as an unsigned int +unsigned int getDeviceUint(IOHIDDeviceRef ref, CFStringRef prop, unsigned int index) +{ + CFTypeRef typeRef = IOHIDDeviceGetProperty(ref, prop); + if (typeRef && (CFGetTypeID(typeRef) == CFNumberGetTypeID())) + { + SInt32 value; + CFNumberGetValue(static_cast(typeRef), kCFNumberSInt32Type, &value); + return static_cast(value); + } + + sf::err() << "Unable to read uint value for property '" << stringFromCFString(prop) << "' for joystick at index " + << index << std::endl; + return 0; +} +} // namespace + namespace sf { namespace priv { //////////////////////////////////////////////////////////// -JoystickImpl::Location JoystickImpl::m_locationIDs[sf::Joystick::Count] = { 0 }; +JoystickImpl::Location JoystickImpl::m_locationIDs[sf::Joystick::Count] = {0}; //////////////////////////////////////////////////////////// @@ -109,7 +112,7 @@ void JoystickImpl::cleanup() bool JoystickImpl::isConnected(unsigned int index) { AutoreleasePool pool; - bool state = false; // Is the index-th joystick connected? + bool state = false; // Is the index-th joystick connected? // First, let's check if the device was previously detected: if (m_locationIDs[index] != 0) @@ -152,7 +155,8 @@ bool JoystickImpl::isConnected(unsigned int index) for (CFIndex didx(0); !state && didx < size; ++didx) { - IOHIDDeviceRef d = static_cast(const_cast(array[static_cast(didx)])); + IOHIDDeviceRef d = static_cast( + const_cast(array[static_cast(didx)])); Location dloc = HIDInputManager::getLocationID(d); bool foundJ = false; @@ -162,11 +166,12 @@ bool JoystickImpl::isConnected(unsigned int index) foundJ = true; } - if (!foundJ) { + if (!foundJ) + { // This is a new device // We set it up for Open(..) m_locationIDs[index] = dloc; - state = true; + state = true; } } } @@ -184,8 +189,8 @@ bool JoystickImpl::isConnected(unsigned int index) bool JoystickImpl::open(unsigned int index) { AutoreleasePool pool; - m_index = index; - m_hat = nullptr; + m_index = index; + m_hat = nullptr; Location deviceLoc = m_locationIDs[index]; // The device we need to load // Get all devices @@ -194,7 +199,7 @@ bool JoystickImpl::open(unsigned int index) return false; // Get a usable copy of the joysticks devices. - CFIndex joysticksCount = CFSetGetCount(devices); + CFIndex joysticksCount = CFSetGetCount(devices); std::vector devicesArray(static_cast(joysticksCount)); CFSetGetValues(devices, devicesArray.data()); @@ -236,12 +241,24 @@ bool JoystickImpl::open(unsigned int index) case kHIDPage_GenericDesktop: switch (IOHIDElementGetUsage(element)) { - case kHIDUsage_GD_X: m_axis[Joystick::X] = element; break; - case kHIDUsage_GD_Y: m_axis[Joystick::Y] = element; break; - case kHIDUsage_GD_Z: m_axis[Joystick::Z] = element; break; - case kHIDUsage_GD_Rx: m_axis[Joystick::U] = element; break; - case kHIDUsage_GD_Ry: m_axis[Joystick::V] = element; break; - case kHIDUsage_GD_Rz: m_axis[Joystick::R] = element; break; + case kHIDUsage_GD_X: + m_axis[Joystick::X] = element; + break; + case kHIDUsage_GD_Y: + m_axis[Joystick::Y] = element; + break; + case kHIDUsage_GD_Z: + m_axis[Joystick::Z] = element; + break; + case kHIDUsage_GD_Rx: + m_axis[Joystick::U] = element; + break; + case kHIDUsage_GD_Ry: + m_axis[Joystick::V] = element; + break; + case kHIDUsage_GD_Rz: + m_axis[Joystick::R] = element; + break; case kHIDUsage_GD_Hatswitch: // From §4.3 MiscellaneousControls of HUT v1.12: @@ -260,11 +277,9 @@ bool JoystickImpl::open(unsigned int index) if (min != 0 || max != 7) { - sf::err() << std::hex - << "Joystick (vendor/product id: 0x" << m_identification.vendorId + sf::err() << std::hex << "Joystick (vendor/product id: 0x" << m_identification.vendorId << "/0x" << m_identification.productId << std::dec - << ") range is an unexpected one: [" << min << ", " << max << "]" - << std::endl; + << ") range is an unexpected one: [" << min << ", " << max << "]" << std::endl; } else { @@ -287,7 +302,8 @@ bool JoystickImpl::open(unsigned int index) default: #ifdef SFML_DEBUG - sf::err() << "Unexpected usage for element of Page Generic Desktop: 0x" << std::hex << IOHIDElementGetUsage(element) << std::dec << std::endl; + sf::err() << "Unexpected usage for element of Page Generic Desktop: 0x" << std::hex + << IOHIDElementGetUsage(element) << std::dec << std::endl; #endif break; } @@ -295,11 +311,12 @@ bool JoystickImpl::open(unsigned int index) case kHIDPage_Button: if (m_buttons.size() < Joystick::ButtonCount) // If we have free slot... - m_buttons.push_back(element); // ...we add this element to the list + m_buttons.push_back(element); // ...we add this element to the list // Else: too many buttons. We ignore this one. break; - default: /* No other page is expected because of the mask applied by the HID manager. */ break; + default: /* No other page is expected because of the mask applied by the HID manager. */ + break; } } @@ -357,7 +374,7 @@ void JoystickImpl::close() JoystickCaps JoystickImpl::getCapabilities() const { AutoreleasePool pool; - JoystickCaps caps; + JoystickCaps caps; // Buttons: caps.buttonCount = static_cast(m_buttons.size()); @@ -384,9 +401,9 @@ Joystick::Identification JoystickImpl::getIdentification() const //////////////////////////////////////////////////////////// JoystickState JoystickImpl::update() { - AutoreleasePool pool; + AutoreleasePool pool; static constexpr JoystickState disconnectedState; // return this if joystick was disconnected - JoystickState state; // otherwise return that + JoystickState state; // otherwise return that state.connected = true; // Note: free up is done in close() which is called, if required, @@ -401,7 +418,7 @@ JoystickState JoystickImpl::update() return disconnectedState; // Get a usable copy of the joysticks devices. - CFIndex joysticksCount = CFSetGetCount(devices); + CFIndex joysticksCount = CFSetGetCount(devices); std::vector devicesArray(static_cast(joysticksCount)); CFSetGetValues(devices, devicesArray.data()); @@ -460,12 +477,13 @@ JoystickState JoystickImpl::update() // This method might not be very accurate (the "0 position" can be // slightly shift with some device) but we don't care because most // of devices are so sensitive that this is not relevant. - double physicalMax = static_cast(IOHIDElementGetPhysicalMax(iohidElementRef)); - double physicalMin = static_cast(IOHIDElementGetPhysicalMin(iohidElementRef)); - double scaledMin = -100; - double scaledMax = 100; - double physicalValue = IOHIDValueGetScaledValue(value, kIOHIDValueScaleTypePhysical); - float scaledValue = static_cast((((physicalValue - physicalMin) * (scaledMax - scaledMin)) / (physicalMax - physicalMin)) + scaledMin); + double physicalMax = static_cast(IOHIDElementGetPhysicalMax(iohidElementRef)); + double physicalMin = static_cast(IOHIDElementGetPhysicalMin(iohidElementRef)); + double scaledMin = -100; + double scaledMax = 100; + double physicalValue = IOHIDValueGetScaledValue(value, kIOHIDValueScaleTypePhysical); + float scaledValue = static_cast( + (((physicalValue - physicalMin) * (scaledMax - scaledMin)) / (physicalMax - physicalMin)) + scaledMin); state.axes[axis] = scaledValue; } @@ -494,18 +512,18 @@ JoystickState JoystickImpl::update() case 1: case 2: case 3: - state.axes[Joystick::PovX] = +100; - break; + state.axes[Joystick::PovX] = +100; + break; - case 5: - case 6: - case 7: - state.axes[Joystick::PovX] = -100; - break; + case 5: + case 6: + case 7: + state.axes[Joystick::PovX] = -100; + break; default: - state.axes[Joystick::PovX] = 0; - break; + state.axes[Joystick::PovX] = 0; + break; } // Load PovY @@ -514,18 +532,18 @@ JoystickState JoystickImpl::update() case 0: case 1: case 7: - state.axes[Joystick::PovY] = +100; - break; + state.axes[Joystick::PovY] = +100; + break; - case 3: - case 4: - case 5: - state.axes[Joystick::PovY] = -100; - break; + case 3: + case 4: + case 5: + state.axes[Joystick::PovY] = -100; + break; default: - state.axes[Joystick::PovY] = 0; - break; + state.axes[Joystick::PovY] = 0; + break; } } @@ -535,4 +553,3 @@ JoystickState JoystickImpl::update() } // namespace priv } // namespace sf - diff --git a/src/SFML/Window/OSX/JoystickImpl.hpp b/src/SFML/Window/OSX/JoystickImpl.hpp index deb45a2b9..bd9d7b00e 100644 --- a/src/SFML/Window/OSX/JoystickImpl.hpp +++ b/src/SFML/Window/OSX/JoystickImpl.hpp @@ -30,6 +30,7 @@ // Headers //////////////////////////////////////////////////////////// #include + #include #include #include @@ -47,7 +48,6 @@ namespace priv class JoystickImpl { public: - //////////////////////////////////////////////////////////// /// \brief Perform the global initialization of the joystick module /// @@ -111,12 +111,11 @@ public: [[nodiscard]] JoystickState update(); private: - //////////////////////////////////////////////////////////// // Member data //////////////////////////////////////////////////////////// - using Location = long; - using AxisMap = std::unordered_map; + using Location = long; + using AxisMap = std::unordered_map; using ButtonsVector = std::vector; AxisMap m_axis; ///< Axes (but not POV/Hat) of the joystick diff --git a/src/SFML/Window/OSX/NSImage+raw.h b/src/SFML/Window/OSX/NSImage+raw.h index ceb37e4f2..0636a938e 100644 --- a/src/SFML/Window/OSX/NSImage+raw.h +++ b/src/SFML/Window/OSX/NSImage+raw.h @@ -47,6 +47,6 @@ /// \return an instance of NSImage that needs to be released by the caller /// //////////////////////////////////////////////////////////// -+(NSImage*)imageWithRawData:(const sf::Uint8*)pixels andSize:(NSSize)size; ++ (NSImage*)imageWithRawData:(const sf::Uint8*)pixels andSize:(NSSize)size; @end diff --git a/src/SFML/Window/OSX/NSImage+raw.mm b/src/SFML/Window/OSX/NSImage+raw.mm index 33376b104..38f5c60ef 100644 --- a/src/SFML/Window/OSX/NSImage+raw.mm +++ b/src/SFML/Window/OSX/NSImage+raw.mm @@ -30,28 +30,27 @@ @implementation NSImage (raw) -+(NSImage*)imageWithRawData:(const sf::Uint8*)pixels andSize:(NSSize)size ++ (NSImage*)imageWithRawData:(const sf::Uint8*)pixels andSize:(NSSize)size { // Create an empty image representation. - NSBitmapImageRep* bitmap = - [[NSBitmapImageRep alloc] initWithBitmapDataPlanes:0 // if 0: only allocate memory - pixelsWide:(static_cast(size.width)) - pixelsHigh:(static_cast(size.height)) - bitsPerSample:8 // The number of bits used to specify - // one pixel in a single component of the data. - samplesPerPixel:4 // 3 if no alpha, 4 with it - hasAlpha:YES - isPlanar:NO // I don't know what it is but it works - colorSpaceName:NSCalibratedRGBColorSpace - bytesPerRow:0 // 0 == determine automatically - bitsPerPixel:0]; // 0 == determine automatically + NSBitmapImageRep* bitmap = [[NSBitmapImageRep alloc] + initWithBitmapDataPlanes:0 // if 0: only allocate memory + pixelsWide:(static_cast(size.width))pixelsHigh + :(static_cast(size.height))bitsPerSample:8 // The number of bits used to specify + // one pixel in a single component of the data. + samplesPerPixel:4 // 3 if no alpha, 4 with it + hasAlpha:YES + isPlanar:NO // I don't know what it is but it works + colorSpaceName:NSCalibratedRGBColorSpace + bytesPerRow:0 // 0 == determine automatically + bitsPerPixel:0]; // 0 == determine automatically // Load data pixels. for (unsigned int y = 0; y < size.height; ++y) { for (unsigned int x = 0; x < size.width; ++x, pixels += 4) { - NSUInteger pixel[4] = { pixels[0], pixels[1], pixels[2], pixels[3] }; + NSUInteger pixel[4] = {pixels[0], pixels[1], pixels[2], pixels[3]}; [bitmap setPixel:pixel atX:x y:y]; } } diff --git a/src/SFML/Window/OSX/SFApplication.h b/src/SFML/Window/OSX/SFApplication.h index 12bf1d830..18fb1ce82 100644 --- a/src/SFML/Window/OSX/SFApplication.h +++ b/src/SFML/Window/OSX/SFApplication.h @@ -40,14 +40,14 @@ /// \brief Event processing /// //////////////////////////////////////////////////////////// -+(void)processEvent; ++ (void)processEvent; //////////////////////////////////////////////////////////// /// \brief Set up the menu bar and its items /// //////////////////////////////////////////////////////////// -+(void)setUpMenuBar; ++ (void)setUpMenuBar; //////////////////////////////////////////////////////////// @@ -57,7 +57,7 @@ /// fix KeyRelease events when the command key is down. /// //////////////////////////////////////////////////////////// --(void)sendEvent:(NSEvent*)anEvent; +- (void)sendEvent:(NSEvent*)anEvent; @end diff --git a/src/SFML/Window/OSX/SFApplicationDelegate.h b/src/SFML/Window/OSX/SFApplicationDelegate.h index 7712c57e3..5f00e2f5f 100644 --- a/src/SFML/Window/OSX/SFApplicationDelegate.h +++ b/src/SFML/Window/OSX/SFApplicationDelegate.h @@ -34,7 +34,7 @@ /// \brief Process some application specific events /// //////////////////////////////////////////////////////////// -@interface SFApplicationDelegate : NSObject +@interface SFApplicationDelegate : NSObject //////////////////////////////////////////////////////////// /// \brief React to a termination notification @@ -42,12 +42,12 @@ /// Send a close message to all windows and cancel the termination. /// //////////////////////////////////////////////////////////// --(NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication*)sender; +- (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication*)sender; //////////////////////////////////////////////////////////// /// \brief Exit the app when all windows are closed /// //////////////////////////////////////////////////////////// --(BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication*)theApplication; +- (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication*)theApplication; @end diff --git a/src/SFML/Window/OSX/SFContext.hpp b/src/SFML/Window/OSX/SFContext.hpp index 6e70a41ec..c9b20b139 100644 --- a/src/SFML/Window/OSX/SFContext.hpp +++ b/src/SFML/Window/OSX/SFContext.hpp @@ -48,8 +48,8 @@ using NSWindowRef = NSWindow*; #else // If C++ using NSOpenGLContextRef = void*; -using NSOpenGLViewRef = void*; -using NSWindowRef = void*; +using NSOpenGLViewRef = void*; +using NSWindowRef = void*; #endif @@ -82,8 +82,7 @@ public: /// \param bitsPerPixel Pixel depth, in bits per pixel /// //////////////////////////////////////////////////////////// - SFContext(SFContext* shared, const ContextSettings& settings, - const WindowImpl& owner, unsigned int bitsPerPixel); + SFContext(SFContext* shared, const ContextSettings& settings, const WindowImpl& owner, unsigned int bitsPerPixel); //////////////////////////////////////////////////////////// /// \brief Create a new context that embeds its own rendering target @@ -93,8 +92,7 @@ public: /// \param size Back buffer width and height, in pixels /// //////////////////////////////////////////////////////////// - SFContext(SFContext* shared, const ContextSettings& settings, - const Vector2u& size); + SFContext(SFContext* shared, const ContextSettings& settings, const Vector2u& size); //////////////////////////////////////////////////////////// /// \brief Destructor @@ -153,16 +151,14 @@ private: /// \param settings Creation parameters /// //////////////////////////////////////////////////////////// - void createContext(SFContext* shared, - unsigned int bitsPerPixel, - const ContextSettings& settings); + void createContext(SFContext* shared, unsigned int bitsPerPixel, const ContextSettings& settings); //////////////////////////////////////////////////////////// // Member data //////////////////////////////////////////////////////////// - NSOpenGLContextRef m_context; ///< OpenGL context. - NSOpenGLViewRef m_view; ///< Only for offscreen context. - NSWindowRef m_window; ///< Only for offscreen context. + NSOpenGLContextRef m_context; ///< OpenGL context. + NSOpenGLViewRef m_view; ///< Only for offscreen context. + NSWindowRef m_window; ///< Only for offscreen context. }; } // namespace priv diff --git a/src/SFML/Window/OSX/SFContext.mm b/src/SFML/Window/OSX/SFContext.mm index 6a5d7c913..7eaf54850 100644 --- a/src/SFML/Window/OSX/SFContext.mm +++ b/src/SFML/Window/OSX/SFContext.mm @@ -26,20 +26,21 @@ //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// +#include #include #include #include -#include + #include -#include #include +#include #if defined(__APPLE__) - #if defined(__clang__) - #pragma clang diagnostic ignored "-Wdeprecated-declarations" - #elif defined(__GNUC__) - #pragma GCC diagnostic ignored "-Wdeprecated-declarations" - #endif +#if defined(__clang__) +#pragma clang diagnostic ignored "-Wdeprecated-declarations" +#elif defined(__GNUC__) +#pragma GCC diagnostic ignored "-Wdeprecated-declarations" +#endif #endif namespace sf @@ -49,22 +50,16 @@ namespace priv //////////////////////////////////////////////////////////// -SFContext::SFContext(SFContext* shared) : -m_context(0), -m_view(0), -m_window(0) +SFContext::SFContext(SFContext* shared) : m_context(0), m_view(0), m_window(0) { AutoreleasePool pool; // Create the context - createContext(shared, - VideoMode::getDesktopMode().bitsPerPixel, - ContextSettings(0, 0, 0)); + createContext(shared, VideoMode::getDesktopMode().bitsPerPixel, ContextSettings(0, 0, 0)); } //////////////////////////////////////////////////////////// -SFContext::SFContext(SFContext* shared, const ContextSettings& settings, - const WindowImpl& owner, unsigned int bitsPerPixel) : +SFContext::SFContext(SFContext* shared, const ContextSettings& settings, const WindowImpl& owner, unsigned int bitsPerPixel) : m_context(0), m_view(0), m_window(0) @@ -80,8 +75,7 @@ m_window(0) //////////////////////////////////////////////////////////// -SFContext::SFContext(SFContext* shared, const ContextSettings& settings, - const Vector2u& size) : +SFContext::SFContext(SFContext* shared, const ContextSettings& settings, const Vector2u& size) : m_context(0), m_view(0), m_window(0) @@ -94,11 +88,12 @@ m_window(0) createContext(shared, VideoMode::getDesktopMode().bitsPerPixel, settings); // Create a dummy window/view pair (hidden) and assign it our context. - m_window = [[NSWindow alloc] initWithContentRect:NSMakeRect(0, 0, size.x, size.y) - styleMask:NSBorderlessWindowMask - backing:NSBackingStoreBuffered - defer:NO]; // Don't defer it! - m_view = [[NSOpenGLView alloc] initWithFrame:NSMakeRect(0, 0, size.x, size.y)]; + m_window = [[NSWindow alloc] + initWithContentRect:NSMakeRect(0, 0, size.x, size.y) + styleMask:NSBorderlessWindowMask + backing:NSBackingStoreBuffered + defer:NO]; // Don't defer it! + m_view = [[NSOpenGLView alloc] initWithFrame:NSMakeRect(0, 0, size.x, size.y)]; [m_window setContentView:m_view]; [m_view setOpenGLContext:m_context]; [m_context setView:m_view]; @@ -119,7 +114,7 @@ SFContext::~SFContext() [m_context release]; - [m_view release]; // Might be nil but we don't care. + [m_view release]; // Might be nil but we don't care. [m_window release]; // Idem. } @@ -128,7 +123,7 @@ SFContext::~SFContext() GlFunctionPointer SFContext::getFunction(const char* name) { AutoreleasePool pool; - static void* image = nullptr; + static void* image = nullptr; if (!image) image = dlopen("/System/Library/Frameworks/OpenGL.framework/Versions/Current/OpenGL", RTLD_LAZY); @@ -166,16 +161,14 @@ void SFContext::display() void SFContext::setVerticalSyncEnabled(bool enabled) { AutoreleasePool pool; - GLint swapInterval = enabled ? 1 : 0; + GLint swapInterval = enabled ? 1 : 0; [m_context setValues:&swapInterval forParameter:NSOpenGLCPSwapInterval]; } //////////////////////////////////////////////////////////// -void SFContext::createContext(SFContext* shared, - unsigned int bitsPerPixel, - const ContextSettings& settings) +void SFContext::createContext(SFContext* shared, unsigned int bitsPerPixel, const ContextSettings& settings) { AutoreleasePool pool; // Save the settings. (OpenGL version is updated elsewhere.) @@ -295,14 +288,12 @@ void SFContext::createContext(SFContext* shared, } // Create the context. - m_context = [[NSOpenGLContext alloc] initWithFormat:pixFmt - shareContext:sharedContext]; + m_context = [[NSOpenGLContext alloc] initWithFormat:pixFmt shareContext:sharedContext]; if (m_context == nil) { sf::err() << "Error. Unable to create the context. Retrying without shared context." << std::endl; - m_context = [[NSOpenGLContext alloc] initWithFormat:pixFmt - shareContext:nil]; + m_context = [[NSOpenGLContext alloc] initWithFormat:pixFmt shareContext:nil]; if (m_context == nil) sf::err() << "Error. Unable to create the context." << std::endl; @@ -312,10 +303,8 @@ void SFContext::createContext(SFContext* shared, // Free up. [pixFmt release]; - } } // namespace priv } // namespace sf - diff --git a/src/SFML/Window/OSX/SFKeyboardModifiersHelper.h b/src/SFML/Window/OSX/SFKeyboardModifiersHelper.h index 7074e55dc..053fbfe8a 100644 --- a/src/SFML/Window/OSX/SFKeyboardModifiersHelper.h +++ b/src/SFML/Window/OSX/SFKeyboardModifiersHelper.h @@ -28,10 +28,12 @@ //////////////////////////////////////////////////////////// #import -namespace sf { - namespace priv { - class WindowImplCocoa; - } +namespace sf +{ +namespace priv +{ +class WindowImplCocoa; +} } //////////////////////////////////////////////////////////// @@ -66,5 +68,3 @@ sf::Event::KeyEvent keyEventWithModifiers(NSUInteger modifiers, sf::Keyboard::Ke /// //////////////////////////////////////////////////////////// void handleModifiersChanged(NSUInteger modifiers, sf::priv::WindowImplCocoa& requester); - - diff --git a/src/SFML/Window/OSX/SFKeyboardModifiersHelper.mm b/src/SFML/Window/OSX/SFKeyboardModifiersHelper.mm index 1c9a33505..b82c86ef8 100644 --- a/src/SFML/Window/OSX/SFKeyboardModifiersHelper.mm +++ b/src/SFML/Window/OSX/SFKeyboardModifiersHelper.mm @@ -26,16 +26,15 @@ //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// +#import #include -#import - #if defined(__APPLE__) - #if defined(__clang__) - #pragma clang diagnostic ignored "-Wdeprecated-declarations" - #elif defined(__GNUC__) - #pragma GCC diagnostic ignored "-Wdeprecated-declarations" - #endif +#if defined(__clang__) +#pragma clang diagnostic ignored "-Wdeprecated-declarations" +#elif defined(__GNUC__) +#pragma GCC diagnostic ignored "-Wdeprecated-declarations" +#endif #endif @@ -44,14 +43,14 @@ /// keys (cmd, ctrl, alt, shift) /// //////////////////////////////////////////////////////////// -#define NSRightShiftKeyMask 0x020004 -#define NSLeftShiftKeyMask 0x020002 -#define NSRightCommandKeyMask 0x100010 -#define NSLeftCommandKeyMask 0x100008 -#define NSRightAlternateKeyMask 0x080040 -#define NSLeftAlternateKeyMask 0x080020 -#define NSRightControlKeyMask 0x042000 -#define NSLeftControlKeyMask 0x040001 +#define NSRightShiftKeyMask 0x020004 +#define NSLeftShiftKeyMask 0x020002 +#define NSRightCommandKeyMask 0x100010 +#define NSLeftCommandKeyMask 0x100008 +#define NSRightAlternateKeyMask 0x080040 +#define NSLeftAlternateKeyMask 0x080020 +#define NSRightControlKeyMask 0x042000 +#define NSLeftControlKeyMask 0x040001 //////////////////////////////////////////////////////////// @@ -78,7 +77,7 @@ struct ModifiersState /// Share 'modifiers' state with all windows to correctly fire pressed/released events static ModifiersState state; -static BOOL isStateInitialized = NO; +static BOOL isStateInitialized = NO; //////////////////////////////////////////////////////////// @@ -98,8 +97,10 @@ BOOL isKeyMaskActive(NSUInteger modifiers, NSUInteger mask); /// Update the key state and send events to the requester /// //////////////////////////////////////////////////////////// -void processOneModifier(NSUInteger modifiers, NSUInteger mask, - BOOL& wasDown, sf::Keyboard::Key key, +void processOneModifier(NSUInteger modifiers, + NSUInteger mask, + BOOL& wasDown, + sf::Keyboard::Key key, sf::priv::WindowImplCocoa& requester); @@ -109,12 +110,15 @@ void processOneModifier(NSUInteger modifiers, NSUInteger mask, /// Update the keys state and send events to the requester /// //////////////////////////////////////////////////////////// -void processLeftRightModifiers(NSUInteger modifiers, - NSUInteger leftMask, NSUInteger rightMask, - BOOL& leftWasDown, BOOL& rightWasDown, - sf::Keyboard::Key leftKey, sf::Keyboard::Key rightKey, - sf::priv::WindowImplCocoa& requester); - +void processLeftRightModifiers( + NSUInteger modifiers, + NSUInteger leftMask, + NSUInteger rightMask, + BOOL& leftWasDown, + BOOL& rightWasDown, + sf::Keyboard::Key leftKey, + sf::Keyboard::Key rightKey, + sf::priv::WindowImplCocoa& requester); //////////////////////////////////////////////////////////// @@ -125,19 +129,20 @@ void processLeftRightModifiers(NSUInteger modifiers, //////////////////////////////////////////////////////// void initialiseKeyboardHelper() { - if (isStateInitialized) return; + if (isStateInitialized) + return; NSUInteger modifiers = [[NSApp currentEvent] modifierFlags]; // Load current keyboard state - state.leftShiftWasDown = isKeyMaskActive(modifiers, NSLeftShiftKeyMask); - state.rightShiftWasDown = isKeyMaskActive(modifiers, NSRightShiftKeyMask); - state.leftCommandWasDown = isKeyMaskActive(modifiers, NSLeftCommandKeyMask); - state.rightCommandWasDown = isKeyMaskActive(modifiers, NSRightCommandKeyMask); - state.leftAlternateWasDown = isKeyMaskActive(modifiers, NSLeftAlternateKeyMask); - state.rightAlternateWasDown = isKeyMaskActive(modifiers, NSRightAlternateKeyMask); - state.leftControlWasDown = isKeyMaskActive(modifiers, NSLeftControlKeyMask); - state.rightControlWasDown = isKeyMaskActive(modifiers, NSRightControlKeyMask); + state.leftShiftWasDown = isKeyMaskActive(modifiers, NSLeftShiftKeyMask); + state.rightShiftWasDown = isKeyMaskActive(modifiers, NSRightShiftKeyMask); + state.leftCommandWasDown = isKeyMaskActive(modifiers, NSLeftCommandKeyMask); + state.rightCommandWasDown = isKeyMaskActive(modifiers, NSRightCommandKeyMask); + state.leftAlternateWasDown = isKeyMaskActive(modifiers, NSLeftAlternateKeyMask); + state.rightAlternateWasDown = isKeyMaskActive(modifiers, NSRightAlternateKeyMask); + state.leftControlWasDown = isKeyMaskActive(modifiers, NSLeftControlKeyMask); + state.rightControlWasDown = isKeyMaskActive(modifiers, NSRightControlKeyMask); isStateInitialized = YES; } @@ -161,40 +166,44 @@ sf::Event::KeyEvent keyEventWithModifiers(NSUInteger modifiers, sf::Keyboard::Ke void handleModifiersChanged(NSUInteger modifiers, sf::priv::WindowImplCocoa& requester) { // Handle shift - processLeftRightModifiers( - modifiers, - NSLeftShiftKeyMask, NSRightShiftKeyMask, - state.leftShiftWasDown, state.rightShiftWasDown, - sf::Keyboard::LShift, sf::Keyboard::RShift, - requester - ); + processLeftRightModifiers(modifiers, + NSLeftShiftKeyMask, + NSRightShiftKeyMask, + state.leftShiftWasDown, + state.rightShiftWasDown, + sf::Keyboard::LShift, + sf::Keyboard::RShift, + requester); // Handle command - processLeftRightModifiers( - modifiers, - NSLeftCommandKeyMask, NSRightCommandKeyMask, - state.leftCommandWasDown, state.rightCommandWasDown, - sf::Keyboard::LSystem, sf::Keyboard::RSystem, - requester - ); + processLeftRightModifiers(modifiers, + NSLeftCommandKeyMask, + NSRightCommandKeyMask, + state.leftCommandWasDown, + state.rightCommandWasDown, + sf::Keyboard::LSystem, + sf::Keyboard::RSystem, + requester); // Handle option (alt) - processLeftRightModifiers( - modifiers, - NSLeftAlternateKeyMask, NSRightAlternateKeyMask, - state.leftAlternateWasDown, state.rightAlternateWasDown, - sf::Keyboard::LAlt, sf::Keyboard::RAlt, - requester - ); + processLeftRightModifiers(modifiers, + NSLeftAlternateKeyMask, + NSRightAlternateKeyMask, + state.leftAlternateWasDown, + state.rightAlternateWasDown, + sf::Keyboard::LAlt, + sf::Keyboard::RAlt, + requester); // Handle control - processLeftRightModifiers( - modifiers, - NSLeftControlKeyMask, NSRightControlKeyMask, - state.leftControlWasDown, state.rightControlWasDown, - sf::Keyboard::LControl, sf::Keyboard::RControl, - requester - ); + processLeftRightModifiers(modifiers, + NSLeftControlKeyMask, + NSRightControlKeyMask, + state.leftControlWasDown, + state.rightControlWasDown, + sf::Keyboard::LControl, + sf::Keyboard::RControl, + requester); } @@ -209,9 +218,7 @@ BOOL isKeyMaskActive(NSUInteger modifiers, NSUInteger mask) //////////////////////////////////////////////////////// -void processOneModifier(NSUInteger modifiers, NSUInteger mask, - BOOL& wasDown, sf::Keyboard::Key key, - sf::priv::WindowImplCocoa& requester) +void processOneModifier(NSUInteger modifiers, NSUInteger mask, BOOL& wasDown, sf::Keyboard::Key key, sf::priv::WindowImplCocoa& requester) { // Setup a potential event key. sf::Event::KeyEvent event = keyEventWithModifiers(modifiers, key); @@ -235,14 +242,16 @@ void processOneModifier(NSUInteger modifiers, NSUInteger mask, //////////////////////////////////////////////////////// -void processLeftRightModifiers(NSUInteger modifiers, - NSUInteger leftMask, NSUInteger rightMask, - BOOL& leftWasDown, BOOL& rightWasDown, - sf::Keyboard::Key leftKey, sf::Keyboard::Key rightKey, - sf::priv::WindowImplCocoa& requester) +void processLeftRightModifiers( + NSUInteger modifiers, + NSUInteger leftMask, + NSUInteger rightMask, + BOOL& leftWasDown, + BOOL& rightWasDown, + sf::Keyboard::Key leftKey, + sf::Keyboard::Key rightKey, + sf::priv::WindowImplCocoa& requester) { - processOneModifier(modifiers, leftMask, leftWasDown, leftKey, requester); + processOneModifier(modifiers, leftMask, leftWasDown, leftKey, requester); processOneModifier(modifiers, rightMask, rightWasDown, rightKey, requester); } - - diff --git a/src/SFML/Window/OSX/SFOpenGLView+keyboard.mm b/src/SFML/Window/OSX/SFOpenGLView+keyboard.mm index d03f419b7..65581aa8e 100644 --- a/src/SFML/Window/OSX/SFOpenGLView+keyboard.mm +++ b/src/SFML/Window/OSX/SFOpenGLView+keyboard.mm @@ -26,19 +26,18 @@ //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// -#include #include // For localizedKeys and nonLocalizedKeys - #import -#import #import +#import +#include #if defined(__APPLE__) - #if defined(__clang__) - #pragma clang diagnostic ignored "-Wdeprecated-declarations" - #elif defined(__GNUC__) - #pragma GCC diagnostic ignored "-Wdeprecated-declarations" - #endif +#if defined(__clang__) +#pragma clang diagnostic ignored "-Wdeprecated-declarations" +#elif defined(__GNUC__) +#pragma GCC diagnostic ignored "-Wdeprecated-declarations" +#endif #endif //////////////////////////////////////////////////////////// @@ -51,7 +50,7 @@ //////////////////////////////////////////////////////// --(BOOL)acceptsFirstResponder +- (BOOL)acceptsFirstResponder { // Accepts key event. return YES; @@ -59,7 +58,7 @@ //////////////////////////////////////////////////////// --(BOOL)canBecomeKeyView +- (BOOL)canBecomeKeyView { // Accepts key event. return YES; @@ -67,21 +66,21 @@ //////////////////////////////////////////////////////// --(void)enableKeyRepeat +- (void)enableKeyRepeat { m_useKeyRepeat = YES; } //////////////////////////////////////////////////////// --(void)disableKeyRepeat +- (void)disableKeyRepeat { m_useKeyRepeat = NO; } //////////////////////////////////////////////////////// --(void)keyDown:(NSEvent*)theEvent +- (void)keyDown:(NSEvent*)theEvent { // Transmit to non-SFML responder [[self nextResponder] keyDown:theEvent]; @@ -149,7 +148,7 @@ //////////////////////////////////////////////////////// --(void)sfKeyUp:(NSEvent*)theEvent +- (void)sfKeyUp:(NSEvent*)theEvent { // For some mystic reasons, key released events don't work the same way // as key pressed events... We somewhat hijack the event chain of response @@ -172,7 +171,7 @@ //////////////////////////////////////////////////////// --(void)flagsChanged:(NSEvent*)theEvent +- (void)flagsChanged:(NSEvent*)theEvent { // Transmit to non-SFML responder [[self nextResponder] flagsChanged:theEvent]; @@ -186,7 +185,7 @@ //////////////////////////////////////////////////////// -+(sf::Event::KeyEvent)convertNSKeyEventToSFMLEvent:(NSEvent*)event ++ (sf::Event::KeyEvent)convertNSKeyEventToSFMLEvent:(NSEvent*)event { // Key code sf::Keyboard::Key key = sf::Keyboard::Unknown; @@ -207,7 +206,7 @@ //////////////////////////////////////////////////////// -+(BOOL)isValidTextUnicode:(NSEvent*)event ++ (BOOL)isValidTextUnicode:(NSEvent*)event { if ([event keyCode] == 0x35) // Escape { @@ -225,4 +224,3 @@ } @end - diff --git a/src/SFML/Window/OSX/SFOpenGLView+keyboard_priv.h b/src/SFML/Window/OSX/SFOpenGLView+keyboard_priv.h index e7ed76553..165362929 100644 --- a/src/SFML/Window/OSX/SFOpenGLView+keyboard_priv.h +++ b/src/SFML/Window/OSX/SFOpenGLView+keyboard_priv.h @@ -50,7 +50,7 @@ /// \return sf::Keyboard::Unknown as Code if the key is unknown /// //////////////////////////////////////////////////////////// -+(sf::Event::KeyEvent)convertNSKeyEventToSFMLEvent:(NSEvent*)event; ++ (sf::Event::KeyEvent)convertNSKeyEventToSFMLEvent:(NSEvent*)event; //////////////////////////////////////////////////////////// /// \brief Check if the event represent some Unicode text @@ -63,6 +63,6 @@ /// \return true if event represents a Unicode character, false otherwise /// //////////////////////////////////////////////////////////// -+(BOOL)isValidTextUnicode:(NSEvent*)event; ++ (BOOL)isValidTextUnicode:(NSEvent*)event; @end diff --git a/src/SFML/Window/OSX/SFOpenGLView+mouse.mm b/src/SFML/Window/OSX/SFOpenGLView+mouse.mm index 9580ea702..e78a781ae 100644 --- a/src/SFML/Window/OSX/SFOpenGLView+mouse.mm +++ b/src/SFML/Window/OSX/SFOpenGLView+mouse.mm @@ -26,18 +26,18 @@ //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// +#import +#import #include + #include -#import -#import - #if defined(__APPLE__) - #if defined(__clang__) - #pragma clang diagnostic ignored "-Wdeprecated-declarations" - #elif defined(__GNUC__) - #pragma GCC diagnostic ignored "-Wdeprecated-declarations" - #endif +#if defined(__clang__) +#pragma clang diagnostic ignored "-Wdeprecated-declarations" +#elif defined(__GNUC__) +#pragma GCC diagnostic ignored "-Wdeprecated-declarations" +#endif #endif @@ -49,7 +49,7 @@ @implementation SFOpenGLView (mouse) //////////////////////////////////////////////////////// --(void)setCursor:(NSCursor*)cursor +- (void)setCursor:(NSCursor*)cursor { m_cursor = cursor; @@ -59,7 +59,7 @@ //////////////////////////////////////////////////////// --(void)resetCursorRects +- (void)resetCursorRects { // addCursorRect:cursor: has to be called from within this function! [self addCursorRect:[self frame] cursor:m_cursor]; @@ -68,21 +68,21 @@ //////////////////////////////////////////////////////// --(BOOL)isMouseInside +- (BOOL)isMouseInside { NSPoint relativeToWindow = [[self window] mouseLocationOutsideOfEventStream]; - NSPoint relativeToView = [self convertPoint:relativeToWindow fromView:nil]; + NSPoint relativeToView = [self convertPoint:relativeToWindow fromView:nil]; return NSPointInRect(relativeToView, [self bounds]); } //////////////////////////////////////////////////////// --(void)updateMouseState +- (void)updateMouseState { // Update in/out state BOOL mouseWasIn = m_mouseIsIn; - m_mouseIsIn = [self isMouseInside]; + m_mouseIsIn = [self isMouseInside]; // Send event if needed. if (m_requester != 0) @@ -96,7 +96,7 @@ //////////////////////////////////////////////////////// --(void)setCursorGrabbed:(BOOL)grabbed +- (void)setCursorGrabbed:(BOOL)grabbed { m_cursorGrabbed = grabbed; @@ -105,7 +105,7 @@ //////////////////////////////////////////////////////// --(void)mouseDown:(NSEvent*)theEvent +- (void)mouseDown:(NSEvent*)theEvent { [self handleMouseDown:theEvent]; @@ -115,7 +115,7 @@ //////////////////////////////////////////////////////// --(void)rightMouseDown:(NSEvent*)theEvent +- (void)rightMouseDown:(NSEvent*)theEvent { [self handleMouseDown:theEvent]; @@ -125,7 +125,7 @@ //////////////////////////////////////////////////////// --(void)otherMouseDown:(NSEvent*)theEvent +- (void)otherMouseDown:(NSEvent*)theEvent { [self handleMouseDown:theEvent]; @@ -135,7 +135,7 @@ //////////////////////////////////////////////////////// --(void)handleMouseDown:(NSEvent*)theEvent +- (void)handleMouseDown:(NSEvent*)theEvent { sf::Mouse::Button button = [SFOpenGLView mouseButtonFromEvent:theEvent]; @@ -150,7 +150,7 @@ //////////////////////////////////////////////////////// --(void)mouseUp:(NSEvent*)theEvent +- (void)mouseUp:(NSEvent*)theEvent { [self handleMouseUp:theEvent]; @@ -160,7 +160,7 @@ //////////////////////////////////////////////////////// --(void)rightMouseUp:(NSEvent*)theEvent +- (void)rightMouseUp:(NSEvent*)theEvent { [self handleMouseUp:theEvent]; @@ -170,7 +170,7 @@ //////////////////////////////////////////////////////// --(void)otherMouseUp:(NSEvent*)theEvent +- (void)otherMouseUp:(NSEvent*)theEvent { [self handleMouseUp:theEvent]; @@ -180,7 +180,7 @@ //////////////////////////////////////////////////////////// --(void)handleMouseUp:(NSEvent*)theEvent +- (void)handleMouseUp:(NSEvent*)theEvent { sf::Mouse::Button button = [SFOpenGLView mouseButtonFromEvent:theEvent]; @@ -195,7 +195,7 @@ //////////////////////////////////////////////////////// --(void)mouseMoved:(NSEvent*)theEvent +- (void)mouseMoved:(NSEvent*)theEvent { [self handleMouseMove:theEvent]; @@ -205,7 +205,7 @@ //////////////////////////////////////////////////////// --(void)rightMouseDragged:(NSEvent*)theEvent +- (void)rightMouseDragged:(NSEvent*)theEvent { [self handleMouseMove:theEvent]; @@ -215,7 +215,7 @@ //////////////////////////////////////////////////////// --(void)mouseDragged:(NSEvent*)theEvent +- (void)mouseDragged:(NSEvent*)theEvent { [self handleMouseMove:theEvent]; @@ -225,7 +225,7 @@ //////////////////////////////////////////////////////// --(void)otherMouseDragged:(NSEvent*)theEvent +- (void)otherMouseDragged:(NSEvent*)theEvent { [self handleMouseMove:theEvent]; @@ -235,7 +235,7 @@ //////////////////////////////////////////////////////// --(void)handleMouseMove:(NSEvent*)theEvent +- (void)handleMouseMove:(NSEvent*)theEvent { NSPoint loc = [self cursorPositionFromEvent:theEvent]; @@ -255,14 +255,14 @@ //////////////////////////////////////////////////////// --(BOOL)isCursorCurrentlyGrabbed +- (BOOL)isCursorCurrentlyGrabbed { return [[self window] isKeyWindow] && m_cursorGrabbed; } //////////////////////////////////////////////////////// --(void)updateCursorGrabbed +- (void)updateCursorGrabbed { // Disable/enable normal movements of the cursor // and project the cursor if needed. @@ -282,7 +282,7 @@ //////////////////////////////////////////////////////// --(void)moveCursorTo:(NSPoint)loc +- (void)moveCursorTo:(NSPoint)loc { // Convert the point from SFML coord system to screen coord system. NSPoint screenLocation = [self computeGlobalPositionOfRelativePoint:loc]; @@ -294,21 +294,24 @@ //////////////////////////////////////////////////////// --(CGDirectDisplayID)displayId +- (CGDirectDisplayID)displayId { - NSScreen* screen = [[self window] screen]; + NSScreen* screen = [[self window] screen]; NSNumber* displayId = [[screen deviceDescription] objectForKey:@"NSScreenNumber"]; return static_cast([displayId intValue]); } //////////////////////////////////////////////////////// --(void)scrollWheel:(NSEvent*)theEvent +- (void)scrollWheel:(NSEvent*)theEvent { if (m_requester != 0) { NSPoint loc = [self cursorPositionFromEvent:theEvent]; - m_requester->mouseWheelScrolledAt(static_cast([theEvent deltaX]), static_cast([theEvent deltaY]), static_cast(loc.x), static_cast(loc.y)); + m_requester->mouseWheelScrolledAt(static_cast([theEvent deltaX]), + static_cast([theEvent deltaY]), + static_cast(loc.x), + static_cast(loc.y)); } // Transmit to non-SFML responder @@ -317,7 +320,7 @@ //////////////////////////////////////////////////////// --(void)mouseEntered:(NSEvent*)theEvent +- (void)mouseEntered:(NSEvent*)theEvent { (void)theEvent; [self updateMouseState]; @@ -325,7 +328,7 @@ //////////////////////////////////////////////////////// --(void)mouseExited:(NSEvent*)theEvent +- (void)mouseExited:(NSEvent*)theEvent { (void)theEvent; [self updateMouseState]; @@ -333,7 +336,7 @@ //////////////////////////////////////////////////////// --(NSPoint)cursorPositionFromEvent:(NSEvent*)eventOrNil +- (NSPoint)cursorPositionFromEvent:(NSEvent*)eventOrNil { NSPoint rawPos; @@ -352,10 +355,8 @@ // is dissociated from its position. // Ignore any non-move related event - if (([eventOrNil type] == NSMouseMoved) || - ([eventOrNil type] == NSLeftMouseDragged) || - ([eventOrNil type] == NSRightMouseDragged) || - ([eventOrNil type] == NSOtherMouseDragged)) + if (([eventOrNil type] == NSMouseMoved) || ([eventOrNil type] == NSLeftMouseDragged) || + ([eventOrNil type] == NSRightMouseDragged) || ([eventOrNil type] == NSOtherMouseDragged)) { // Without this factor, the cursor flies around waaay too fast! // But I don't know if it because of retina display or because @@ -389,8 +390,8 @@ NSSize size = [self frame].size; NSPoint origin = [self frame].origin; NSPoint oldPos = rawPos; - rawPos.x = std::min(std::max(origin.x, rawPos.x), origin.x + size.width - 1); - rawPos.y = std::min(std::max(origin.y + 1, rawPos.y), origin.y + size.height); + rawPos.x = std::min(std::max(origin.x, rawPos.x), origin.x + size.width - 1); + rawPos.y = std::min(std::max(origin.y + 1, rawPos.y), origin.y + size.height); // Note: the `-1` and `+1` on the two lines above prevent the user to click // on the left or below the window, repectively, and therefore prevent the // application to lose focus by accident. The sign of this offset is determinded @@ -405,23 +406,29 @@ // Don't forget to change to SFML coord system. const double h = [self frame].size.height; - loc.y = h - loc.y; + loc.y = h - loc.y; return loc; } //////////////////////////////////////////////////////// -+(sf::Mouse::Button)mouseButtonFromEvent:(NSEvent*)event ++ (sf::Mouse::Button)mouseButtonFromEvent:(NSEvent*)event { switch ([event buttonNumber]) { - case 0: return sf::Mouse::Left; - case 1: return sf::Mouse::Right; - case 2: return sf::Mouse::Middle; - case 3: return sf::Mouse::XButton1; - case 4: return sf::Mouse::XButton2; - default: return sf::Mouse::ButtonCount; // Never happens! (hopefully) + case 0: + return sf::Mouse::Left; + case 1: + return sf::Mouse::Right; + case 2: + return sf::Mouse::Middle; + case 3: + return sf::Mouse::XButton1; + case 4: + return sf::Mouse::XButton2; + default: + return sf::Mouse::ButtonCount; // Never happens! (hopefully) } } diff --git a/src/SFML/Window/OSX/SFOpenGLView+mouse_priv.h b/src/SFML/Window/OSX/SFOpenGLView+mouse_priv.h index 0aab9cacc..cf89891a9 100644 --- a/src/SFML/Window/OSX/SFOpenGLView+mouse_priv.h +++ b/src/SFML/Window/OSX/SFOpenGLView+mouse_priv.h @@ -46,25 +46,25 @@ /// Fire an event if its state has changed. /// //////////////////////////////////////////////////////////// --(void)updateMouseState; +- (void)updateMouseState; //////////////////////////////////////////////////////////// /// \brief handle mouse down event /// //////////////////////////////////////////////////////////// --(void)handleMouseDown:(NSEvent*)theEvent; +- (void)handleMouseDown:(NSEvent*)theEvent; //////////////////////////////////////////////////////////// /// \brief handle mouse up event /// //////////////////////////////////////////////////////////// --(void)handleMouseUp:(NSEvent*)theEvent; +- (void)handleMouseUp:(NSEvent*)theEvent; //////////////////////////////////////////////////////////// /// \brief handle mouse move event /// //////////////////////////////////////////////////////////// --(void)handleMouseMove:(NSEvent*)theEvent; +- (void)handleMouseMove:(NSEvent*)theEvent; //////////////////////////////////////////////////////////// /// \brief Check whether the cursor is grabbed or not @@ -73,14 +73,14 @@ /// the user wants to grab it. /// //////////////////////////////////////////////////////////// --(BOOL)isCursorCurrentlyGrabbed; +- (BOOL)isCursorCurrentlyGrabbed; //////////////////////////////////////////////////////////// /// \brief (Dis)connect the cursor's movements from/to the system /// and project the cursor into the view /// //////////////////////////////////////////////////////////// --(void)updateCursorGrabbed; +- (void)updateCursorGrabbed; //////////////////////////////////////////////////////////// /// \brief Move the cursor to the given location @@ -88,13 +88,13 @@ /// \param loc location expressed in SFML coordinate system /// //////////////////////////////////////////////////////////// --(void)moveCursorTo:(NSPoint)loc; +- (void)moveCursorTo:(NSPoint)loc; //////////////////////////////////////////////////////////// /// \brief Get the display identifier on which the view is /// //////////////////////////////////////////////////////////// --(CGDirectDisplayID)displayId; +- (CGDirectDisplayID)displayId; //////////////////////////////////////////////////////////// /// \brief Convert the NSEvent mouse button type to SFML type @@ -104,6 +104,6 @@ /// \return Left, Right, ..., or ButtonCount if the button is unknown /// //////////////////////////////////////////////////////////// -+(sf::Mouse::Button)mouseButtonFromEvent:(NSEvent*)event; ++ (sf::Mouse::Button)mouseButtonFromEvent:(NSEvent*)event; @end diff --git a/src/SFML/Window/OSX/SFOpenGLView.h b/src/SFML/Window/OSX/SFOpenGLView.h index f9659d4e1..2f4e44bbb 100644 --- a/src/SFML/Window/OSX/SFOpenGLView.h +++ b/src/SFML/Window/OSX/SFOpenGLView.h @@ -29,19 +29,21 @@ #import #if defined(__APPLE__) - #if defined(__clang__) - #pragma clang diagnostic push - #pragma clang diagnostic ignored "-Wdeprecated-declarations" - #elif defined(__GNUC__) - #pragma GCC diagnostic push - #pragma GCC diagnostic ignored "-Wdeprecated-declarations" - #endif +#if defined(__clang__) +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" +#elif defined(__GNUC__) +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wdeprecated-declarations" +#endif #endif -namespace sf { - namespace priv { - class WindowImplCocoa; - } +namespace sf +{ +namespace priv +{ +class WindowImplCocoa; +} } @class SFSilentResponder; @@ -78,22 +80,22 @@ namespace sf { //////////////////////////////////////////////////////////// @interface SFOpenGLView : NSOpenGLView { - sf::priv::WindowImplCocoa* m_requester; ///< View's requester - BOOL m_useKeyRepeat; ///< Key repeat setting - BOOL m_mouseIsIn; ///< Mouse positional state - NSCursor* m_cursor; ///< Active cursor - NSTrackingArea* m_trackingArea; ///< Mouse tracking area - BOOL m_fullscreen; ///< Indicate whether the window is fullscreen or not - CGFloat m_scaleFactor; ///< Display scale factor (e.g. 1x for classic display, 2x for retina) - BOOL m_cursorGrabbed; ///< Is the mouse cursor trapped? - CGFloat m_deltaXBuffer; ///< See note about cursor grabbing above - CGFloat m_deltaYBuffer; ///< See note about cursor grabbing above - BOOL m_highDpi; ///< Is high-DPI enabled? + sf::priv::WindowImplCocoa* m_requester; ///< View's requester + BOOL m_useKeyRepeat; ///< Key repeat setting + BOOL m_mouseIsIn; ///< Mouse positional state + NSCursor* m_cursor; ///< Active cursor + NSTrackingArea* m_trackingArea; ///< Mouse tracking area + BOOL m_fullscreen; ///< Indicate whether the window is fullscreen or not + CGFloat m_scaleFactor; ///< Display scale factor (e.g. 1x for classic display, 2x for retina) + BOOL m_cursorGrabbed; ///< Is the mouse cursor trapped? + CGFloat m_deltaXBuffer; ///< See note about cursor grabbing above + CGFloat m_deltaYBuffer; ///< See note about cursor grabbing above + BOOL m_highDpi; ///< Is high-DPI enabled? // Hidden text view used to convert key event to actual chars. // We use a silent responder to prevent sound alerts. - SFSilentResponder* m_silentResponder; - NSTextView* m_hiddenTextView; + SFSilentResponder* m_silentResponder; + NSTextView* m_hiddenTextView; } //////////////////////////////////////////////////////////// @@ -110,7 +112,7 @@ namespace sf { /// \return an initialized view /// //////////////////////////////////////////////////////////// --(id)initWithFrame:(NSRect)frameRect fullscreen:(BOOL)isFullscreen highDpi:(BOOL)isHighDpi; +- (id)initWithFrame:(NSRect)frameRect fullscreen:(BOOL)isFullscreen highDpi:(BOOL)isHighDpi; //////////////////////////////////////////////////////////// /// \brief Finish the creation of the SFML OpenGL view @@ -118,7 +120,7 @@ namespace sf { /// This method should be called after the view was added to a window /// //////////////////////////////////////////////////////////// --(void)finishInit; +- (void)finishInit; //////////////////////////////////////////////////////////// /// \brief Apply the given requester to the view @@ -126,7 +128,7 @@ namespace sf { /// \param requester new 'requester' of the view /// //////////////////////////////////////////////////////////// --(void)setRequesterTo:(sf::priv::WindowImplCocoa*)requester; +- (void)setRequesterTo:(sf::priv::WindowImplCocoa*)requester; //////////////////////////////////////////////////////////// /// \brief Compute the position in global coordinate @@ -136,7 +138,7 @@ namespace sf { /// \return the global coordinates of the point /// //////////////////////////////////////////////////////////// --(NSPoint)computeGlobalPositionOfRelativePoint:(NSPoint)point; +- (NSPoint)computeGlobalPositionOfRelativePoint:(NSPoint)point; //////////////////////////////////////////////////////////// /// \brief Get the display scale factor @@ -144,7 +146,7 @@ namespace sf { /// \return e.g. 1.0 for classic display, 2.0 for retina display /// //////////////////////////////////////////////////////////// --(CGFloat)displayScaleFactor; +- (CGFloat)displayScaleFactor; @end @@ -154,13 +156,13 @@ namespace sf { /// \brief Enable key repeat /// //////////////////////////////////////////////////////////// --(void)enableKeyRepeat; +- (void)enableKeyRepeat; //////////////////////////////////////////////////////////// /// \brief Disable key repeat /// //////////////////////////////////////////////////////////// --(void)disableKeyRepeat; +- (void)disableKeyRepeat; @end @@ -170,7 +172,7 @@ namespace sf { /// \brief Set the system cursor for the window area /// //////////////////////////////////////////////////////////// --(void)setCursor:(NSCursor*)cursor; +- (void)setCursor:(NSCursor*)cursor; //////////////////////////////////////////////////////////// /// \brief Compute the position of the cursor @@ -180,7 +182,7 @@ namespace sf { /// \return the mouse position in SFML coord system /// //////////////////////////////////////////////////////////// --(NSPoint)cursorPositionFromEvent:(NSEvent*)eventOrNil; +- (NSPoint)cursorPositionFromEvent:(NSEvent*)eventOrNil; //////////////////////////////////////////////////////////// /// \brief Determine where the mouse is @@ -188,7 +190,7 @@ namespace sf { /// \return true when the mouse is inside the OpenGL view, false otherwise /// //////////////////////////////////////////////////////////// --(BOOL)isMouseInside; +- (BOOL)isMouseInside; //////////////////////////////////////////////////////////// /// Clips or releases the mouse cursor @@ -198,7 +200,7 @@ namespace sf { /// \param grabbed YES to grab, NO to release /// //////////////////////////////////////////////////////////// --(void)setCursorGrabbed:(BOOL)grabbed; +- (void)setCursorGrabbed:(BOOL)grabbed; //////////////////////////////////////////////////////////// /// Update the cursor position according to the grabbing behaviour @@ -206,14 +208,14 @@ namespace sf { /// This function has to be called when the window's state change /// //////////////////////////////////////////////////////////// --(void)updateCursorGrabbed; +- (void)updateCursorGrabbed; @end #if defined(__APPLE__) - #if defined(__clang__) - #pragma clang diagnostic pop - #elif defined(__GNUC__) - #pragma GCC diagnostic pop - #endif +#if defined(__clang__) +#pragma clang diagnostic pop +#elif defined(__GNUC__) +#pragma GCC diagnostic pop +#endif #endif diff --git a/src/SFML/Window/OSX/SFOpenGLView.mm b/src/SFML/Window/OSX/SFOpenGLView.mm index 5711c96b4..e4cdd26a5 100644 --- a/src/SFML/Window/OSX/SFOpenGLView.mm +++ b/src/SFML/Window/OSX/SFOpenGLView.mm @@ -26,19 +26,18 @@ //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// -#include #include - -#import #import +#import #import +#include #if defined(__APPLE__) - #if defined(__clang__) - #pragma clang diagnostic ignored "-Wdeprecated-declarations" - #elif defined(__GNUC__) - #pragma GCC diagnostic ignored "-Wdeprecated-declarations" - #endif +#if defined(__clang__) +#pragma clang diagnostic ignored "-Wdeprecated-declarations" +#elif defined(__GNUC__) +#pragma GCC diagnostic ignored "-Wdeprecated-declarations" +#endif #endif @@ -52,37 +51,37 @@ /// \brief Handle screen changed event /// //////////////////////////////////////////////////////////// --(void)updateScaleFactor; +- (void)updateScaleFactor; //////////////////////////////////////////////////////////// /// \brief Handle view resized event /// //////////////////////////////////////////////////////////// --(void)viewDidEndLiveResize; +- (void)viewDidEndLiveResize; //////////////////////////////////////////////////////////// /// \brief Callback for focus event /// //////////////////////////////////////////////////////////// --(void)windowDidBecomeKey:(NSNotification*)notification; +- (void)windowDidBecomeKey:(NSNotification*)notification; //////////////////////////////////////////////////////////// /// \brief Callback for unfocus event /// //////////////////////////////////////////////////////////// --(void)windowDidResignKey:(NSNotification*)notification; +- (void)windowDidResignKey:(NSNotification*)notification; //////////////////////////////////////////////////////////// /// \brief Handle going in fullscreen mode /// //////////////////////////////////////////////////////////// --(void)enterFullscreen; +- (void)enterFullscreen; //////////////////////////////////////////////////////////// /// \brief Handle exiting fullscreen mode /// //////////////////////////////////////////////////////////// --(void)exitFullscreen; +- (void)exitFullscreen; @end @@ -92,19 +91,19 @@ #pragma mark SFOpenGLView's methods //////////////////////////////////////////////////////// --(id)initWithFrame:(NSRect)frameRect +- (id)initWithFrame:(NSRect)frameRect { return [self initWithFrame:frameRect fullscreen:NO highDpi:NO]; } //////////////////////////////////////////////////////// --(id)initWithFrame:(NSRect)frameRect fullscreen:(BOOL)isFullscreen +- (id)initWithFrame:(NSRect)frameRect fullscreen:(BOOL)isFullscreen { return [self initWithFrame:frameRect fullscreen:isFullscreen highDpi:NO]; } //////////////////////////////////////////////////////// --(id)initWithFrame:(NSRect)frameRect fullscreen:(BOOL)isFullscreen highDpi:(BOOL)isHighDpi +- (id)initWithFrame:(NSRect)frameRect fullscreen:(BOOL)isFullscreen highDpi:(BOOL)isHighDpi { if ((self = [super initWithFrame:frameRect])) { @@ -112,24 +111,22 @@ [self enableKeyRepeat]; // Register for mouse move event - m_mouseIsIn = [self isMouseInside]; - NSUInteger opts = (NSTrackingActiveAlways | NSTrackingMouseEnteredAndExited | NSTrackingMouseMoved | NSTrackingEnabledDuringMouseDrag); - m_trackingArea = [[NSTrackingArea alloc] initWithRect:[self bounds] - options:opts - owner:self - userInfo:nil]; + m_mouseIsIn = [self isMouseInside]; + NSUInteger opts = (NSTrackingActiveAlways | NSTrackingMouseEnteredAndExited | NSTrackingMouseMoved | + NSTrackingEnabledDuringMouseDrag); + m_trackingArea = [[NSTrackingArea alloc] initWithRect:[self bounds] options:opts owner:self userInfo:nil]; [self addTrackingArea:m_trackingArea]; - m_fullscreen = isFullscreen; - m_scaleFactor = 1.0; // Default value; it will be updated in finishInit + m_fullscreen = isFullscreen; + m_scaleFactor = 1.0; // Default value; it will be updated in finishInit m_cursorGrabbed = NO; - m_deltaXBuffer = 0; - m_deltaYBuffer = 0; - m_cursor = [NSCursor arrowCursor]; + m_deltaXBuffer = 0; + m_deltaYBuffer = 0; + m_cursor = [NSCursor arrowCursor]; // Create a hidden text view for parsing key down event properly m_silentResponder = [[SFSilentResponder alloc] init]; - m_hiddenTextView = [[NSTextView alloc] initWithFrame:NSZeroRect]; + m_hiddenTextView = [[NSTextView alloc] initWithFrame:NSZeroRect]; [m_hiddenTextView setNextResponder:m_silentResponder]; // If high DPI is requested, then use high resolution for the OpenGL view. @@ -148,42 +145,48 @@ //////////////////////////////////////////////////////// --(void)update +- (void)update { // In order to prevent an infinite recursion when the window/view is // resized to zero-height/width, we ignore update event when resizing. - if (![self inLiveResize]) { + if (![self inLiveResize]) + { [super update]; } } //////////////////////////////////////////////////////// --(void)finishInit +- (void)finishInit { // Register for window focus events - [[NSNotificationCenter defaultCenter] addObserver:self - selector:@selector(windowDidBecomeKey:) - name:NSWindowDidBecomeKeyNotification - object:[self window]]; - [[NSNotificationCenter defaultCenter] addObserver:self - selector:@selector(windowDidResignKey:) - name:NSWindowDidResignKeyNotification - object:[self window]]; - [[NSNotificationCenter defaultCenter] addObserver:self - selector:@selector(windowDidResignKey:) - name:NSWindowWillCloseNotification - object:[self window]]; + [[NSNotificationCenter defaultCenter] + addObserver:self + selector:@selector(windowDidBecomeKey:) + name:NSWindowDidBecomeKeyNotification + object:[self window]]; + [[NSNotificationCenter defaultCenter] + addObserver:self + selector:@selector(windowDidResignKey:) + name:NSWindowDidResignKeyNotification + object:[self window]]; + [[NSNotificationCenter defaultCenter] + addObserver:self + selector:@selector(windowDidResignKey:) + name:NSWindowWillCloseNotification + object:[self window]]; // Register for changed screen and changed screen's profile events - [[NSNotificationCenter defaultCenter] addObserver:self - selector:@selector(updateScaleFactor) - name:NSWindowDidChangeScreenNotification - object:[self window]]; - [[NSNotificationCenter defaultCenter] addObserver:self - selector:@selector(updateScaleFactor) - name:NSWindowDidChangeScreenProfileNotification - object:[self window]]; + [[NSNotificationCenter defaultCenter] + addObserver:self + selector:@selector(updateScaleFactor) + name:NSWindowDidChangeScreenNotification + object:[self window]]; + [[NSNotificationCenter defaultCenter] + addObserver:self + selector:@selector(updateScaleFactor) + name:NSWindowDidChangeScreenProfileNotification + object:[self window]]; // Now that we have a window, set up correctly the scale factor and cursor grabbing [self updateScaleFactor]; @@ -192,24 +195,24 @@ //////////////////////////////////////////////////////// --(void)setRequesterTo:(sf::priv::WindowImplCocoa*)requester +- (void)setRequesterTo:(sf::priv::WindowImplCocoa*)requester { m_requester = requester; } //////////////////////////////////////////////////////// --(NSPoint)convertPointToScreen:(NSPoint)point +- (NSPoint)convertPointToScreen:(NSPoint)point { NSRect rect = NSZeroRect; rect.origin = point; - rect = [[self window] convertRectToScreen:rect]; + rect = [[self window] convertRectToScreen:rect]; return rect.origin; } //////////////////////////////////////////////////////// --(NSPoint)computeGlobalPositionOfRelativePoint:(NSPoint)point +- (NSPoint)computeGlobalPositionOfRelativePoint:(NSPoint)point { // Flip SFML coordinates to match window coordinates point.y = [self frame].size.height - point.y; @@ -223,29 +226,30 @@ // Flip screen coordinates to match CGDisplayMoveCursorToPoint referential. const double screenHeight = [[[self window] screen] frame].size.height; - point.y = screenHeight - point.y; + point.y = screenHeight - point.y; return point; } //////////////////////////////////////////////////////// --(CGFloat)displayScaleFactor +- (CGFloat)displayScaleFactor { return m_scaleFactor; } //////////////////////////////////////////////////////// --(void)updateScaleFactor +- (void)updateScaleFactor { - NSWindow* window = [self window]; - NSScreen* screen = window ? [window screen] : [NSScreen mainScreen]; - CGFloat oldScaleFactor = m_scaleFactor; - m_scaleFactor = m_highDpi ? [screen backingScaleFactor] : 1.0; + NSWindow* window = [self window]; + NSScreen* screen = window ? [window screen] : [NSScreen mainScreen]; + CGFloat oldScaleFactor = m_scaleFactor; + m_scaleFactor = m_highDpi ? [screen backingScaleFactor] : 1.0; // Send a resize event if the scaling factor changed - if ((m_scaleFactor != oldScaleFactor) && (m_requester != 0)) { + if ((m_scaleFactor != oldScaleFactor) && (m_requester != 0)) + { NSSize newSize = [self frame].size; m_requester->windowResized({static_cast(newSize.width), static_cast(newSize.height)}); } @@ -253,7 +257,7 @@ //////////////////////////////////////////////////////// --(void)viewDidEndLiveResize +- (void)viewDidEndLiveResize { // We use viewDidEndLiveResize to notify the user ONCE // only, when the resizing is finished. @@ -283,7 +287,7 @@ } //////////////////////////////////////////////////////// --(void)windowDidBecomeKey:(NSNotification*)notification +- (void)windowDidBecomeKey:(NSNotification*)notification { (void)notification; @@ -298,7 +302,7 @@ //////////////////////////////////////////////////////// --(void)windowDidResignKey:(NSNotification*)notification +- (void)windowDidResignKey:(NSNotification*)notification { (void)notification; @@ -313,7 +317,7 @@ //////////////////////////////////////////////////////// --(void)enterFullscreen +- (void)enterFullscreen { // Remove the tracking area first, // just to be sure we don't add it twice! @@ -330,7 +334,7 @@ //////////////////////////////////////////////////////// --(void)exitFullscreen +- (void)exitFullscreen { [self removeTrackingArea:m_trackingArea]; @@ -348,7 +352,7 @@ //////////////////////////////////////////////////////// --(void)dealloc +- (void)dealloc { // Unregister for window focus events [[NSNotificationCenter defaultCenter] removeObserver:self]; diff --git a/src/SFML/Window/OSX/SFSilentResponder.h b/src/SFML/Window/OSX/SFSilentResponder.h index 4493f2daf..e899c6451 100644 --- a/src/SFML/Window/OSX/SFSilentResponder.h +++ b/src/SFML/Window/OSX/SFSilentResponder.h @@ -36,7 +36,6 @@ //////////////////////////////////////////////////////////// @interface SFSilentResponder : NSResponder --(void)doCommandBySelector:(SEL)sel; +- (void)doCommandBySelector:(SEL)sel; @end - diff --git a/src/SFML/Window/OSX/SFViewController.h b/src/SFML/Window/OSX/SFViewController.h index 34a1e2547..2fbfac762 100644 --- a/src/SFML/Window/OSX/SFViewController.h +++ b/src/SFML/Window/OSX/SFViewController.h @@ -38,11 +38,11 @@ /// //////////////////////////////////////////////////////////// -@interface SFViewController : NSObject +@interface SFViewController : NSObject { - NSView* m_view; ///< Underlying Cocoa view - SFOpenGLView* m_oglView; ///< OpenGL view - sf::priv::WindowImplCocoa* m_requester; ///< View's requester + NSView* m_view; ///< Underlying Cocoa view + SFOpenGLView* m_oglView; ///< OpenGL view + sf::priv::WindowImplCocoa* m_requester; ///< View's requester } //////////////////////////////////////////////////////////// @@ -53,6 +53,6 @@ /// \return an initialized view controller /// //////////////////////////////////////////////////////////// --(id)initWithView:(NSView*)view; +- (id)initWithView:(NSView*)view; @end diff --git a/src/SFML/Window/OSX/SFViewController.mm b/src/SFML/Window/OSX/SFViewController.mm index 06771f32e..90b072fde 100644 --- a/src/SFML/Window/OSX/SFViewController.mm +++ b/src/SFML/Window/OSX/SFViewController.mm @@ -27,26 +27,26 @@ // Headers //////////////////////////////////////////////////////////// #include -#include -#include - #import #import #import +#include + +#include #if defined(__APPLE__) - #if defined(__clang__) - #pragma clang diagnostic ignored "-Wdeprecated-declarations" - #elif defined(__GNUC__) - #pragma GCC diagnostic ignored "-Wdeprecated-declarations" - #endif +#if defined(__clang__) +#pragma clang diagnostic ignored "-Wdeprecated-declarations" +#elif defined(__GNUC__) +#pragma GCC diagnostic ignored "-Wdeprecated-declarations" +#endif #endif @implementation SFViewController //////////////////////////////////////////////////////// --(id)initWithView:(NSView *)view +- (id)initWithView:(NSView*)view { if ((self = [super init])) { @@ -62,16 +62,15 @@ } // Create the view. - NSRect frame = [m_view frame]; + NSRect frame = [m_view frame]; frame.origin.x = 0; frame.origin.y = 0; - m_oglView = [[SFOpenGLView alloc] initWithFrame:frame]; + m_oglView = [[SFOpenGLView alloc] initWithFrame:frame]; if (m_oglView == nil) { sf::err() << "Could not create an instance of NSOpenGLView " - << "in (SFViewController -initWithView:)." - << std::endl; + << "in (SFViewController -initWithView:)." << std::endl; return self; } @@ -89,7 +88,7 @@ //////////////////////////////////////////////////////// --(void)dealloc +- (void)dealloc { [self closeWindow]; @@ -101,14 +100,14 @@ //////////////////////////////////////////////////////// --(CGFloat)displayScaleFactor +- (CGFloat)displayScaleFactor { return [m_oglView displayScaleFactor]; } //////////////////////////////////////////////////////// --(void)setRequesterTo:(sf::priv::WindowImplCocoa*)requester +- (void)setRequesterTo:(sf::priv::WindowImplCocoa*)requester { // Forward to the view. [m_oglView setRequesterTo:requester]; @@ -117,35 +116,35 @@ //////////////////////////////////////////////////////// --(sf::WindowHandle)getSystemHandle +- (sf::WindowHandle)getSystemHandle { return m_view; } //////////////////////////////////////////////////////// --(BOOL)isMouseInside +- (BOOL)isMouseInside { return [m_oglView isMouseInside]; } //////////////////////////////////////////////////////// --(void)setCursorGrabbed:(BOOL)grabbed +- (void)setCursorGrabbed:(BOOL)grabbed { [m_oglView setCursorGrabbed:grabbed]; } //////////////////////////////////////////////////////// --(void)setCursor:(NSCursor*)cursor +- (void)setCursor:(NSCursor*)cursor { return [m_oglView setCursor:cursor]; } //////////////////////////////////////////////////////////// --(NSPoint)position +- (NSPoint)position { // Origin is bottom-left corner of the window return [m_view convertPoint:NSMakePoint(0, 0) toView:nil]; // nil means window @@ -153,28 +152,26 @@ ////////////////////////////////////////////////////////. --(void)setWindowPositionToX:(int)x Y:(int)y +- (void)setWindowPositionToX:(int)x Y:(int)y { (void)x; (void)y; - sf::err() << "Cannot move SFML area when SFML is integrated in a NSView. Use the view handler directly instead." << std::endl; + sf::err() << "Cannot move SFML area when SFML is integrated in a NSView. Use the view handler directly instead." + << std::endl; } //////////////////////////////////////////////////////////// --(NSSize)size +- (NSSize)size { return [m_oglView frame].size; } //////////////////////////////////////////////////////// --(void)resizeTo:(unsigned int)width by:(unsigned int)height +- (void)resizeTo:(unsigned int)width by:(unsigned int)height { - NSRect frame = NSMakeRect([m_view frame].origin.x, - [m_view frame].origin.y, - width, - height); + NSRect frame = NSMakeRect([m_view frame].origin.x, [m_view frame].origin.y, width, height); [m_view setFrame:frame]; [m_oglView setFrame:frame]; @@ -182,7 +179,7 @@ //////////////////////////////////////////////////////// --(void)changeTitle:(NSString*)title +- (void)changeTitle:(NSString*)title { (void)title; sf::err() << "Cannot change the title of the SFML area when SFML is integrated in a NSView." << std::endl; @@ -190,28 +187,28 @@ //////////////////////////////////////////////////////// --(void)hideWindow +- (void)hideWindow { [m_view setHidden:YES]; } //////////////////////////////////////////////////////// --(void)showWindow +- (void)showWindow { [m_view setHidden:NO]; } //////////////////////////////////////////////////////// --(void)closeWindow +- (void)closeWindow { // If the "window" is really a view, this is a no-op. } //////////////////////////////////////////////////////// --(void)requestFocus +- (void)requestFocus { // Note: this doesn't imply that the view will get any event. // The user has to make sure events are forwarded to the view @@ -224,30 +221,28 @@ //////////////////////////////////////////////////////////// --(BOOL)hasFocus +- (BOOL)hasFocus { return [NSApp keyWindow] == [m_view window]; } //////////////////////////////////////////////////////// --(void)enableKeyRepeat +- (void)enableKeyRepeat { [m_oglView enableKeyRepeat]; } //////////////////////////////////////////////////////// --(void)disableKeyRepeat +- (void)disableKeyRepeat { [m_oglView disableKeyRepeat]; } //////////////////////////////////////////////////////// --(void)setIconTo:(unsigned int)width - by:(unsigned int)height - with:(const sf::Uint8*)pixels +- (void)setIconTo:(unsigned int)width by:(unsigned int)height with:(const sf::Uint8*)pixels { (void)width; (void)height; @@ -257,7 +252,7 @@ //////////////////////////////////////////////////////// --(void)processEvent +- (void)processEvent { // If we are not on the main thread we stop here and advice the user. if ([NSThread currentThread] != [NSThread mainThread]) @@ -278,7 +273,7 @@ //////////////////////////////////////////////////////// --(void)applyContext:(NSOpenGLContext*)context +- (void)applyContext:(NSOpenGLContext*)context { [m_oglView setOpenGLContext:context]; [context setView:m_oglView]; diff --git a/src/SFML/Window/OSX/SFWindow.h b/src/SFML/Window/OSX/SFWindow.h index 89fdad857..ce949543e 100644 --- a/src/SFML/Window/OSX/SFWindow.h +++ b/src/SFML/Window/OSX/SFWindow.h @@ -45,7 +45,7 @@ /// \return YES /// //////////////////////////////////////////////////////////// --(BOOL)acceptsFirstResponder; +- (BOOL)acceptsFirstResponder; //////////////////////////////////////////////////////////// /// \brief Allow to grab fullscreen events @@ -55,7 +55,7 @@ /// \return YES /// //////////////////////////////////////////////////////////// --(BOOL)canBecomeKeyWindow; +- (BOOL)canBecomeKeyWindow; //////////////////////////////////////////////////////////// /// \brief Allow fullscreen windows to become the main window @@ -67,7 +67,7 @@ /// \return YES /// //////////////////////////////////////////////////////////// --(BOOL)canBecomeMainWindow; +- (BOOL)canBecomeMainWindow; //////////////////////////////////////////////////////////// /// \brief Prevent system alert @@ -75,7 +75,7 @@ /// \param theEvent a Cocoa event /// //////////////////////////////////////////////////////////// --(void)keyDown:(NSEvent*)theEvent; +- (void)keyDown:(NSEvent*)theEvent; //////////////////////////////////////////////////////////// /// \brief This action method simulates the user clicking the close button @@ -85,7 +85,7 @@ /// \param sender The message's sender /// //////////////////////////////////////////////////////////// --(void)performClose:(id)sender; +- (void)performClose:(id)sender; //////////////////////////////////////////////////////////// /// \brief Enabling or disabling a specific menu item @@ -95,7 +95,7 @@ /// \return YES to enable menuItem, NO to disable it. /// //////////////////////////////////////////////////////////// --(BOOL)validateMenuItem:(NSMenuItem*)menuItem; +- (BOOL)validateMenuItem:(NSMenuItem*)menuItem; @end @@ -114,6 +114,6 @@ /// \return nil /// //////////////////////////////////////////////////////////// --(id)sfClose; +- (id)sfClose; @end diff --git a/src/SFML/Window/OSX/SFWindowController.h b/src/SFML/Window/OSX/SFWindowController.h index 6953d11d6..abe85b255 100644 --- a/src/SFML/Window/OSX/SFWindowController.h +++ b/src/SFML/Window/OSX/SFWindowController.h @@ -26,17 +26,18 @@ //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// -#include - #import +#include //////////////////////////////////////////////////////////// /// Predefine some classes //////////////////////////////////////////////////////////// -namespace sf { - namespace priv { - class WindowImplCocoa; - } +namespace sf +{ +namespace priv +{ +class WindowImplCocoa; +} } @class SFOpenGLView; @@ -55,14 +56,14 @@ namespace sf { /// style is restored. /// //////////////////////////////////////////////////////////// -@interface SFWindowController : NSResponder +@interface SFWindowController : NSResponder { - NSWindow* m_window; ///< Underlying Cocoa window to be controlled - SFOpenGLView* m_oglView; ///< OpenGL view for rendering - sf::priv::WindowImplCocoa* m_requester; ///< Requester - BOOL m_fullscreen; ///< Indicate whether the window is fullscreen or not - BOOL m_restoreResize; ///< See note above - BOOL m_highDpi; ///< Support high-DPI rendering or not + NSWindow* m_window; ///< Underlying Cocoa window to be controlled + SFOpenGLView* m_oglView; ///< OpenGL view for rendering + sf::priv::WindowImplCocoa* m_requester; ///< Requester + BOOL m_fullscreen; ///< Indicate whether the window is fullscreen or not + BOOL m_restoreResize; ///< See note above + BOOL m_highDpi; ///< Support high-DPI rendering or not } //////////////////////////////////////////////////////////// @@ -73,7 +74,7 @@ namespace sf { /// \return an initialized controller /// //////////////////////////////////////////////////////////// --(id)initWithWindow:(NSWindow*)window; +- (id)initWithWindow:(NSWindow*)window; //////////////////////////////////////////////////////////// /// \brief Create the SFML window "from scratch" (SFML handle everything) @@ -84,6 +85,6 @@ namespace sf { /// \return an initialized controller /// //////////////////////////////////////////////////////////// --(id)initWithMode:(const sf::VideoMode&)mode andStyle:(unsigned long)style; +- (id)initWithMode:(const sf::VideoMode&)mode andStyle:(unsigned long)style; @end diff --git a/src/SFML/Window/OSX/SFWindowController.mm b/src/SFML/Window/OSX/SFWindowController.mm index e605874f6..d63590e65 100644 --- a/src/SFML/Window/OSX/SFWindowController.mm +++ b/src/SFML/Window/OSX/SFWindowController.mm @@ -26,29 +26,29 @@ //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// -#include -#include -#include -#include #include -#include -#include -#include - #import -#import #import #import #import #import +#import +#include +#include +#include +#include + +#include #import +#include +#include #if defined(__APPLE__) - #if defined(__clang__) - #pragma clang diagnostic ignored "-Wdeprecated-declarations" - #elif defined(__GNUC__) - #pragma GCC diagnostic ignored "-Wdeprecated-declarations" - #endif +#if defined(__clang__) +#pragma clang diagnostic ignored "-Wdeprecated-declarations" +#elif defined(__GNUC__) +#pragma GCC diagnostic ignored "-Wdeprecated-declarations" +#endif #endif //////////////////////////////////////////////////////////// @@ -61,7 +61,7 @@ @implementation SFBlackView //////////////////////////////////////////////////////////// --(void)drawRect:(NSRect)dirtyRect +- (void)drawRect:(NSRect)dirtyRect { [[NSColor blackColor] setFill]; NSRectFill(dirtyRect); @@ -81,7 +81,7 @@ /// \return screen height /// //////////////////////////////////////////////////////////// --(float)screenHeight; +- (float)screenHeight; //////////////////////////////////////////////////////////// /// \brief Retrieves the title bar height @@ -89,7 +89,7 @@ /// \return title bar height /// //////////////////////////////////////////////////////////// --(float)titlebarHeight; +- (float)titlebarHeight; @end @@ -99,16 +99,16 @@ #pragma mark SFWindowController's methods //////////////////////////////////////////////////////// --(id)initWithWindow:(NSWindow*)window +- (id)initWithWindow:(NSWindow*)window { if ((self = [super init])) { - m_window = nil; - m_oglView = nil; - m_requester = 0; - m_fullscreen = NO; // assuming this is the case... too hard to handle anyway. + m_window = nil; + m_oglView = nil; + m_requester = 0; + m_fullscreen = NO; // assuming this is the case... too hard to handle anyway. m_restoreResize = NO; - m_highDpi = NO; + m_highDpi = NO; // Retain the window for our own use. m_window = [window retain]; @@ -120,15 +120,12 @@ } // Create the view. - m_oglView = [[SFOpenGLView alloc] initWithFrame:[[m_window contentView] frame] - fullscreen:NO - highDpi:NO]; + m_oglView = [[SFOpenGLView alloc] initWithFrame:[[m_window contentView] frame] fullscreen:NO highDpi:NO]; if (m_oglView == nil) { sf::err() << "Could not create an instance of NSOpenGLView " - << "in -[SFWindowController initWithWindow:]." - << std::endl; + << "in -[SFWindowController initWithWindow:]." << std::endl; return self; } @@ -143,7 +140,7 @@ //////////////////////////////////////////////////////// --(id)initWithMode:(const sf::VideoMode&)mode andStyle:(unsigned long)style +- (id)initWithMode:(const sf::VideoMode&)mode andStyle:(unsigned long)style { // If we are not on the main thread we stop here and advice the user. if ([NSThread currentThread] != [NSThread mainThread]) @@ -159,12 +156,12 @@ if ((self = [super init])) { - m_window = nil; - m_oglView = nil; - m_requester = 0; - m_fullscreen = ((style & sf::Style::Fullscreen) != 0) ? YES : NO; + m_window = nil; + m_oglView = nil; + m_requester = 0; + m_fullscreen = ((style & sf::Style::Fullscreen) != 0) ? YES : NO; m_restoreResize = NO; - m_highDpi = NO; + m_highDpi = NO; if (m_fullscreen) [self setupFullscreenViewWithMode:mode]; @@ -178,27 +175,27 @@ //////////////////////////////////////////////////////// --(void)setupFullscreenViewWithMode:(const sf::VideoMode&)mode +- (void)setupFullscreenViewWithMode:(const sf::VideoMode&)mode { // Create a screen-sized window on the main display sf::VideoMode desktop = sf::VideoMode::getDesktopMode(); sf::priv::scaleInWidthHeight(desktop, nil); NSRect windowRect = NSMakeRect(0, 0, desktop.size.x, desktop.size.y); - m_window = [[SFWindow alloc] initWithContentRect:windowRect - styleMask:NSBorderlessWindowMask - backing:NSBackingStoreBuffered - defer:NO]; + m_window = [[SFWindow alloc] + initWithContentRect:windowRect + styleMask:NSBorderlessWindowMask + backing:NSBackingStoreBuffered + defer:NO]; if (m_window == nil) { sf::err() << "Could not create an instance of NSWindow " - << "in -[SFWindowController setupFullscreenViewWithMode:]." - << std::endl; + << "in -[SFWindowController setupFullscreenViewWithMode:]." << std::endl; return; } // Set the window level to be above the menu bar - [m_window setLevel:NSMainMenuWindowLevel+1]; + [m_window setLevel:NSMainMenuWindowLevel + 1]; // More window configuration... [m_window setOpaque:YES]; @@ -217,27 +214,23 @@ if (masterView == nil) { sf::err() << "Could not create an instance of SFBlackView " - << "in -[SFWindowController setupFullscreenViewWithMode:]." - << std::endl; + << "in -[SFWindowController setupFullscreenViewWithMode:]." << std::endl; return; } // Create our OpenGL view size and the view - CGFloat width = std::min(mode.size.x, desktop.size.x); - CGFloat height = std::min(mode.size.y, desktop.size.y); - CGFloat x = (desktop.size.x - width) / 2.0; - CGFloat y = (desktop.size.y - height) / 2.0; - NSRect oglRect = NSMakeRect(x, y, width, height); + CGFloat width = std::min(mode.size.x, desktop.size.x); + CGFloat height = std::min(mode.size.y, desktop.size.y); + CGFloat x = (desktop.size.x - width) / 2.0; + CGFloat y = (desktop.size.y - height) / 2.0; + NSRect oglRect = NSMakeRect(x, y, width, height); - m_oglView = [[SFOpenGLView alloc] initWithFrame:oglRect - fullscreen:YES - highDpi:m_highDpi]; + m_oglView = [[SFOpenGLView alloc] initWithFrame:oglRect fullscreen:YES highDpi:m_highDpi]; if (m_oglView == nil) { sf::err() << "Could not create an instance of NSOpenGLView " - << "in -[SFWindowController setupFullscreenViewWithMode:]." - << std::endl; + << "in -[SFWindowController setupFullscreenViewWithMode:]." << std::endl; return; } @@ -248,7 +241,7 @@ //////////////////////////////////////////////////////// --(void)setupWindowWithMode:(const sf::VideoMode&)mode andStyle:(unsigned long)style +- (void)setupWindowWithMode:(const sf::VideoMode&)mode andStyle:(unsigned long)style { // We know that style & sf::Style::Fullscreen is false. @@ -265,10 +258,11 @@ nsStyle |= NSClosableWindowMask; // Create the window. - m_window = [[SFWindow alloc] initWithContentRect:rect - styleMask:nsStyle - backing:NSBackingStoreBuffered - defer:NO]; // Don't defer it! + m_window = [[SFWindow alloc] + initWithContentRect:rect + styleMask:nsStyle + backing:NSBackingStoreBuffered + defer:NO]; // Don't defer it! /* "YES" produces some "invalid drawable". See http://www.cocoabuilder.com/archive/cocoa/152482-nsviews-and-nsopenglcontext-invalid-drawable-error.html @@ -282,22 +276,18 @@ if (m_window == nil) { sf::err() << "Could not create an instance of NSWindow " - << "in -[SFWindowController setupWindowWithMode:andStyle:]." - << std::endl; + << "in -[SFWindowController setupWindowWithMode:andStyle:]." << std::endl; return; } // Create the view. - m_oglView = [[SFOpenGLView alloc] initWithFrame:[[m_window contentView] frame] - fullscreen:NO - highDpi:m_highDpi]; + m_oglView = [[SFOpenGLView alloc] initWithFrame:[[m_window contentView] frame] fullscreen:NO highDpi:m_highDpi]; if (m_oglView == nil) { sf::err() << "Could not create an instance of NSOpenGLView " - << "in -[SFWindowController setupWindowWithMode:andStyle:]." - << std::endl; + << "in -[SFWindowController setupWindowWithMode:andStyle:]." << std::endl; return; } @@ -318,7 +308,7 @@ //////////////////////////////////////////////////////// --(void)dealloc +- (void)dealloc { [self closeWindow]; [NSMenu setMenuBarVisible:YES]; @@ -335,14 +325,14 @@ //////////////////////////////////////////////////////// --(CGFloat)displayScaleFactor +- (CGFloat)displayScaleFactor { return [m_oglView displayScaleFactor]; } //////////////////////////////////////////////////////// --(void)setRequesterTo:(sf::priv::WindowImplCocoa*)requester +- (void)setRequesterTo:(sf::priv::WindowImplCocoa*)requester { // Forward to the view. [m_oglView setRequesterTo:requester]; @@ -351,33 +341,33 @@ //////////////////////////////////////////////////////// --(sf::WindowHandle)getSystemHandle +- (sf::WindowHandle)getSystemHandle { return m_window; } //////////////////////////////////////////////////////// --(BOOL)isMouseInside +- (BOOL)isMouseInside { return [m_oglView isMouseInside]; } //////////////////////////////////////////////////////// --(void)setCursorGrabbed:(BOOL)grabbed +- (void)setCursorGrabbed:(BOOL)grabbed { // Remove or restore resizeable style if needed BOOL resizeable = (([m_window styleMask] & NSResizableWindowMask) != 0) ? YES : NO; if (grabbed && resizeable) { - m_restoreResize = YES; + m_restoreResize = YES; NSUInteger newStyle = [m_window styleMask] & ~NSResizableWindowMask; [m_window setStyleMask:newStyle]; } else if (!grabbed && m_restoreResize) { - m_restoreResize = NO; + m_restoreResize = NO; NSUInteger newStyle = [m_window styleMask] | NSResizableWindowMask; [m_window setStyleMask:newStyle]; } @@ -388,14 +378,14 @@ //////////////////////////////////////////////////////// --(void)setCursor:(NSCursor*)cursor +- (void)setCursor:(NSCursor*)cursor { return [m_oglView setCursor:cursor]; } //////////////////////////////////////////////////////////// --(NSPoint)position +- (NSPoint)position { // Note: since 10.7 the conversion API works with NSRect // instead of NSPoint. Therefore we use a NSRect but ignore @@ -419,7 +409,7 @@ //////////////////////////////////////////////////////// --(void)setWindowPositionToX:(int)x Y:(int)y +- (void)setWindowPositionToX:(int)x Y:(int)y { NSPoint point = NSMakePoint(x, y); @@ -435,14 +425,14 @@ //////////////////////////////////////////////////////// --(NSSize)size +- (NSSize)size { return [m_oglView frame].size; } //////////////////////////////////////////////////////// --(void)resizeTo:(unsigned int)width by:(unsigned int)height +- (void)resizeTo:(unsigned int)width by:(unsigned int)height { if (m_fullscreen) { @@ -451,12 +441,12 @@ sf::VideoMode desktop = sf::VideoMode::getDesktopMode(); sf::priv::scaleInWidthHeight(desktop, nil); - width = std::min(width, desktop.size.x); + width = std::min(width, desktop.size.x); height = std::min(height, desktop.size.y); - CGFloat x = (desktop.size.x - width) / 2.0; - CGFloat y = (desktop.size.y - height) / 2.0; - NSRect oglRect = NSMakeRect(x, y, width, height); + CGFloat x = (desktop.size.x - width) / 2.0; + CGFloat y = (desktop.size.y - height) / 2.0; + NSRect oglRect = NSMakeRect(x, y, width, height); [m_oglView setFrame:oglRect]; [m_oglView setNeedsDisplay:YES]; @@ -474,7 +464,7 @@ // Corner case: don't set the window height bigger than the screen height // or the view will be resized _later_ without generating a resize event. - NSRect screenFrame = [[NSScreen mainScreen] visibleFrame]; + NSRect screenFrame = [[NSScreen mainScreen] visibleFrame]; CGFloat maxVisibleHeight = screenFrame.size.height; if (height > maxVisibleHeight) { @@ -485,10 +475,7 @@ m_requester->windowResized({width, height - static_cast([self titlebarHeight])}); } - NSRect frame = NSMakeRect([m_window frame].origin.x, - [m_window frame].origin.y, - width, - height); + NSRect frame = NSMakeRect([m_window frame].origin.x, [m_window frame].origin.y, width, height); [m_window setFrame:frame display:YES]; @@ -499,28 +486,28 @@ //////////////////////////////////////////////////////// --(void)changeTitle:(NSString*)title +- (void)changeTitle:(NSString*)title { [m_window setTitle:title]; } //////////////////////////////////////////////////////// --(void)hideWindow +- (void)hideWindow { [m_window orderOut:nil]; } //////////////////////////////////////////////////////// --(void)showWindow +- (void)showWindow { [m_window makeKeyAndOrderFront:nil]; } //////////////////////////////////////////////////////// --(void)closeWindow +- (void)closeWindow { [self applyContext:nil]; [m_window close]; @@ -531,7 +518,7 @@ //////////////////////////////////////////////////////// --(void)requestFocus +- (void)requestFocus { [m_window makeKeyAndOrderFront:nil]; @@ -541,34 +528,31 @@ //////////////////////////////////////////////////////////// --(BOOL)hasFocus +- (BOOL)hasFocus { return [NSApp keyWindow] == m_window; } //////////////////////////////////////////////////////// --(void)enableKeyRepeat +- (void)enableKeyRepeat { [m_oglView enableKeyRepeat]; } //////////////////////////////////////////////////////// --(void)disableKeyRepeat +- (void)disableKeyRepeat { [m_oglView disableKeyRepeat]; } //////////////////////////////////////////////////////// --(void)setIconTo:(unsigned int)width - by:(unsigned int)height - with:(const sf::Uint8*)pixels +- (void)setIconTo:(unsigned int)width by:(unsigned int)height with:(const sf::Uint8*)pixels { // Load image and set app icon. - NSImage* icon = [NSImage imageWithRawData:pixels - andSize:NSMakeSize(width, height)]; + NSImage* icon = [NSImage imageWithRawData:pixels andSize:NSMakeSize(width, height)]; [[SFApplication sharedApplication] setApplicationIconImage:icon]; @@ -577,7 +561,7 @@ //////////////////////////////////////////////////////// --(void)processEvent +- (void)processEvent { // If we are not on the main thread we stop here and advice the user. if ([NSThread currentThread] != [NSThread mainThread]) @@ -598,7 +582,7 @@ //////////////////////////////////////////////////////// --(void)applyContext:(NSOpenGLContext*)context +- (void)applyContext:(NSOpenGLContext*)context { [m_oglView setOpenGLContext:context]; [context setView:m_oglView]; @@ -610,7 +594,7 @@ //////////////////////////////////////////////////////// --(BOOL)windowShouldClose:(id)sender +- (BOOL)windowShouldClose:(id)sender { (void)sender; @@ -626,20 +610,19 @@ #pragma mark Other methods //////////////////////////////////////////////////////// --(float)screenHeight +- (float)screenHeight { - NSDictionary* deviceDescription = [[m_window screen] deviceDescription]; - NSNumber* screenNumber = [deviceDescription valueForKey:@"NSScreenNumber"]; - CGDirectDisplayID screenID = static_cast([screenNumber intValue]); + NSDictionary* deviceDescription = [[m_window screen] deviceDescription]; + NSNumber* screenNumber = [deviceDescription valueForKey:@"NSScreenNumber"]; + CGDirectDisplayID screenID = static_cast([screenNumber intValue]); return static_cast(CGDisplayPixelsHigh(screenID)); } //////////////////////////////////////////////////////// --(float)titlebarHeight +- (float)titlebarHeight { return static_cast(NSHeight([m_window frame]) - NSHeight([[m_window contentView] frame])); } @end - diff --git a/src/SFML/Window/OSX/Scaling.h b/src/SFML/Window/OSX/Scaling.h index 80657d4ac..6961c8006 100644 --- a/src/SFML/Window/OSX/Scaling.h +++ b/src/SFML/Window/OSX/Scaling.h @@ -100,4 +100,3 @@ void scaleOutXY(T& out, id delegate) } // namespace priv } // namespace sf - diff --git a/src/SFML/Window/OSX/SensorImpl.hpp b/src/SFML/Window/OSX/SensorImpl.hpp index d257e9765..5a05d9b45 100644 --- a/src/SFML/Window/OSX/SensorImpl.hpp +++ b/src/SFML/Window/OSX/SensorImpl.hpp @@ -37,7 +37,6 @@ namespace priv class SensorImpl { public: - //////////////////////////////////////////////////////////// /// \brief Perform the global initialization of the sensor module /// diff --git a/src/SFML/Window/OSX/VideoModeImpl.cpp b/src/SFML/Window/OSX/VideoModeImpl.cpp index b2ade097a..660f74afc 100644 --- a/src/SFML/Window/OSX/VideoModeImpl.cpp +++ b/src/SFML/Window/OSX/VideoModeImpl.cpp @@ -26,9 +26,10 @@ //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// -#include -#include #include +#include +#include + #include #include @@ -86,7 +87,7 @@ VideoMode VideoModeImpl::getDesktopMode() // instead of display id and CGDisplayPixelsHigh/Wide. CGDirectDisplayID display = CGMainDisplayID(); - CGDisplayModeRef cgmode = CGDisplayCopyDisplayMode(display); + CGDisplayModeRef cgmode = CGDisplayCopyDisplayMode(display); mode = convertCGModeToSFMode(cgmode); @@ -97,4 +98,3 @@ VideoMode VideoModeImpl::getDesktopMode() } // namespace priv } // namespace sf - diff --git a/src/SFML/Window/OSX/WindowImplCocoa.hpp b/src/SFML/Window/OSX/WindowImplCocoa.hpp index f3c55f611..00379e4e0 100644 --- a/src/SFML/Window/OSX/WindowImplCocoa.hpp +++ b/src/SFML/Window/OSX/WindowImplCocoa.hpp @@ -33,13 +33,13 @@ #include #if defined(__APPLE__) - #if defined(__clang__) - #pragma clang diagnostic push - #pragma clang diagnostic ignored "-Wdeprecated-declarations" - #elif defined(__GNUC__) - #pragma GCC diagnostic push - #pragma GCC diagnostic ignored "-Wdeprecated-declarations" - #endif +#if defined(__clang__) +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" +#elif defined(__GNUC__) +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wdeprecated-declarations" +#endif #endif //////////////////////////////////////////////////////////// @@ -48,7 +48,7 @@ #ifdef __OBJC__ #import -using WindowImplDelegateRef = id; +using WindowImplDelegateRef = id; @class NSOpenGLContext; using NSOpenGLContextRef = NSOpenGLContext*; @@ -58,7 +58,7 @@ using NSOpenGLContextRef = NSOpenGLContext*; using unichar = unsigned short; // See NSString.h using WindowImplDelegateRef = void*; -using NSOpenGLContextRef = void*; +using NSOpenGLContextRef = void*; #endif @@ -248,7 +248,6 @@ public: static void setUpProcess(); public: - //////////////////////////////////////////////////////////// /// \brief Get the OS-specific handle of the window /// @@ -362,7 +361,6 @@ public: bool hasFocus() const override; protected: - //////////////////////////////////////////////////////////// /// \brief Process incoming events from the operating system /// @@ -370,7 +368,6 @@ protected: void processEvents() override; private: - //////////////////////////////////////////////////////////// // Member data //////////////////////////////////////////////////////////// @@ -383,11 +380,11 @@ private: } // namespace sf #if defined(__APPLE__) - #if defined(__clang__) - #pragma clang diagnostic pop - #elif defined(__GNUC__) - #pragma GCC diagnostic pop - #endif +#if defined(__clang__) +#pragma clang diagnostic pop +#elif defined(__GNUC__) +#pragma GCC diagnostic pop +#endif #endif #endif // SFML_WINDOWIMPLCOCOA_HPP diff --git a/src/SFML/Window/OSX/WindowImplCocoa.mm b/src/SFML/Window/OSX/WindowImplCocoa.mm index 6594b2c07..5392cc99e 100644 --- a/src/SFML/Window/OSX/WindowImplCocoa.mm +++ b/src/SFML/Window/OSX/WindowImplCocoa.mm @@ -26,19 +26,19 @@ //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// -#include -#include #include #include -#include - -#import -#import +#include #import #import #import #import #import +#import +#include +#import + +#include namespace sf { @@ -54,7 +54,7 @@ namespace priv namespace { - bool isCursorHidden = false; // initially, the cursor is visible +bool isCursorHidden = false; // initially, the cursor is visible } @@ -85,8 +85,7 @@ void showMouseCursor() #pragma mark WindowImplCocoa's ctor/dtor //////////////////////////////////////////////////////////// -WindowImplCocoa::WindowImplCocoa(WindowHandle handle) : -m_showCursor(true) +WindowImplCocoa::WindowImplCocoa(WindowHandle handle) : m_showCursor(true) { AutoreleasePool pool; // Treat the handle as it real type @@ -106,12 +105,9 @@ m_showCursor(true) sf::err() << "Cannot import this Window Handle because it is neither " << "a nor object " - << "(or any of their subclasses). You gave a <" - << [[nsHandle className] UTF8String] - << "> object." + << "(or any of their subclasses). You gave a <" << [[nsHandle className] UTF8String] << "> object." << std::endl; return; - } [m_delegate setRequesterTo:this]; @@ -122,10 +118,7 @@ m_showCursor(true) //////////////////////////////////////////////////////////// -WindowImplCocoa::WindowImplCocoa(VideoMode mode, - const String& title, - unsigned long style, - const ContextSettings& /*settings*/) : +WindowImplCocoa::WindowImplCocoa(VideoMode mode, const String& title, unsigned long style, const ContextSettings& /*settings*/) : m_showCursor(true) { AutoreleasePool pool; @@ -156,7 +149,7 @@ WindowImplCocoa::~WindowImplCocoa() NSArray* windows = [NSApp orderedWindows]; if ([windows count] > 0) { - NSWindow *nextWindow = [windows objectAtIndex:0]; + NSWindow* nextWindow = [windows objectAtIndex:0]; if ([nextWindow isVisible]) [nextWindow makeKeyAndOrderFront:nil]; } @@ -175,7 +168,7 @@ void WindowImplCocoa::applyContext(NSOpenGLContextRef context) const void WindowImplCocoa::setUpProcess() { AutoreleasePool pool; - static bool isTheProcessSetAsApplication = false; + static bool isTheProcessSetAsApplication = false; if (!isTheProcessSetAsApplication) { @@ -222,7 +215,7 @@ void WindowImplCocoa::windowClosed() void WindowImplCocoa::windowResized(const Vector2u& size) { Event event; - event.type = Event::Resized; + event.type = Event::Resized; event.size.width = size.x; event.size.height = size.y; scaleOutWidthHeight(event.size.width, event.size.height, m_delegate); @@ -264,10 +257,10 @@ void WindowImplCocoa::windowGainedFocus() void WindowImplCocoa::mouseDownAt(Mouse::Button button, int x, int y) { Event event; - event.type = Event::MouseButtonPressed; + event.type = Event::MouseButtonPressed; event.mouseButton.button = button; - event.mouseButton.x = x; - event.mouseButton.y = y; + event.mouseButton.x = x; + event.mouseButton.y = y; scaleOutXY(event.mouseButton, m_delegate); pushEvent(event); @@ -278,10 +271,10 @@ void WindowImplCocoa::mouseDownAt(Mouse::Button button, int x, int y) void WindowImplCocoa::mouseUpAt(Mouse::Button button, int x, int y) { Event event; - event.type = Event::MouseButtonReleased; + event.type = Event::MouseButtonReleased; event.mouseButton.button = button; - event.mouseButton.x = x; - event.mouseButton.y = y; + event.mouseButton.x = x; + event.mouseButton.y = y; scaleOutXY(event.mouseButton, m_delegate); pushEvent(event); @@ -292,7 +285,7 @@ void WindowImplCocoa::mouseUpAt(Mouse::Button button, int x, int y) void WindowImplCocoa::mouseMovedAt(int x, int y) { Event event; - event.type = Event::MouseMoved; + event.type = Event::MouseMoved; event.mouseMove.x = x; event.mouseMove.y = y; scaleOutXY(event.mouseMove, m_delegate); @@ -305,19 +298,19 @@ void WindowImplCocoa::mouseWheelScrolledAt(float deltaX, float deltaY, int x, in { Event event; - event.type = Event::MouseWheelScrolled; + event.type = Event::MouseWheelScrolled; event.mouseWheelScroll.wheel = Mouse::VerticalWheel; event.mouseWheelScroll.delta = deltaY; - event.mouseWheelScroll.x = x; - event.mouseWheelScroll.y = y; + event.mouseWheelScroll.x = x; + event.mouseWheelScroll.y = y; scaleOutXY(event.mouseWheelScroll, m_delegate); pushEvent(event); - event.type = Event::MouseWheelScrolled; + event.type = Event::MouseWheelScrolled; event.mouseWheelScroll.wheel = Mouse::HorizontalWheel; event.mouseWheelScroll.delta = deltaX; - event.mouseWheelScroll.x = x; - event.mouseWheelScroll.y = y; + event.mouseWheelScroll.x = x; + event.mouseWheelScroll.y = y; scaleOutXY(event.mouseWheelScroll, m_delegate); pushEvent(event); } @@ -356,7 +349,7 @@ void WindowImplCocoa::keyDown(Event::KeyEvent key) { Event event; event.type = Event::KeyPressed; - event.key = key; + event.key = key; pushEvent(event); } @@ -367,7 +360,7 @@ void WindowImplCocoa::keyUp(Event::KeyEvent key) { Event event; event.type = Event::KeyReleased; - event.key = key; + event.key = key; pushEvent(event); } @@ -377,7 +370,7 @@ void WindowImplCocoa::keyUp(Event::KeyEvent key) void WindowImplCocoa::textEntered(unichar charcode) { Event event; - event.type = Event::TextEntered; + event.type = Event::TextEntered; event.text.unicode = charcode; pushEvent(event); @@ -409,8 +402,8 @@ WindowHandle WindowImplCocoa::getSystemHandle() const Vector2i WindowImplCocoa::getPosition() const { AutoreleasePool pool; - NSPoint pos = [m_delegate position]; - sf::Vector2i ret(static_cast(pos.x), static_cast(pos.y)); + NSPoint pos = [m_delegate position]; + sf::Vector2i ret(static_cast(pos.x), static_cast(pos.y)); scaleOutXY(ret, m_delegate); return ret; } @@ -420,7 +413,7 @@ Vector2i WindowImplCocoa::getPosition() const void WindowImplCocoa::setPosition(const Vector2i& position) { AutoreleasePool pool; - sf::Vector2i backingPosition = position; + sf::Vector2i backingPosition = position; scaleInXY(backingPosition, m_delegate); [m_delegate setWindowPositionToX:backingPosition.x Y:backingPosition.y]; } @@ -430,8 +423,8 @@ void WindowImplCocoa::setPosition(const Vector2i& position) Vector2u WindowImplCocoa::getSize() const { AutoreleasePool pool; - NSSize size = [m_delegate size]; - Vector2u ret(static_cast(size.width), static_cast(size.height)); + NSSize size = [m_delegate size]; + Vector2u ret(static_cast(size.width), static_cast(size.height)); scaleOutXY(ret, m_delegate); return ret; } diff --git a/src/SFML/Window/OSX/WindowImplDelegateProtocol.h b/src/SFML/Window/OSX/WindowImplDelegateProtocol.h index 36dc4ac51..3d06fad37 100644 --- a/src/SFML/Window/OSX/WindowImplDelegateProtocol.h +++ b/src/SFML/Window/OSX/WindowImplDelegateProtocol.h @@ -27,24 +27,27 @@ // Headers //////////////////////////////////////////////////////////// #include // for sf::Uint8 + #include #import #if defined(__APPLE__) - #if defined(__clang__) - #pragma clang diagnostic push - #pragma clang diagnostic ignored "-Wdeprecated-declarations" - #elif defined(__GNUC__) - #pragma GCC diagnostic push - #pragma GCC diagnostic ignored "-Wdeprecated-declarations" - #endif +#if defined(__clang__) +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" +#elif defined(__GNUC__) +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wdeprecated-declarations" +#endif #endif -namespace sf { - namespace priv { - class WindowImplCocoa; - } +namespace sf +{ +namespace priv +{ +class WindowImplCocoa; +} } //////////////////////////////////////////////////////////// @@ -82,13 +85,13 @@ namespace sf { /// \return e.g. 1.0 for classic display, 2.0 for retina display /// //////////////////////////////////////////////////////////// --(CGFloat)displayScaleFactor; +- (CGFloat)displayScaleFactor; //////////////////////////////////////////////////////////// /// \brief Set the WindowImpl who requested this delegate /// //////////////////////////////////////////////////////////// --(void)setRequesterTo:(sf::priv::WindowImplCocoa*)requester; +- (void)setRequesterTo:(sf::priv::WindowImplCocoa*)requester; //////////////////////////////////////////////////////////// /// \brief Get the underlying OS specific handle @@ -96,7 +99,7 @@ namespace sf { /// \return Return the main view or window. /// //////////////////////////////////////////////////////////// --(sf::WindowHandle)getSystemHandle; +- (sf::WindowHandle)getSystemHandle; //////////////////////////////////////////////////////////// /// \brief Determine where the mouse is @@ -104,7 +107,7 @@ namespace sf { /// \return true when the mouse is inside the OpenGL view, false otherwise /// //////////////////////////////////////////////////////////// --(BOOL)isMouseInside; +- (BOOL)isMouseInside; //////////////////////////////////////////////////////////// /// \brief Grab or release the mouse cursor @@ -112,13 +115,13 @@ namespace sf { /// \param grabbed YES to grab, NO to release /// //////////////////////////////////////////////////////////// --(void)setCursorGrabbed:(BOOL)grabbed; +- (void)setCursorGrabbed:(BOOL)grabbed; //////////////////////////////////////////////////////////// /// \brief Set the system cursor for the window area /// //////////////////////////////////////////////////////////// --(void)setCursor:(NSCursor*)cursor; +- (void)setCursor:(NSCursor*)cursor; //////////////////////////////////////////////////////////// /// \brief Get window position @@ -126,7 +129,7 @@ namespace sf { /// \return Top left corner of the window or view /// //////////////////////////////////////////////////////////// --(NSPoint)position; +- (NSPoint)position; //////////////////////////////////////////////////////////// /// \brief Move the window @@ -137,7 +140,7 @@ namespace sf { /// \param y y position in SFML coordinates /// //////////////////////////////////////////////////////////// --(void)setWindowPositionToX:(int)x Y:(int)y; +- (void)setWindowPositionToX:(int)x Y:(int)y; //////////////////////////////////////////////////////////// /// \brief Get window/view's size @@ -145,7 +148,7 @@ namespace sf { /// \return the size of the rendering area /// //////////////////////////////////////////////////////////// --(NSSize)size; +- (NSSize)size; //////////////////////////////////////////////////////////// /// \brief Resize the window/view @@ -154,7 +157,7 @@ namespace sf { /// \param height new height /// //////////////////////////////////////////////////////////// --(void)resizeTo:(unsigned int)width by:(unsigned int)height; +- (void)resizeTo:(unsigned int)width by:(unsigned int)height; //////////////////////////////////////////////////////////// /// \brief Set the window's title @@ -164,7 +167,7 @@ namespace sf { /// \param title new title /// //////////////////////////////////////////////////////////// --(void)changeTitle:(NSString*)title; +- (void)changeTitle:(NSString*)title; //////////////////////////////////////////////////////////// /// \brief Hide the window @@ -172,7 +175,7 @@ namespace sf { /// Doesn't apply if the implementation is 'only' a view. /// //////////////////////////////////////////////////////////// --(void)hideWindow; +- (void)hideWindow; //////////////////////////////////////////////////////////// /// \brief Show the window @@ -180,7 +183,7 @@ namespace sf { /// Doesn't apply if the implementation is 'only' a view. /// //////////////////////////////////////////////////////////// --(void)showWindow; +- (void)showWindow; //////////////////////////////////////////////////////////// /// \brief Close the window @@ -188,14 +191,14 @@ namespace sf { /// Doesn't apply if the implementation is 'only' a view. /// //////////////////////////////////////////////////////////// --(void)closeWindow; +- (void)closeWindow; //////////////////////////////////////////////////////////// /// \brief Request the current window to be made the active /// foreground window /// //////////////////////////////////////////////////////////// --(void)requestFocus; +- (void)requestFocus; //////////////////////////////////////////////////////////// /// \brief Check whether the window has the input focus @@ -203,19 +206,19 @@ namespace sf { /// \return True if window has focus, false otherwise /// //////////////////////////////////////////////////////////// --(BOOL)hasFocus; +- (BOOL)hasFocus; //////////////////////////////////////////////////////////// /// \brief Enable key repeat /// //////////////////////////////////////////////////////////// --(void)enableKeyRepeat; +- (void)enableKeyRepeat; //////////////////////////////////////////////////////////// /// \brief Disable key repeat /// //////////////////////////////////////////////////////////// --(void)disableKeyRepeat; +- (void)disableKeyRepeat; //////////////////////////////////////////////////////////// /// \brief Set an icon to the application @@ -225,13 +228,13 @@ namespace sf { /// \param pixels icon's data /// //////////////////////////////////////////////////////////// --(void)setIconTo:(unsigned int)width by:(unsigned int)height with:(const sf::Uint8*)pixels; +- (void)setIconTo:(unsigned int)width by:(unsigned int)height with:(const sf::Uint8*)pixels; //////////////////////////////////////////////////////////// /// \brief Fetch new event /// //////////////////////////////////////////////////////////// --(void)processEvent; +- (void)processEvent; //////////////////////////////////////////////////////////// /// \brief Apply a given context to an OpenGL view @@ -239,14 +242,14 @@ namespace sf { /// \param context OpenGL context to attach to the OpenGL view /// //////////////////////////////////////////////////////////// --(void)applyContext:(NSOpenGLContext*)context; +- (void)applyContext:(NSOpenGLContext*)context; @end #if defined(__APPLE__) - #if defined(__clang__) - #pragma clang diagnostic pop - #elif defined(__GNUC__) - #pragma GCC diagnostic pop - #endif +#if defined(__clang__) +#pragma clang diagnostic pop +#elif defined(__GNUC__) +#pragma GCC diagnostic pop +#endif #endif diff --git a/src/SFML/Window/OSX/cg_sf_conversion.hpp b/src/SFML/Window/OSX/cg_sf_conversion.hpp index 311e57267..1c7ef4ec5 100644 --- a/src/SFML/Window/OSX/cg_sf_conversion.hpp +++ b/src/SFML/Window/OSX/cg_sf_conversion.hpp @@ -30,6 +30,7 @@ // Headers //////////////////////////////////////////////////////////// #include + #include namespace sf diff --git a/src/SFML/Window/OSX/cg_sf_conversion.mm b/src/SFML/Window/OSX/cg_sf_conversion.mm index 9501160aa..65361fbb3 100644 --- a/src/SFML/Window/OSX/cg_sf_conversion.mm +++ b/src/SFML/Window/OSX/cg_sf_conversion.mm @@ -26,17 +26,16 @@ //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// -#include #include - #import +#include #if defined(__APPLE__) - #if defined(__clang__) - #pragma clang diagnostic ignored "-Wdeprecated-declarations" - #elif defined(__GNUC__) - #pragma GCC diagnostic ignored "-Wdeprecated-declarations" - #endif +#if defined(__clang__) +#pragma clang diagnostic ignored "-Wdeprecated-declarations" +#elif defined(__GNUC__) +#pragma GCC diagnostic ignored "-Wdeprecated-declarations" +#endif #endif namespace sf @@ -51,11 +50,11 @@ size_t modeBitsPerPixel(CGDisplayModeRef mode) // Compare encoding. CFStringRef pixEnc = CGDisplayModeCopyPixelEncoding(mode); - if(CFStringCompare(pixEnc, CFSTR(IO32BitDirectPixels), kCFCompareCaseInsensitive) == kCFCompareEqualTo) + if (CFStringCompare(pixEnc, CFSTR(IO32BitDirectPixels), kCFCompareCaseInsensitive) == kCFCompareEqualTo) bpp = 32; - else if(CFStringCompare(pixEnc, CFSTR(IO16BitDirectPixels), kCFCompareCaseInsensitive) == kCFCompareEqualTo) + else if (CFStringCompare(pixEnc, CFSTR(IO16BitDirectPixels), kCFCompareCaseInsensitive) == kCFCompareEqualTo) bpp = 16; - else if(CFStringCompare(pixEnc, CFSTR(IO8BitIndexedPixels), kCFCompareCaseInsensitive) == kCFCompareEqualTo) + else if (CFStringCompare(pixEnc, CFSTR(IO8BitIndexedPixels), kCFCompareCaseInsensitive) == kCFCompareEqualTo) bpp = 8; // Clean up memory. @@ -95,11 +94,12 @@ VideoMode convertCGModeToSFMode(CGDisplayModeRef cgmode) // // [1]: "APIs for Supporting High Resolution" > "Additions and Changes for OS X v10.8" // https://developer.apple.com/library/mac/documentation/GraphicsAnimation/Conceptual/HighResolutionOSX/APIs/APIs.html#//apple_ref/doc/uid/TP40012302-CH5-SW27 - VideoMode mode({static_cast(CGDisplayModeGetWidth(cgmode)), static_cast(CGDisplayModeGetHeight(cgmode))}, static_cast(modeBitsPerPixel(cgmode))); + VideoMode mode({static_cast(CGDisplayModeGetWidth(cgmode)), + static_cast(CGDisplayModeGetHeight(cgmode))}, + static_cast(modeBitsPerPixel(cgmode))); scaleOutWidthHeight(mode.size.x, mode.size.y, nil); return mode; } } // namespace priv } // namespace sf - diff --git a/src/SFML/Window/OSX/cpp_objc_conversion.h b/src/SFML/Window/OSX/cpp_objc_conversion.h index 2d0f303f0..a64ed8f7a 100644 --- a/src/SFML/Window/OSX/cpp_objc_conversion.h +++ b/src/SFML/Window/OSX/cpp_objc_conversion.h @@ -27,9 +27,9 @@ // Headers //////////////////////////////////////////////////////////// #include -#include #import +#include //////////////////////////////////////////////////////////// /// \brief Returns a NSString construct with +stringWithCString:encoding: diff --git a/src/SFML/Window/OSX/cpp_objc_conversion.mm b/src/SFML/Window/OSX/cpp_objc_conversion.mm index 390e9d624..da1989aef 100644 --- a/src/SFML/Window/OSX/cpp_objc_conversion.mm +++ b/src/SFML/Window/OSX/cpp_objc_conversion.mm @@ -27,14 +27,15 @@ // Headers //////////////////////////////////////////////////////////// #include - #import + #import //////////////////////////////////////////////////////////// NSString* stringToNSString(const std::string& string) { - std::string utf8; utf8.reserve(string.size() + 1); + std::string utf8; + utf8.reserve(string.size() + 1); sf::Utf8::fromAnsi(string.begin(), string.end(), std::back_inserter(utf8)); NSString* str = [NSString stringWithCString:utf8.c_str() encoding:NSUTF8StringEncoding]; @@ -44,8 +45,8 @@ NSString* stringToNSString(const std::string& string) //////////////////////////////////////////////////////////// NSString* sfStringToNSString(const sf::String& string) { - sf::Uint32 length = static_cast(string.getSize() * sizeof(sf::Uint32)); - const void* data = reinterpret_cast(string.getData()); + sf::Uint32 length = static_cast(string.getSize() * sizeof(sf::Uint32)); + const void* data = reinterpret_cast(string.getData()); NSStringEncoding encoding; if (NSHostByteOrder() == NS_LittleEndian) diff --git a/src/SFML/Window/OpenBSD/JoystickImpl.cpp b/src/SFML/Window/OpenBSD/JoystickImpl.cpp index 58dfc829c..30f6b5004 100644 --- a/src/SFML/Window/OpenBSD/JoystickImpl.cpp +++ b/src/SFML/Window/OpenBSD/JoystickImpl.cpp @@ -39,7 +39,6 @@ void JoystickImpl::initialize() } - //////////////////////////////////////////////////////////// void JoystickImpl::cleanup() { diff --git a/src/SFML/Window/OpenBSD/JoystickImpl.hpp b/src/SFML/Window/OpenBSD/JoystickImpl.hpp index b39fdb65f..5bfe12559 100644 --- a/src/SFML/Window/OpenBSD/JoystickImpl.hpp +++ b/src/SFML/Window/OpenBSD/JoystickImpl.hpp @@ -37,7 +37,6 @@ namespace priv class JoystickImpl { public: - //////////////////////////////////////////////////////////// /// \brief Perform the global initialization of the joystick module /// @@ -101,11 +100,10 @@ public: [[nodiscard]] JoystickState update(); private: - //////////////////////////////////////////////////////////// // Member data //////////////////////////////////////////////////////////// - int m_index; ///< Index of the joystick + int m_index; ///< Index of the joystick Joystick::Identification m_identification; ///< Joystick identification }; diff --git a/src/SFML/Window/SensorImpl.hpp b/src/SFML/Window/SensorImpl.hpp index 6b5a30efe..66c1d0262 100644 --- a/src/SFML/Window/SensorImpl.hpp +++ b/src/SFML/Window/SensorImpl.hpp @@ -29,27 +29,29 @@ // Headers //////////////////////////////////////////////////////////// #include + #include #if defined(SFML_SYSTEM_WINDOWS) - #include +#include -#elif defined(SFML_SYSTEM_LINUX) || defined(SFML_SYSTEM_FREEBSD) || defined(SFML_SYSTEM_OPENBSD) || defined(SFML_SYSTEM_NETBSD) +#elif defined(SFML_SYSTEM_LINUX) || defined(SFML_SYSTEM_FREEBSD) || defined(SFML_SYSTEM_OPENBSD) || \ + defined(SFML_SYSTEM_NETBSD) - #include +#include #elif defined(SFML_SYSTEM_MACOS) - #include +#include #elif defined(SFML_SYSTEM_IOS) - #include +#include #elif defined(SFML_SYSTEM_ANDROID) - #include +#include #endif diff --git a/src/SFML/Window/SensorManager.cpp b/src/SFML/Window/SensorManager.cpp index 254fb9a43..401b6480f 100644 --- a/src/SFML/Window/SensorManager.cpp +++ b/src/SFML/Window/SensorManager.cpp @@ -25,8 +25,9 @@ //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// -#include #include +#include + #include @@ -59,7 +60,8 @@ void SensorManager::setEnabled(Sensor::Type sensor, bool enabled) } else { - err() << "Warning: trying to enable a sensor that is not available (call Sensor::isAvailable to check it)" << std::endl; + err() << "Warning: trying to enable a sensor that is not available (call Sensor::isAvailable to check it)" + << std::endl; } } diff --git a/src/SFML/Window/SensorManager.hpp b/src/SFML/Window/SensorManager.hpp index 9b8ae5d9e..1664f2638 100644 --- a/src/SFML/Window/SensorManager.hpp +++ b/src/SFML/Window/SensorManager.hpp @@ -43,7 +43,6 @@ namespace priv class SensorManager { public: - //////////////////////////////////////////////////////////// /// \brief Get the global unique instance of the manager /// @@ -98,7 +97,6 @@ public: void update(); private: - //////////////////////////////////////////////////////////// /// \brief Default constructor /// @@ -129,10 +127,10 @@ private: //////////////////////////////////////////////////////////// struct Item { - bool available; //!< Is the sensor available on this device? - bool enabled; //!< Current enable state of the sensor - SensorImpl sensor; //!< Sensor implementation - Vector3f value; //!< The current sensor value + bool available; //!< Is the sensor available on this device? + bool enabled; //!< Current enable state of the sensor + SensorImpl sensor; //!< Sensor implementation + Vector3f value; //!< The current sensor value }; //////////////////////////////////////////////////////////// diff --git a/src/SFML/Window/Touch.cpp b/src/SFML/Window/Touch.cpp index dabfd2304..674cd1623 100644 --- a/src/SFML/Window/Touch.cpp +++ b/src/SFML/Window/Touch.cpp @@ -25,8 +25,8 @@ //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// -#include #include +#include namespace sf diff --git a/src/SFML/Window/Unix/ClipboardImpl.cpp b/src/SFML/Window/Unix/ClipboardImpl.cpp index 7181d18ee..d594335c6 100644 --- a/src/SFML/Window/Unix/ClipboardImpl.cpp +++ b/src/SFML/Window/Unix/ClipboardImpl.cpp @@ -25,25 +25,27 @@ //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// -#include -#include #include #include #include +#include +#include + #include -#include + #include +#include namespace { - // Filter the events received by windows (only allow those matching a specific window) - Bool checkEvent(::Display*, XEvent* event, XPointer userData) - { - // Just check if the event matches the window - return event->xany.window == reinterpret_cast< ::Window >(userData); - } +// Filter the events received by windows (only allow those matching a specific window) +Bool checkEvent(::Display*, XEvent* event, XPointer userData) +{ + // Just check if the event matches the window + return event->xany.window == reinterpret_cast<::Window>(userData); } +} // namespace namespace sf { @@ -72,18 +74,16 @@ void ClipboardImpl::processEvents() //////////////////////////////////////////////////////////// -ClipboardImpl::ClipboardImpl() : -m_window (0), -m_requestResponded(false) +ClipboardImpl::ClipboardImpl() : m_window(0), m_requestResponded(false) { // Open a connection with the X server m_display = OpenDisplay(); // Get the atoms we need to make use of the clipboard - m_clipboard = getAtom("CLIPBOARD", false); - m_targets = getAtom("TARGETS", false); - m_text = getAtom("TEXT", false); - m_utf8String = getAtom("UTF8_STRING", true ); + m_clipboard = getAtom("CLIPBOARD", false); + m_targets = getAtom("TARGETS", false); + m_text = getAtom("TEXT", false); + m_utf8String = getAtom("UTF8_STRING", true); m_targetProperty = getAtom("SFML_CLIPBOARD_TARGET_PROPERTY", false); // Create a hidden window that will broker our clipboard interactions with X @@ -136,14 +136,7 @@ String ClipboardImpl::getStringImpl() // Request the current selection to be converted to UTF-8 (or STRING // if UTF-8 is not available) and written to our window property - XConvertSelection( - m_display, - m_clipboard, - (m_utf8String != None) ? m_utf8String : XA_STRING, - m_targetProperty, - m_window, - CurrentTime - ); + XConvertSelection(m_display, m_clipboard, (m_utf8String != None) ? m_utf8String : XA_STRING, m_targetProperty, m_window, CurrentTime); Clock clock; @@ -221,28 +214,26 @@ void ClipboardImpl::processEvent(XEvent& windowEvent) if ((selectionEvent.property == None) || (selectionEvent.selection != m_clipboard)) break; - Atom type; - int format; - unsigned long items; - unsigned long remainingBytes; + Atom type; + int format; + unsigned long items; + unsigned long remainingBytes; unsigned char* data = 0; // The selection owner should have wrote the selection // data to the specified window property - int result = XGetWindowProperty( - m_display, - m_window, - m_targetProperty, - 0, - 0x7fffffff, - False, - AnyPropertyType, - &type, - &format, - &items, - &remainingBytes, - &data - ); + int result = XGetWindowProperty(m_display, + m_window, + m_targetProperty, + 0, + 0x7fffffff, + False, + AnyPropertyType, + &type, + &format, + &items, + &remainingBytes, + &data); if (result == Success) { @@ -301,75 +292,83 @@ void ClipboardImpl::processEvent(XEvent& windowEvent) if (m_utf8String != None) targets.push_back(m_utf8String); - XChangeProperty( - m_display, - selectionRequestEvent.requestor, - selectionRequestEvent.property, - XA_ATOM, - 32, - PropModeReplace, - reinterpret_cast(targets.data()), - static_cast(targets.size()) - ); + XChangeProperty(m_display, + selectionRequestEvent.requestor, + selectionRequestEvent.property, + XA_ATOM, + 32, + PropModeReplace, + reinterpret_cast(targets.data()), + static_cast(targets.size())); // Notify the requestor that they can read the targets from their window property selectionEvent.target = m_targets; - XSendEvent(m_display, selectionRequestEvent.requestor, True, NoEventMask, reinterpret_cast(&selectionEvent)); + XSendEvent(m_display, + selectionRequestEvent.requestor, + True, + NoEventMask, + reinterpret_cast(&selectionEvent)); break; } - else if ((selectionRequestEvent.target == XA_STRING) || ((m_utf8String == None) && (selectionRequestEvent.target == m_text))) + else if ((selectionRequestEvent.target == XA_STRING) || + ((m_utf8String == None) && (selectionRequestEvent.target == m_text))) { // Respond to a request for conversion to a Latin-1 string std::string data = m_clipboardContents.toAnsiString(); - XChangeProperty( - m_display, - selectionRequestEvent.requestor, - selectionRequestEvent.property, - XA_STRING, - 8, - PropModeReplace, - reinterpret_cast(data.c_str()), - static_cast(data.size()) - ); + XChangeProperty(m_display, + selectionRequestEvent.requestor, + selectionRequestEvent.property, + XA_STRING, + 8, + PropModeReplace, + reinterpret_cast(data.c_str()), + static_cast(data.size())); // Notify the requestor that they can read the data from their window property selectionEvent.target = XA_STRING; - XSendEvent(m_display, selectionRequestEvent.requestor, True, NoEventMask, reinterpret_cast(&selectionEvent)); + XSendEvent(m_display, + selectionRequestEvent.requestor, + True, + NoEventMask, + reinterpret_cast(&selectionEvent)); break; } - else if ((m_utf8String != None) && ((selectionRequestEvent.target == m_utf8String) || (selectionRequestEvent.target == m_text))) + else if ((m_utf8String != None) && + ((selectionRequestEvent.target == m_utf8String) || (selectionRequestEvent.target == m_text))) { // Respond to a request for conversion to a UTF-8 string // or an encoding of our choosing (we always choose UTF-8) std::basic_string data = m_clipboardContents.toUtf8(); - XChangeProperty( - m_display, - selectionRequestEvent.requestor, - selectionRequestEvent.property, - m_utf8String, - 8, - PropModeReplace, - data.c_str(), - static_cast(data.size()) - ); + XChangeProperty(m_display, + selectionRequestEvent.requestor, + selectionRequestEvent.property, + m_utf8String, + 8, + PropModeReplace, + data.c_str(), + static_cast(data.size())); // Notify the requestor that they can read the data from their window property selectionEvent.target = m_utf8String; - XSendEvent(m_display, selectionRequestEvent.requestor, True, NoEventMask, reinterpret_cast(&selectionEvent)); + XSendEvent(m_display, + selectionRequestEvent.requestor, + True, + NoEventMask, + reinterpret_cast(&selectionEvent)); break; } } // Notify the requestor that we could not respond to their request - selectionEvent.target = selectionRequestEvent.target; + selectionEvent.target = selectionRequestEvent.target; selectionEvent.property = None; XSendEvent(m_display, selectionRequestEvent.requestor, True, NoEventMask, reinterpret_cast(&selectionEvent)); diff --git a/src/SFML/Window/Unix/ClipboardImpl.hpp b/src/SFML/Window/Unix/ClipboardImpl.hpp index 38e1a6761..6f21ca39b 100644 --- a/src/SFML/Window/Unix/ClipboardImpl.hpp +++ b/src/SFML/Window/Unix/ClipboardImpl.hpp @@ -30,7 +30,9 @@ //////////////////////////////////////////////////////////// #include #include // Prevent conflict with macro None from Xlib + #include + #include @@ -46,7 +48,6 @@ namespace priv class ClipboardImpl { public: - //////////////////////////////////////////////////////////// /// \brief Get the content of the clipboard as string data /// @@ -82,7 +83,6 @@ public: static void processEvents(); private: - //////////////////////////////////////////////////////////// /// \brief Constructor /// diff --git a/src/SFML/Window/Unix/CursorImpl.cpp b/src/SFML/Window/Unix/CursorImpl.cpp index f3103111c..dd3ebe74e 100644 --- a/src/SFML/Window/Unix/CursorImpl.cpp +++ b/src/SFML/Window/Unix/CursorImpl.cpp @@ -27,9 +27,11 @@ //////////////////////////////////////////////////////////// #include #include -#include -#include + #include +#include +#include + #include #include #include @@ -40,9 +42,7 @@ namespace priv { //////////////////////////////////////////////////////////// -CursorImpl::CursorImpl() : -m_display(OpenDisplay()), -m_cursor(None) +CursorImpl::CursorImpl() : m_display(OpenDisplay()), m_cursor(None) { // That's it. } @@ -74,16 +74,15 @@ bool CursorImpl::loadFromPixelsARGB(const Uint8* pixels, Vector2u size, Vector2u { // Create cursor image, convert from RGBA to ARGB. XcursorImage* cursorImage = XcursorImageCreate(static_cast(size.x), static_cast(size.y)); - cursorImage->xhot = hotspot.x; - cursorImage->yhot = hotspot.y; + cursorImage->xhot = hotspot.x; + cursorImage->yhot = hotspot.y; const std::size_t numPixels = static_cast(size.x) * static_cast(size.y); for (std::size_t pixelIndex = 0; pixelIndex < numPixels; ++pixelIndex) { - cursorImage->pixels[pixelIndex] = static_cast(pixels[pixelIndex * 4 + 2] + - (pixels[pixelIndex * 4 + 1] << 8) + - (pixels[pixelIndex * 4 + 0] << 16) + - (pixels[pixelIndex * 4 + 3] << 24)); + cursorImage->pixels[pixelIndex] = static_cast( + pixels[pixelIndex * 4 + 2] + (pixels[pixelIndex * 4 + 1] << 8) + (pixels[pixelIndex * 4 + 0] << 16) + + (pixels[pixelIndex * 4 + 3] << 24)); } // Create the cursor. @@ -104,8 +103,8 @@ bool CursorImpl::loadFromPixelsMonochrome(const Uint8* pixels, Vector2u size, Ve // The bit data is stored packed into bytes. If the number of pixels on each row of the image // does not fit exactly into (width/8) bytes, one extra byte is allocated at the end of each // row to store the extra pixels. - std::size_t packedWidth = (size.x + 7) / 8; - std::size_t bytes = packedWidth * size.y; + std::size_t packedWidth = (size.x + 7) / 8; + std::size_t bytes = packedWidth * size.y; std::vector mask(bytes, 0); // Defines which pixel is opaque (1) or transparent (0). std::vector data(bytes, 0); // Defines which pixel is white (1) or black (0). @@ -125,15 +124,21 @@ bool CursorImpl::loadFromPixelsMonochrome(const Uint8* pixels, Vector2u size, Ve // based on the pixel color intensity: on average, if a channel is "active" // at 50%, the bit is white. int intensity = (pixels[pixelIndex * 4 + 0] + pixels[pixelIndex * 4 + 1] + pixels[pixelIndex * 4 + 2]) / 3; - Uint8 bit = intensity > 128 ? 1 : 0; + Uint8 bit = intensity > 128 ? 1 : 0; data[byteIndex] |= static_cast(bit << bitIndex); } } - Pixmap maskPixmap = XCreateBitmapFromData(m_display, XDefaultRootWindow(m_display), - reinterpret_cast(mask.data()), size.x, size.y); - Pixmap dataPixmap = XCreateBitmapFromData(m_display, XDefaultRootWindow(m_display), - reinterpret_cast(data.data()), size.x, size.y); + Pixmap maskPixmap = XCreateBitmapFromData(m_display, + XDefaultRootWindow(m_display), + reinterpret_cast(mask.data()), + size.x, + size.y); + Pixmap dataPixmap = XCreateBitmapFromData(m_display, + XDefaultRootWindow(m_display), + reinterpret_cast(data.data()), + size.x, + size.y); // Define the foreground color as white and the background as black. XColor fg, bg; @@ -145,10 +150,7 @@ bool CursorImpl::loadFromPixelsMonochrome(const Uint8* pixels, Vector2u size, Ve bg.green = 0x0000; // Create the monochrome cursor. - m_cursor = XCreatePixmapCursor(m_display, - dataPixmap, maskPixmap, - &fg, &bg, - hotspot.x, hotspot.y); + m_cursor = XCreatePixmapCursor(m_display, dataPixmap, maskPixmap, &fg, &bg, hotspot.x, hotspot.y); // Free the resources XFreePixmap(m_display, dataPixmap); @@ -218,4 +220,3 @@ void CursorImpl::release() } // namespace priv } // namespace sf - diff --git a/src/SFML/Window/Unix/CursorImpl.hpp b/src/SFML/Window/Unix/CursorImpl.hpp index 74a28231a..beb4b343d 100644 --- a/src/SFML/Window/Unix/CursorImpl.hpp +++ b/src/SFML/Window/Unix/CursorImpl.hpp @@ -28,9 +28,10 @@ //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// -#include #include +#include #include // Prevent conflict with macro None from Xlib + #include namespace sf @@ -45,7 +46,6 @@ namespace priv class CursorImpl { public: - //////////////////////////////////////////////////////////// /// \brief Default constructor /// @@ -91,7 +91,6 @@ public: bool loadFromSystem(Cursor::Type type); private: - friend class WindowImplX11; //////////////////////////////////////////////////////////// diff --git a/src/SFML/Window/Unix/Display.cpp b/src/SFML/Window/Unix/Display.cpp index 9bd3165c5..140092afc 100644 --- a/src/SFML/Window/Unix/Display.cpp +++ b/src/SFML/Window/Unix/Display.cpp @@ -27,26 +27,28 @@ //////////////////////////////////////////////////////////// #include #include + #include -#include -#include -#include + #include #include +#include +#include +#include namespace { - // The shared display and its reference counter - Display* sharedDisplay = nullptr; - unsigned int referenceCount = 0; - XIM sharedXIM = nullptr; - unsigned int referenceCountXIM = 0; - std::recursive_mutex mutex; +// The shared display and its reference counter +Display* sharedDisplay = nullptr; +unsigned int referenceCount = 0; +XIM sharedXIM = nullptr; +unsigned int referenceCountXIM = 0; +std::recursive_mutex mutex; - using AtomMap = std::unordered_map; - AtomMap atoms; -} +using AtomMap = std::unordered_map; +AtomMap atoms; +} // namespace namespace sf { diff --git a/src/SFML/Window/Unix/Display.hpp b/src/SFML/Window/Unix/Display.hpp index 7071b8af1..07f36aef3 100644 --- a/src/SFML/Window/Unix/Display.hpp +++ b/src/SFML/Window/Unix/Display.hpp @@ -29,7 +29,9 @@ // Headers //////////////////////////////////////////////////////////// #include // Prevent conflict with macro None from Xlib + #include + #include diff --git a/src/SFML/Window/Unix/GlxContext.cpp b/src/SFML/Window/Unix/GlxContext.cpp index 8da58bf61..94ef9ca94 100644 --- a/src/SFML/Window/Unix/GlxContext.cpp +++ b/src/SFML/Window/Unix/GlxContext.cpp @@ -26,16 +26,14 @@ // Headers //////////////////////////////////////////////////////////// -// clang-format off -#include // important to be included first (conflict with None) -// clang-format on - -#include -#include #include +#include +#include +#include + #include -#include #include +#include // We check for this definition in order to avoid multiple definitions of GLAD // entities during unity builds of SFML. @@ -46,76 +44,73 @@ #endif #if !defined(GLX_DEBUGGING) && defined(SFML_DEBUG) - // Enable this to print messages to err() everytime GLX produces errors - //#define GLX_DEBUGGING +// Enable this to print messages to err() everytime GLX produces errors +//#define GLX_DEBUGGING #endif namespace { - std::recursive_mutex glxErrorMutex; - bool glxErrorOccurred = false; +std::recursive_mutex glxErrorMutex; +bool glxErrorOccurred = false; - //////////////////////////////////////////////////////////// - void ensureExtensionsInit(::Display* display, int screen) +//////////////////////////////////////////////////////////// +void ensureExtensionsInit(::Display* display, int screen) +{ + static bool initialized = false; + if (!initialized) { - static bool initialized = false; - if (!initialized) - { - initialized = true; + initialized = true; - // We don't check the return value since the extension - // flags are cleared even if loading fails - gladLoaderLoadGLX(display, screen); + // We don't check the return value since the extension + // flags are cleared even if loading fails + gladLoaderLoadGLX(display, screen); - gladLoadGLX(display, screen, sf::priv::GlxContext::getFunction); - } + gladLoadGLX(display, screen, sf::priv::GlxContext::getFunction); } - - - int HandleXError(::Display*, XErrorEvent*) - { - glxErrorOccurred = true; - return 0; - } - - - class GlxErrorHandler - { - public: - - GlxErrorHandler(::Display* display) : - m_lock (glxErrorMutex), - m_display(display) - { - glxErrorOccurred = false; - m_previousHandler = XSetErrorHandler(HandleXError); - } - - ~GlxErrorHandler() - { - XSync(m_display, False); - XSetErrorHandler(m_previousHandler); - } - - private: - std::scoped_lock m_lock; - ::Display* m_display; - int (*m_previousHandler)(::Display*, XErrorEvent*); - }; } +int HandleXError(::Display*, XErrorEvent*) +{ + glxErrorOccurred = true; + return 0; +} + + +class GlxErrorHandler +{ +public: + GlxErrorHandler(::Display* display) : m_lock(glxErrorMutex), m_display(display) + { + glxErrorOccurred = false; + m_previousHandler = XSetErrorHandler(HandleXError); + } + + ~GlxErrorHandler() + { + XSync(m_display, False); + XSetErrorHandler(m_previousHandler); + } + +private: + std::scoped_lock m_lock; + ::Display* m_display; + int (*m_previousHandler)(::Display*, XErrorEvent*); +}; +} // namespace + + namespace sf { namespace priv { //////////////////////////////////////////////////////////// GlxContext::GlxContext(GlxContext* shared) : -m_display (nullptr), -m_window (0), -m_context (nullptr), -m_pbuffer (0), +m_display(nullptr), +m_window(0), +m_context(nullptr), +m_pbuffer(0), m_ownsWindow(false) { // Save the creation settings @@ -137,10 +132,10 @@ m_ownsWindow(false) //////////////////////////////////////////////////////////// GlxContext::GlxContext(GlxContext* shared, const ContextSettings& settings, const WindowImpl& owner, unsigned int /*bitsPerPixel*/) : -m_display (nullptr), -m_window (0), -m_context (nullptr), -m_pbuffer (0), +m_display(nullptr), +m_window(0), +m_context(nullptr), +m_pbuffer(0), m_ownsWindow(false) { // Save the creation settings @@ -162,10 +157,10 @@ m_ownsWindow(false) //////////////////////////////////////////////////////////// GlxContext::GlxContext(GlxContext* shared, const ContextSettings& settings, const Vector2u& size) : -m_display (nullptr), -m_window (0), -m_context (nullptr), -m_pbuffer (0), +m_display(nullptr), +m_window(0), +m_context(nullptr), +m_pbuffer(0), m_ownsWindow(false) { // Save the creation settings @@ -335,12 +330,12 @@ XVisualInfo GlxContext::selectBestVisual(::Display* display, unsigned int bitsPe const int screen = DefaultScreen(display); // Retrieve all the visuals - int count; + int count; XVisualInfo* visuals = XGetVisualInfo(display, 0, nullptr, &count); if (visuals) { // Evaluate all the returned visuals, and pick the best one - int bestScore = 0x7FFFFFFF; + int bestScore = 0x7FFFFFFF; XVisualInfo bestVisual = XVisualInfo(); for (int i = 0; i < count; ++i) { @@ -356,22 +351,22 @@ XVisualInfo GlxContext::selectBestVisual(::Display* display, unsigned int bitsPe // Extract the components of the current visual int red, green, blue, alpha, depth, stencil, multiSampling, samples, sRgb; - glXGetConfig(display, &visuals[i], GLX_RED_SIZE, &red); - glXGetConfig(display, &visuals[i], GLX_GREEN_SIZE, &green); - glXGetConfig(display, &visuals[i], GLX_BLUE_SIZE, &blue); - glXGetConfig(display, &visuals[i], GLX_ALPHA_SIZE, &alpha); - glXGetConfig(display, &visuals[i], GLX_DEPTH_SIZE, &depth); + glXGetConfig(display, &visuals[i], GLX_RED_SIZE, &red); + glXGetConfig(display, &visuals[i], GLX_GREEN_SIZE, &green); + glXGetConfig(display, &visuals[i], GLX_BLUE_SIZE, &blue); + glXGetConfig(display, &visuals[i], GLX_ALPHA_SIZE, &alpha); + glXGetConfig(display, &visuals[i], GLX_DEPTH_SIZE, &depth); glXGetConfig(display, &visuals[i], GLX_STENCIL_SIZE, &stencil); if (SF_GLAD_GLX_ARB_multisample) { glXGetConfig(display, &visuals[i], GLX_SAMPLE_BUFFERS_ARB, &multiSampling); - glXGetConfig(display, &visuals[i], GLX_SAMPLES_ARB, &samples); + glXGetConfig(display, &visuals[i], GLX_SAMPLES_ARB, &samples); } else { multiSampling = 0; - samples = 0; + samples = 0; } if (SF_GLAD_GLX_EXT_framebuffer_sRGB || SF_GLAD_GLX_ARB_framebuffer_sRGB) @@ -388,12 +383,19 @@ XVisualInfo GlxContext::selectBestVisual(::Display* display, unsigned int bitsPe // Evaluate the visual int color = red + green + blue + alpha; - int score = evaluateFormat(bitsPerPixel, settings, color, depth, stencil, multiSampling ? samples : 0, accelerated, sRgb == True); + int score = evaluateFormat(bitsPerPixel, + settings, + color, + depth, + stencil, + multiSampling ? samples : 0, + accelerated, + sRgb == True); // If it's better than the current best, make it the new best if (score < bestScore) { - bestScore = score; + bestScore = score; bestVisual = visuals[i]; } } @@ -418,18 +420,18 @@ void GlxContext::updateSettingsFromVisualInfo(XVisualInfo* visualInfo) { // Update the creation settings from the chosen format int depth, stencil, multiSampling, samples, sRgb; - glXGetConfig(m_display, visualInfo, GLX_DEPTH_SIZE, &depth); + glXGetConfig(m_display, visualInfo, GLX_DEPTH_SIZE, &depth); glXGetConfig(m_display, visualInfo, GLX_STENCIL_SIZE, &stencil); if (SF_GLAD_GLX_ARB_multisample) { glXGetConfig(m_display, visualInfo, GLX_SAMPLE_BUFFERS_ARB, &multiSampling); - glXGetConfig(m_display, visualInfo, GLX_SAMPLES_ARB, &samples); + glXGetConfig(m_display, visualInfo, GLX_SAMPLES_ARB, &samples); } else { multiSampling = 0; - samples = 0; + samples = 0; } if (SF_GLAD_GLX_EXT_framebuffer_sRGB || SF_GLAD_GLX_ARB_framebuffer_sRGB) @@ -461,9 +463,9 @@ void GlxContext::updateSettingsFromWindow() // Get its visuals XVisualInfo tpl; - tpl.screen = DefaultScreen(m_display); - tpl.visualid = XVisualIDFromVisual(windowAttributes.visual); - int nbVisuals = 0; + tpl.screen = DefaultScreen(m_display); + tpl.visualid = XVisualIDFromVisual(windowAttributes.visual); + int nbVisuals = 0; XVisualInfo* visualInfo = XGetVisualInfo(m_display, VisualIDMask | VisualScreenMask, &tpl, &nbVisuals); if (!visualInfo) @@ -501,8 +503,8 @@ void GlxContext::createSurface(GlxContext* shared, const Vector2u& size, unsigne // We don't supply attributes to match against, since // the visual we are matching against was already // deemed suitable in selectBestVisual() - int nbConfigs = 0; - GLXFBConfig* configs = glXChooseFBConfig(m_display, DefaultScreen(m_display), nullptr, &nbConfigs); + int nbConfigs = 0; + GLXFBConfig* configs = glXChooseFBConfig(m_display, DefaultScreen(m_display), nullptr, &nbConfigs); for (int i = 0; configs && (i < nbConfigs); ++i) { @@ -524,11 +526,7 @@ void GlxContext::createSurface(GlxContext* shared, const Vector2u& size, unsigne if (config) { int attributes[] = - { - GLX_PBUFFER_WIDTH, static_cast(size.x), - GLX_PBUFFER_HEIGHT, static_cast(size.y), - 0, 0 - }; + {GLX_PBUFFER_WIDTH, static_cast(size.x), GLX_PBUFFER_HEIGHT, static_cast(size.y), 0, 0}; m_pbuffer = glXCreatePbuffer(m_display, *config, attributes); @@ -556,8 +554,10 @@ void GlxContext::createSurface(GlxContext* shared, const Vector2u& size, unsigne // rendering surface (unlike on Windows, for example). m_window = XCreateWindow(m_display, RootWindow(m_display, screen), - 0, 0, - size.x, size.y, + 0, + 0, + size.x, + size.y, 0, DefaultDepth(m_display, screen), InputOutput, @@ -595,13 +595,9 @@ void GlxContext::createContext(GlxContext* shared) glXQueryDrawable(m_display, m_pbuffer, GLX_FBCONFIG_ID, &fbConfigId); - int attributes[] = - { - GLX_FBCONFIG_ID, static_cast(fbConfigId), - 0, 0 - }; + int attributes[] = {GLX_FBCONFIG_ID, static_cast(fbConfigId), 0, 0}; - int count = 0; + int count = 0; GLXFBConfig* fbconfig = glXChooseFBConfig(m_display, DefaultScreen(m_display), attributes, &count); if (count == 1) @@ -622,10 +618,10 @@ void GlxContext::createContext(GlxContext* shared) // Get its visuals XVisualInfo tpl; - tpl.screen = DefaultScreen(m_display); - tpl.visualid = XVisualIDFromVisual(windowAttributes.visual); + tpl.screen = DefaultScreen(m_display); + tpl.visualid = XVisualIDFromVisual(windowAttributes.visual); int nbVisuals = 0; - visualInfo = XGetVisualInfo(m_display, VisualIDMask | VisualScreenMask, &tpl, &nbVisuals); + visualInfo = XGetVisualInfo(m_display, VisualIDMask | VisualScreenMask, &tpl, &nbVisuals); } if (!visualInfo) @@ -656,8 +652,8 @@ void GlxContext::createContext(GlxContext* shared) // We don't supply attributes to match against, since // the visual we are matching against was already // deemed suitable in selectBestVisual() - int nbConfigs = 0; - GLXFBConfig* configs = glXChooseFBConfig(m_display, DefaultScreen(m_display), nullptr, &nbConfigs); + int nbConfigs = 0; + GLXFBConfig* configs = glXChooseFBConfig(m_display, DefaultScreen(m_display), nullptr, &nbConfigs); for (int i = 0; configs && (i < nbConfigs); ++i) { @@ -695,8 +691,10 @@ void GlxContext::createContext(GlxContext* shared) // Check if setting the profile is supported if (SF_GLAD_GLX_ARB_create_context_profile) { - int profile = (m_settings.attributeFlags & ContextSettings::Core) ? GLX_CONTEXT_CORE_PROFILE_BIT_ARB : GLX_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB; - int debug = (m_settings.attributeFlags & ContextSettings::Debug) ? GLX_CONTEXT_DEBUG_BIT_ARB : 0; + int profile = (m_settings.attributeFlags & ContextSettings::Core) + ? GLX_CONTEXT_CORE_PROFILE_BIT_ARB + : GLX_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB; + int debug = (m_settings.attributeFlags & ContextSettings::Debug) ? GLX_CONTEXT_DEBUG_BIT_ARB : 0; attributes.push_back(GLX_CONTEXT_PROFILE_MASK_ARB); attributes.push_back(profile); @@ -705,7 +703,8 @@ void GlxContext::createContext(GlxContext* shared) } else { - if ((m_settings.attributeFlags & ContextSettings::Core) || (m_settings.attributeFlags & ContextSettings::Debug)) + if ((m_settings.attributeFlags & ContextSettings::Core) || + (m_settings.attributeFlags & ContextSettings::Debug)) err() << "Selecting a profile during context creation is not supported," << "disabling comptibility and debug" << std::endl; @@ -767,12 +766,12 @@ void GlxContext::createContext(GlxContext* shared) if (!m_context) { // set the context version to 2.1 (arbitrary) and disable flags - m_settings.majorVersion = 2; - m_settings.minorVersion = 1; + m_settings.majorVersion = 2; + m_settings.minorVersion = 1; m_settings.attributeFlags = ContextSettings::Default; #if defined(GLX_DEBUGGING) - GlxErrorHandler handler(m_display); + GlxErrorHandler handler(m_display); #endif if (toShare) @@ -788,8 +787,8 @@ void GlxContext::createContext(GlxContext* shared) m_context = glXCreateContext(m_display, visualInfo, toShare, true); #if defined(GLX_DEBUGGING) - if (glxErrorOccurred) - err() << "GLX error in GlxContext::createContext()" << std::endl; + if (glxErrorOccurred) + err() << "GLX error in GlxContext::createContext()" << std::endl; #endif } diff --git a/src/SFML/Window/Unix/GlxContext.hpp b/src/SFML/Window/Unix/GlxContext.hpp index 3829d941e..c59113be3 100644 --- a/src/SFML/Window/Unix/GlxContext.hpp +++ b/src/SFML/Window/Unix/GlxContext.hpp @@ -30,8 +30,9 @@ //////////////////////////////////////////////////////////// #include #include // Prevent conflict with macro None from Xlib -#include + #include +#include namespace sf @@ -45,7 +46,6 @@ namespace priv class GlxContext : public GlContext { public: - //////////////////////////////////////////////////////////// /// \brief Create a new default context /// @@ -133,7 +133,6 @@ public: static XVisualInfo selectBestVisual(::Display* display, unsigned int bitsPerPixel, const ContextSettings& settings); private: - //////////////////////////////////////////////////////////// /// \brief Update the context visual settings from XVisualInfo /// @@ -177,11 +176,11 @@ private: //////////////////////////////////////////////////////////// // Member data //////////////////////////////////////////////////////////// - ::Display* m_display; ///< Connection to the X server - ::Window m_window; ///< Window to which the context is attached - GLXContext m_context; ///< OpenGL context - GLXPbuffer m_pbuffer; ///< GLX pbuffer ID if one was created - bool m_ownsWindow; ///< Do we own the window associated to the context? + ::Display* m_display; ///< Connection to the X server + ::Window m_window; ///< Window to which the context is attached + GLXContext m_context; ///< OpenGL context + GLXPbuffer m_pbuffer; ///< GLX pbuffer ID if one was created + bool m_ownsWindow; ///< Do we own the window associated to the context? }; } // namespace priv diff --git a/src/SFML/Window/Unix/InputImpl.cpp b/src/SFML/Window/Unix/InputImpl.cpp index 2f6cad771..cf6522ca8 100644 --- a/src/SFML/Window/Unix/InputImpl.cpp +++ b/src/SFML/Window/Unix/InputImpl.cpp @@ -30,8 +30,9 @@ #include // important to be included first (conflict with None) // clang-format on -#include #include +#include + #include #include @@ -200,8 +201,8 @@ bool InputImpl::isMouseButtonPressed(Mouse::Button button) // we don't care about these but they are required ::Window root, child; - int wx, wy; - int gx, gy; + int wx, wy; + int gx, gy; unsigned int buttons = 0; XQueryPointer(display, DefaultRootWindow(display), &root, &child, &gx, &gy, &wx, &wy, &buttons); @@ -232,8 +233,8 @@ Vector2i InputImpl::getMousePosition() Display* display = OpenDisplay(); // we don't care about these but they are required - ::Window root, child; - int x, y; + ::Window root, child; + int x, y; unsigned int buttons; int gx = 0; @@ -257,8 +258,8 @@ Vector2i InputImpl::getMousePosition(const WindowBase& relativeTo) Display* display = OpenDisplay(); // we don't care about these but they are required - ::Window root, child; - int gx, gy; + ::Window root, child; + int gx, gy; unsigned int buttons; int x = 0; diff --git a/src/SFML/Window/Unix/InputImpl.hpp b/src/SFML/Window/Unix/InputImpl.hpp index 4d4f61efc..213e06d32 100644 --- a/src/SFML/Window/Unix/InputImpl.hpp +++ b/src/SFML/Window/Unix/InputImpl.hpp @@ -43,7 +43,6 @@ namespace priv class InputImpl { public: - //////////////////////////////////////////////////////////// /// \brief Check if a key is pressed /// diff --git a/src/SFML/Window/Unix/JoystickImpl.cpp b/src/SFML/Window/Unix/JoystickImpl.cpp index 89f1546e5..7dc3825bb 100644 --- a/src/SFML/Window/Unix/JoystickImpl.cpp +++ b/src/SFML/Window/Unix/JoystickImpl.cpp @@ -25,421 +25,418 @@ //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// -#include #include -#include -#include -#include -#include -#include -#include -#include -#include +#include + #include #include +#include +#include +#include +#include +#include +#include +#include +#include namespace { - udev* udevContext = 0; - udev_monitor* udevMonitor = 0; +udev* udevContext = 0; +udev_monitor* udevMonitor = 0; - struct JoystickRecord +struct JoystickRecord +{ + std::string deviceNode; + std::string systemPath; + bool plugged; +}; + +using JoystickList = std::vector; +JoystickList joystickList; + +bool isJoystick(udev_device* udevDevice) +{ + // If anything goes wrong, we go safe and return true + + // No device to check, assume not a joystick + if (!udevDevice) + return false; + + const char* devnode = udev_device_get_devnode(udevDevice); + + // We only consider devices with a device node + if (!devnode) + return false; + + // SFML doesn't support evdev yet, so make sure we only handle /js nodes + if (!std::strstr(devnode, "/js")) + return false; + + // Check if this device is a joystick + if (udev_device_get_property_value(udevDevice, "ID_INPUT_JOYSTICK")) + return true; + + // Check if this device is something that isn't a joystick + // We do this because the absence of any ID_INPUT_ property doesn't + // necessarily mean that the device isn't a joystick, whereas the + // presence of any ID_INPUT_ property that isn't ID_INPUT_JOYSTICK does + if (udev_device_get_property_value(udevDevice, "ID_INPUT_ACCELEROMETER") || + udev_device_get_property_value(udevDevice, "ID_INPUT_KEY") || + udev_device_get_property_value(udevDevice, "ID_INPUT_KEYBOARD") || + udev_device_get_property_value(udevDevice, "ID_INPUT_MOUSE") || + udev_device_get_property_value(udevDevice, "ID_INPUT_TABLET") || + udev_device_get_property_value(udevDevice, "ID_INPUT_TOUCHPAD") || + udev_device_get_property_value(udevDevice, "ID_INPUT_TOUCHSCREEN")) + return false; + + // On some platforms (older udev), ID_INPUT_ properties are not present, instead + // the system makes use of the ID_CLASS property to identify the device class + const char* idClass = udev_device_get_property_value(udevDevice, "ID_CLASS"); + + if (idClass) { - std::string deviceNode; - std::string systemPath; - bool plugged; - }; - - using JoystickList = std::vector; - JoystickList joystickList; - - bool isJoystick(udev_device* udevDevice) - { - // If anything goes wrong, we go safe and return true - - // No device to check, assume not a joystick - if (!udevDevice) - return false; - - const char* devnode = udev_device_get_devnode(udevDevice); - - // We only consider devices with a device node - if (!devnode) - return false; - - // SFML doesn't support evdev yet, so make sure we only handle /js nodes - if (!std::strstr(devnode, "/js")) - return false; - - // Check if this device is a joystick - if (udev_device_get_property_value(udevDevice, "ID_INPUT_JOYSTICK")) + // Check if the device class matches joystick + if (std::strstr(idClass, "joystick")) return true; - // Check if this device is something that isn't a joystick - // We do this because the absence of any ID_INPUT_ property doesn't - // necessarily mean that the device isn't a joystick, whereas the - // presence of any ID_INPUT_ property that isn't ID_INPUT_JOYSTICK does - if (udev_device_get_property_value(udevDevice, "ID_INPUT_ACCELEROMETER") || - udev_device_get_property_value(udevDevice, "ID_INPUT_KEY") || - udev_device_get_property_value(udevDevice, "ID_INPUT_KEYBOARD") || - udev_device_get_property_value(udevDevice, "ID_INPUT_MOUSE") || - udev_device_get_property_value(udevDevice, "ID_INPUT_TABLET") || - udev_device_get_property_value(udevDevice, "ID_INPUT_TOUCHPAD") || - udev_device_get_property_value(udevDevice, "ID_INPUT_TOUCHSCREEN")) + // Check if the device class matches something that isn't a joystick + // Rationale same as above + if (std::strstr(idClass, "accelerometer") || std::strstr(idClass, "key") || std::strstr(idClass, "keyboard") || + std::strstr(idClass, "mouse") || std::strstr(idClass, "tablet") || std::strstr(idClass, "touchpad") || + std::strstr(idClass, "touchscreen")) return false; - - // On some platforms (older udev), ID_INPUT_ properties are not present, instead - // the system makes use of the ID_CLASS property to identify the device class - const char* idClass = udev_device_get_property_value(udevDevice, "ID_CLASS"); - - if (idClass) - { - // Check if the device class matches joystick - if (std::strstr(idClass, "joystick")) - return true; - - // Check if the device class matches something that isn't a joystick - // Rationale same as above - if (std::strstr(idClass, "accelerometer") || - std::strstr(idClass, "key") || - std::strstr(idClass, "keyboard") || - std::strstr(idClass, "mouse") || - std::strstr(idClass, "tablet") || - std::strstr(idClass, "touchpad") || - std::strstr(idClass, "touchscreen")) - return false; - } - - // At this point, assume it is a joystick - return true; } - void updatePluggedList(udev_device* udevDevice = nullptr) + // At this point, assume it is a joystick + return true; +} + +void updatePluggedList(udev_device* udevDevice = nullptr) +{ + if (udevDevice) { - if (udevDevice) + const char* action = udev_device_get_action(udevDevice); + + if (action) { - const char* action = udev_device_get_action(udevDevice); - - if (action) - { - if (isJoystick(udevDevice)) - { - // Since isJoystick returned true, this has to succeed - const char* devnode = udev_device_get_devnode(udevDevice); - - JoystickList::iterator recordIt; - - for (recordIt = joystickList.begin(); recordIt != joystickList.end(); ++recordIt) - { - if (recordIt->deviceNode == devnode) - { - if (std::strstr(action, "add")) - { - // The system path might have changed so update it - const char* syspath = udev_device_get_syspath(udevDevice); - - recordIt->plugged = true; - recordIt->systemPath = syspath ? syspath : ""; - break; - } - else if (std::strstr(action, "remove")) - { - recordIt->plugged = false; - break; - } - } - } - - if (recordIt == joystickList.end()) - { - if (std::strstr(action, "add")) - { - // If not mapped before and it got added, map it now - const char* syspath = udev_device_get_syspath(udevDevice); - - JoystickRecord newRecord; - newRecord.deviceNode = devnode; - newRecord.systemPath = syspath ? syspath : ""; - newRecord.plugged = true; - - joystickList.push_back(newRecord); - } - else if (std::strstr(action, "remove")) - { - // Not mapped during the initial scan, and removed (shouldn't happen) - sf::err() << "Trying to disconnect joystick that wasn't connected" << std::endl; - } - } - } - - return; - } - - // Do a full rescan if there was no action just to be sure - } - - // Reset the plugged status of each mapping since we are doing a full rescan - for (JoystickRecord& record : joystickList) - record.plugged = false; - - udev_enumerate* udevEnumerator = udev_enumerate_new(udevContext); - - if (!udevEnumerator) - { - sf::err() << "Error while creating udev enumerator" << std::endl; - return; - } - - int result = 0; - - result = udev_enumerate_add_match_subsystem(udevEnumerator, "input"); - - if (result < 0) - { - sf::err() << "Error while adding udev enumerator match" << std::endl; - return; - } - - result = udev_enumerate_scan_devices(udevEnumerator); - - if (result < 0) - { - sf::err() << "Error while enumerating udev devices" << std::endl; - return; - } - - udev_list_entry* devices = udev_enumerate_get_list_entry(udevEnumerator); - udev_list_entry* device; - - udev_list_entry_foreach(device, devices) { - const char* syspath = udev_list_entry_get_name(device); - udev_device* newUdevDevice = udev_device_new_from_syspath(udevContext, syspath); - - if (newUdevDevice && isJoystick(newUdevDevice)) + if (isJoystick(udevDevice)) { // Since isJoystick returned true, this has to succeed - const char* devnode = udev_device_get_devnode(newUdevDevice); + const char* devnode = udev_device_get_devnode(udevDevice); JoystickList::iterator recordIt; - // Check if the device node has been mapped before for (recordIt = joystickList.begin(); recordIt != joystickList.end(); ++recordIt) { if (recordIt->deviceNode == devnode) { - recordIt->plugged = true; - break; + if (std::strstr(action, "add")) + { + // The system path might have changed so update it + const char* syspath = udev_device_get_syspath(udevDevice); + + recordIt->plugged = true; + recordIt->systemPath = syspath ? syspath : ""; + break; + } + else if (std::strstr(action, "remove")) + { + recordIt->plugged = false; + break; + } } } - // If not mapped before, map it now if (recordIt == joystickList.end()) { - JoystickRecord newRecord; - newRecord.deviceNode = devnode; - newRecord.systemPath = syspath; - newRecord.plugged = true; + if (std::strstr(action, "add")) + { + // If not mapped before and it got added, map it now + const char* syspath = udev_device_get_syspath(udevDevice); - joystickList.push_back(newRecord); + JoystickRecord newRecord; + newRecord.deviceNode = devnode; + newRecord.systemPath = syspath ? syspath : ""; + newRecord.plugged = true; + + joystickList.push_back(newRecord); + } + else if (std::strstr(action, "remove")) + { + // Not mapped during the initial scan, and removed (shouldn't happen) + sf::err() << "Trying to disconnect joystick that wasn't connected" << std::endl; + } } } - udev_device_unref(newUdevDevice); + return; } - udev_enumerate_unref(udevEnumerator); + // Do a full rescan if there was no action just to be sure } - bool hasMonitorEvent() + // Reset the plugged status of each mapping since we are doing a full rescan + for (JoystickRecord& record : joystickList) + record.plugged = false; + + udev_enumerate* udevEnumerator = udev_enumerate_new(udevContext); + + if (!udevEnumerator) { - // This will not fail since we make sure udevMonitor is valid - int monitorFd = udev_monitor_get_fd(udevMonitor); - - pollfd fds{ monitorFd, POLLIN, 0 }; - - return (poll(&fds, 1, 0) > 0) && ((fds.revents & POLLIN) != 0); + sf::err() << "Error while creating udev enumerator" << std::endl; + return; } - // Get a property value from a udev device - const char* getUdevAttribute(udev_device* udevDevice, const std::string& attributeName) + int result = 0; + + result = udev_enumerate_add_match_subsystem(udevEnumerator, "input"); + + if (result < 0) { - return udev_device_get_property_value(udevDevice, attributeName.c_str()); + sf::err() << "Error while adding udev enumerator match" << std::endl; + return; } - // Get a system attribute from a USB device - const char* getUsbAttribute(udev_device* udevDevice, const std::string& attributeName) + result = udev_enumerate_scan_devices(udevEnumerator); + + if (result < 0) { - udev_device* udevDeviceParent = udev_device_get_parent_with_subsystem_devtype(udevDevice, "usb", "usb_device"); - - if (!udevDeviceParent) - return nullptr; - - return udev_device_get_sysattr_value(udevDeviceParent, attributeName.c_str()); + sf::err() << "Error while enumerating udev devices" << std::endl; + return; } - // Get a USB attribute for a joystick as an unsigned int - unsigned int getUsbAttributeUint(udev_device* udevDevice, const std::string& attributeName) + udev_list_entry* devices = udev_enumerate_get_list_entry(udevEnumerator); + udev_list_entry* device; + + udev_list_entry_foreach(device, devices) { - if (!udevDevice) - return 0; + const char* syspath = udev_list_entry_get_name(device); + udev_device* newUdevDevice = udev_device_new_from_syspath(udevContext, syspath); - const char* attribute = getUsbAttribute(udevDevice, attributeName); - unsigned int value = 0; - - if (attribute) - value = static_cast(std::strtoul(attribute, nullptr, 16)); - - return value; - } - - // Get a udev property value for a joystick as an unsigned int - unsigned int getUdevAttributeUint(udev_device* udevDevice, const std::string& attributeName) - { - if (!udevDevice) - return 0; - - const char* attribute = getUdevAttribute(udevDevice, attributeName); - unsigned int value = 0; - - if (attribute) - value = static_cast(std::strtoul(attribute, nullptr, 16)); - - return value; - } - - // Get the joystick vendor id - unsigned int getJoystickVendorId(unsigned int index) - { - if (!udevContext) + if (newUdevDevice && isJoystick(newUdevDevice)) { - sf::err() << "Failed to get vendor ID of joystick " << joystickList[index].deviceNode << std::endl; - return 0; - } + // Since isJoystick returned true, this has to succeed + const char* devnode = udev_device_get_devnode(newUdevDevice); - udev_device* udevDevice = udev_device_new_from_syspath(udevContext, joystickList[index].systemPath.c_str()); + JoystickList::iterator recordIt; - if (!udevDevice) - { - sf::err() << "Failed to get vendor ID of joystick " << joystickList[index].deviceNode << std::endl; - return 0; - } - - unsigned int id = 0; - - // First try using udev - id = getUdevAttributeUint(udevDevice, "ID_VENDOR_ID"); - - if (id) - { - udev_device_unref(udevDevice); - return id; - } - - // Fall back to using USB attribute - id = getUsbAttributeUint(udevDevice, "idVendor"); - - udev_device_unref(udevDevice); - - if (id) - return id; - - sf::err() << "Failed to get vendor ID of joystick " << joystickList[index].deviceNode << std::endl; - - return 0; - } - - // Get the joystick product id - unsigned int getJoystickProductId(unsigned int index) - { - if (!udevContext) - { - sf::err() << "Failed to get product ID of joystick " << joystickList[index].deviceNode << std::endl; - return 0; - } - - udev_device* udevDevice = udev_device_new_from_syspath(udevContext, joystickList[index].systemPath.c_str()); - - if (!udevDevice) - { - sf::err() << "Failed to get product ID of joystick " << joystickList[index].deviceNode << std::endl; - return 0; - } - - unsigned int id = 0; - - // First try using udev - id = getUdevAttributeUint(udevDevice, "ID_MODEL_ID"); - - if (id) - { - udev_device_unref(udevDevice); - return id; - } - - // Fall back to using USB attribute - id = getUsbAttributeUint(udevDevice, "idProduct"); - - udev_device_unref(udevDevice); - - if (id) - return id; - - sf::err() << "Failed to get product ID of joystick " << joystickList[index].deviceNode << std::endl; - - return 0; - } - - // Get the joystick name - std::string getJoystickName(unsigned int index) - { - std::string devnode = joystickList[index].deviceNode; - - // First try using ioctl with JSIOCGNAME - int fd = ::open(devnode.c_str(), O_RDONLY | O_NONBLOCK); - - if (fd >= 0) - { - // Get the name - char name[128]; - std::memset(name, 0, sizeof(name)); - - int result = ioctl(fd, JSIOCGNAME(sizeof(name)), name); - - ::close(fd); - - if (result >= 0) - return std::string(name); - } - - // Fall back to manual USB chain walk via udev - if (udevContext) - { - udev_device* udevDevice = udev_device_new_from_syspath(udevContext, joystickList[index].systemPath.c_str()); - - if (udevDevice) + // Check if the device node has been mapped before + for (recordIt = joystickList.begin(); recordIt != joystickList.end(); ++recordIt) { - const char* product = getUsbAttribute(udevDevice, "product"); - udev_device_unref(udevDevice); + if (recordIt->deviceNode == devnode) + { + recordIt->plugged = true; + break; + } + } - if (product) - return std::string(product); + // If not mapped before, map it now + if (recordIt == joystickList.end()) + { + JoystickRecord newRecord; + newRecord.deviceNode = devnode; + newRecord.systemPath = syspath; + newRecord.plugged = true; + + joystickList.push_back(newRecord); } } - sf::err() << "Unable to get name for joystick " << devnode << std::endl; - - return std::string("Unknown Joystick"); + udev_device_unref(newUdevDevice); } + + udev_enumerate_unref(udevEnumerator); } +bool hasMonitorEvent() +{ + // This will not fail since we make sure udevMonitor is valid + int monitorFd = udev_monitor_get_fd(udevMonitor); + + pollfd fds{monitorFd, POLLIN, 0}; + + return (poll(&fds, 1, 0) > 0) && ((fds.revents & POLLIN) != 0); +} + +// Get a property value from a udev device +const char* getUdevAttribute(udev_device* udevDevice, const std::string& attributeName) +{ + return udev_device_get_property_value(udevDevice, attributeName.c_str()); +} + +// Get a system attribute from a USB device +const char* getUsbAttribute(udev_device* udevDevice, const std::string& attributeName) +{ + udev_device* udevDeviceParent = udev_device_get_parent_with_subsystem_devtype(udevDevice, "usb", "usb_device"); + + if (!udevDeviceParent) + return nullptr; + + return udev_device_get_sysattr_value(udevDeviceParent, attributeName.c_str()); +} + +// Get a USB attribute for a joystick as an unsigned int +unsigned int getUsbAttributeUint(udev_device* udevDevice, const std::string& attributeName) +{ + if (!udevDevice) + return 0; + + const char* attribute = getUsbAttribute(udevDevice, attributeName); + unsigned int value = 0; + + if (attribute) + value = static_cast(std::strtoul(attribute, nullptr, 16)); + + return value; +} + +// Get a udev property value for a joystick as an unsigned int +unsigned int getUdevAttributeUint(udev_device* udevDevice, const std::string& attributeName) +{ + if (!udevDevice) + return 0; + + const char* attribute = getUdevAttribute(udevDevice, attributeName); + unsigned int value = 0; + + if (attribute) + value = static_cast(std::strtoul(attribute, nullptr, 16)); + + return value; +} + +// Get the joystick vendor id +unsigned int getJoystickVendorId(unsigned int index) +{ + if (!udevContext) + { + sf::err() << "Failed to get vendor ID of joystick " << joystickList[index].deviceNode << std::endl; + return 0; + } + + udev_device* udevDevice = udev_device_new_from_syspath(udevContext, joystickList[index].systemPath.c_str()); + + if (!udevDevice) + { + sf::err() << "Failed to get vendor ID of joystick " << joystickList[index].deviceNode << std::endl; + return 0; + } + + unsigned int id = 0; + + // First try using udev + id = getUdevAttributeUint(udevDevice, "ID_VENDOR_ID"); + + if (id) + { + udev_device_unref(udevDevice); + return id; + } + + // Fall back to using USB attribute + id = getUsbAttributeUint(udevDevice, "idVendor"); + + udev_device_unref(udevDevice); + + if (id) + return id; + + sf::err() << "Failed to get vendor ID of joystick " << joystickList[index].deviceNode << std::endl; + + return 0; +} + +// Get the joystick product id +unsigned int getJoystickProductId(unsigned int index) +{ + if (!udevContext) + { + sf::err() << "Failed to get product ID of joystick " << joystickList[index].deviceNode << std::endl; + return 0; + } + + udev_device* udevDevice = udev_device_new_from_syspath(udevContext, joystickList[index].systemPath.c_str()); + + if (!udevDevice) + { + sf::err() << "Failed to get product ID of joystick " << joystickList[index].deviceNode << std::endl; + return 0; + } + + unsigned int id = 0; + + // First try using udev + id = getUdevAttributeUint(udevDevice, "ID_MODEL_ID"); + + if (id) + { + udev_device_unref(udevDevice); + return id; + } + + // Fall back to using USB attribute + id = getUsbAttributeUint(udevDevice, "idProduct"); + + udev_device_unref(udevDevice); + + if (id) + return id; + + sf::err() << "Failed to get product ID of joystick " << joystickList[index].deviceNode << std::endl; + + return 0; +} + +// Get the joystick name +std::string getJoystickName(unsigned int index) +{ + std::string devnode = joystickList[index].deviceNode; + + // First try using ioctl with JSIOCGNAME + int fd = ::open(devnode.c_str(), O_RDONLY | O_NONBLOCK); + + if (fd >= 0) + { + // Get the name + char name[128]; + std::memset(name, 0, sizeof(name)); + + int result = ioctl(fd, JSIOCGNAME(sizeof(name)), name); + + ::close(fd); + + if (result >= 0) + return std::string(name); + } + + // Fall back to manual USB chain walk via udev + if (udevContext) + { + udev_device* udevDevice = udev_device_new_from_syspath(udevContext, joystickList[index].systemPath.c_str()); + + if (udevDevice) + { + const char* product = getUsbAttribute(udevDevice, "product"); + udev_device_unref(udevDevice); + + if (product) + return std::string(product); + } + } + + sf::err() << "Unable to get name for joystick " << devnode << std::endl; + + return std::string("Unknown Joystick"); +} +} // namespace + namespace sf { namespace priv { //////////////////////////////////////////////////////////// -JoystickImpl::JoystickImpl() : -m_file(-1) +JoystickImpl::JoystickImpl() : m_file(-1) { std::fill(m_mapping, m_mapping + ABS_MAX + 1, 0); } @@ -468,7 +465,8 @@ void JoystickImpl::initialize() if (error < 0) { - err() << "Failed to add udev monitor filter, joystick connections and disconnections won't be notified: " << error << std::endl; + err() << "Failed to add udev monitor filter, joystick connections and disconnections won't be notified: " + << error << std::endl; udev_monitor_unref(udevMonitor); udevMonitor = 0; @@ -479,7 +477,8 @@ void JoystickImpl::initialize() if (error < 0) { - err() << "Failed to enable udev monitor, joystick connections and disconnections won't be notified: " << error << std::endl; + err() << "Failed to enable udev monitor, joystick connections and disconnections won't be notified: " + << error << std::endl; udev_monitor_unref(udevMonitor); udevMonitor = 0; @@ -623,7 +622,7 @@ JoystickCaps JoystickImpl::getCapabilities() const case ABS_HAT0X: caps.axes[Joystick::PovX] = true; break; case ABS_HAT0Y: caps.axes[Joystick::PovY] = true; break; default: break; - // clang-format on + // clang-format on } } @@ -649,7 +648,7 @@ JoystickState JoystickImpl::JoystickImpl::update() // pop events from the joystick file js_event joyState; - ssize_t result = read(m_file, &joyState, sizeof(joyState)); + ssize_t result = read(m_file, &joyState, sizeof(joyState)); while (result > 0) { switch (joyState.type & ~JS_EVENT_INIT) @@ -663,17 +662,34 @@ JoystickState JoystickImpl::JoystickImpl::update() { switch (m_mapping[joyState.number]) { - case ABS_X: m_state.axes[Joystick::X] = value; break; - case ABS_Y: m_state.axes[Joystick::Y] = value; break; + case ABS_X: + m_state.axes[Joystick::X] = value; + break; + case ABS_Y: + m_state.axes[Joystick::Y] = value; + break; case ABS_Z: - case ABS_THROTTLE: m_state.axes[Joystick::Z] = value; break; + case ABS_THROTTLE: + m_state.axes[Joystick::Z] = value; + break; case ABS_RZ: - case ABS_RUDDER: m_state.axes[Joystick::R] = value; break; - case ABS_RX: m_state.axes[Joystick::U] = value; break; - case ABS_RY: m_state.axes[Joystick::V] = value; break; - case ABS_HAT0X: m_state.axes[Joystick::PovX] = value; break; - case ABS_HAT0Y: m_state.axes[Joystick::PovY] = value; break; - default: break; + case ABS_RUDDER: + m_state.axes[Joystick::R] = value; + break; + case ABS_RX: + m_state.axes[Joystick::U] = value; + break; + case ABS_RY: + m_state.axes[Joystick::V] = value; + break; + case ABS_HAT0X: + m_state.axes[Joystick::PovX] = value; + break; + case ABS_HAT0Y: + m_state.axes[Joystick::PovY] = value; + break; + default: + break; } } break; diff --git a/src/SFML/Window/Unix/JoystickImpl.hpp b/src/SFML/Window/Unix/JoystickImpl.hpp index ab3049022..a4732bfea 100644 --- a/src/SFML/Window/Unix/JoystickImpl.hpp +++ b/src/SFML/Window/Unix/JoystickImpl.hpp @@ -29,6 +29,7 @@ // Headers //////////////////////////////////////////////////////////// #include + #include @@ -43,7 +44,6 @@ namespace priv class JoystickImpl { public: - //////////////////////////////////////////////////////////// /// \brief Constructor /// @@ -113,7 +113,6 @@ public: [[nodiscard]] JoystickState update(); private: - //////////////////////////////////////////////////////////// // Member data //////////////////////////////////////////////////////////// diff --git a/src/SFML/Window/Unix/SensorImpl.hpp b/src/SFML/Window/Unix/SensorImpl.hpp index bf8e0c9b4..01b0189fb 100644 --- a/src/SFML/Window/Unix/SensorImpl.hpp +++ b/src/SFML/Window/Unix/SensorImpl.hpp @@ -37,7 +37,6 @@ namespace priv class SensorImpl { public: - //////////////////////////////////////////////////////////// /// \brief Perform the global initialization of the sensor module /// diff --git a/src/SFML/Window/Unix/VideoModeImpl.cpp b/src/SFML/Window/Unix/VideoModeImpl.cpp index 118e13416..7daafdc30 100644 --- a/src/SFML/Window/Unix/VideoModeImpl.cpp +++ b/src/SFML/Window/Unix/VideoModeImpl.cpp @@ -25,11 +25,13 @@ //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// -#include -#include #include +#include +#include + #include #include + #include #include @@ -59,13 +61,13 @@ std::vector VideoModeImpl::getFullscreenModes() if (config) { // Get the available screen sizes - int nbSizes; + int nbSizes; XRRScreenSize* sizes = XRRConfigSizes(config, &nbSizes); if (sizes && (nbSizes > 0)) { // Get the list of supported depths - int nbDepths = 0; - int* depths = XListDepths(display, screen, &nbDepths); + int nbDepths = 0; + int* depths = XListDepths(display, screen, &nbDepths); if (depths && (nbDepths > 0)) { // Combine depths and sizes to fill the array of supported modes @@ -101,7 +103,8 @@ std::vector VideoModeImpl::getFullscreenModes() else { // Failed to get the screen configuration - err() << "Failed to retrieve the screen configuration while trying to get the supported video modes" << std::endl; + err() << "Failed to retrieve the screen configuration while trying to get the supported video modes" + << std::endl; } } else @@ -145,10 +148,10 @@ VideoMode VideoModeImpl::getDesktopMode() { // Get the current video mode Rotation currentRotation; - int currentMode = XRRConfigCurrentConfiguration(config, ¤tRotation); + int currentMode = XRRConfigCurrentConfiguration(config, ¤tRotation); // Get the available screen sizes - int nbSizes; + int nbSizes; XRRScreenSize* sizes = XRRConfigSizes(config, &nbSizes); if (sizes && (nbSizes > 0)) { @@ -169,7 +172,8 @@ VideoMode VideoModeImpl::getDesktopMode() else { // Failed to get the screen configuration - err() << "Failed to retrieve the screen configuration while trying to get the desktop video modes" << std::endl; + err() << "Failed to retrieve the screen configuration while trying to get the desktop video modes" + << std::endl; } } else diff --git a/src/SFML/Window/Unix/VulkanImplX11.cpp b/src/SFML/Window/Unix/VulkanImplX11.cpp index 0c5dc1ddf..620eb25a4 100644 --- a/src/SFML/Window/Unix/VulkanImplX11.cpp +++ b/src/SFML/Window/Unix/VulkanImplX11.cpp @@ -25,87 +25,88 @@ //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// -#include #include +#include + +#include #include +#include +#include #define VK_USE_PLATFORM_XLIB_KHR #define VK_NO_PROTOTYPES #include -#include -#include -#include namespace { - struct VulkanLibraryWrapper +struct VulkanLibraryWrapper +{ + VulkanLibraryWrapper() : + library(nullptr), + vkGetInstanceProcAddr(nullptr), + vkEnumerateInstanceLayerProperties(nullptr), + vkEnumerateInstanceExtensionProperties(nullptr) { - VulkanLibraryWrapper() : - library(nullptr), - vkGetInstanceProcAddr(nullptr), - vkEnumerateInstanceLayerProperties(nullptr), - vkEnumerateInstanceExtensionProperties(nullptr) - { - } + } - ~VulkanLibraryWrapper() - { - if (library) - dlclose(library); - } - - // Try to load the library and all the required entry points - bool loadLibrary() - { - if (library) - return true; - - library = dlopen("libvulkan.so.1", RTLD_LAZY); - - if (!library) - return false; - - if (!loadEntryPoint(vkGetInstanceProcAddr, "vkGetInstanceProcAddr")) - { - dlclose(library); - library = nullptr; - return false; - } - - if (!loadEntryPoint(vkEnumerateInstanceLayerProperties, "vkEnumerateInstanceLayerProperties")) - { - dlclose(library); - library = nullptr; - return false; - } - - if (!loadEntryPoint(vkEnumerateInstanceExtensionProperties, "vkEnumerateInstanceExtensionProperties")) - { - dlclose(library); - library = nullptr; - return false; - } + ~VulkanLibraryWrapper() + { + if (library) + dlclose(library); + } + // Try to load the library and all the required entry points + bool loadLibrary() + { + if (library) return true; - } - template - bool loadEntryPoint(T& entryPoint, const char* name) + library = dlopen("libvulkan.so.1", RTLD_LAZY); + + if (!library) + return false; + + if (!loadEntryPoint(vkGetInstanceProcAddr, "vkGetInstanceProcAddr")) { - entryPoint = reinterpret_cast(dlsym(library, name)); - - return (entryPoint != nullptr); + dlclose(library); + library = nullptr; + return false; } - void* library; + if (!loadEntryPoint(vkEnumerateInstanceLayerProperties, "vkEnumerateInstanceLayerProperties")) + { + dlclose(library); + library = nullptr; + return false; + } - PFN_vkGetInstanceProcAddr vkGetInstanceProcAddr; - PFN_vkEnumerateInstanceLayerProperties vkEnumerateInstanceLayerProperties; - PFN_vkEnumerateInstanceExtensionProperties vkEnumerateInstanceExtensionProperties; - }; + if (!loadEntryPoint(vkEnumerateInstanceExtensionProperties, "vkEnumerateInstanceExtensionProperties")) + { + dlclose(library); + library = nullptr; + return false; + } - VulkanLibraryWrapper wrapper; -} + return true; + } + + template + bool loadEntryPoint(T& entryPoint, const char* name) + { + entryPoint = reinterpret_cast(dlsym(library, name)); + + return (entryPoint != nullptr); + } + + void* library; + + PFN_vkGetInstanceProcAddr vkGetInstanceProcAddr; + PFN_vkEnumerateInstanceLayerProperties vkEnumerateInstanceLayerProperties; + PFN_vkEnumerateInstanceExtensionProperties vkEnumerateInstanceExtensionProperties; +}; + +VulkanLibraryWrapper wrapper; +} // namespace namespace sf @@ -115,8 +116,8 @@ namespace priv //////////////////////////////////////////////////////////// bool VulkanImplX11::isAvailable(bool requireGraphics) { - static bool checked = false; - static bool computeAvailable = false; + static bool checked = false; + static bool computeAvailable = false; static bool graphicsAvailable = false; if (!checked) @@ -143,7 +144,7 @@ bool VulkanImplX11::isAvailable(bool requireGraphics) wrapper.vkEnumerateInstanceExtensionProperties(0, &extensionCount, extensionProperties.data()); // Check if the necessary extensions are available - bool has_VK_KHR_surface = false; + bool has_VK_KHR_surface = false; bool has_VK_KHR_platform_surface = false; for (const VkExtensionProperties& properties : extensionProperties) @@ -196,7 +197,10 @@ const std::vector& VulkanImplX11::getGraphicsRequiredInstanceExtens //////////////////////////////////////////////////////////// -bool VulkanImplX11::createVulkanSurface(const VkInstance& instance, WindowHandle windowHandle, VkSurfaceKHR& surface, const VkAllocationCallbacks* allocator) +bool VulkanImplX11::createVulkanSurface(const VkInstance& instance, + WindowHandle windowHandle, + VkSurfaceKHR& surface, + const VkAllocationCallbacks* allocator) { if (!isAvailable()) return false; @@ -204,7 +208,8 @@ bool VulkanImplX11::createVulkanSurface(const VkInstance& instance, WindowHandle // Make a copy of the instance handle since we get it passed as a reference VkInstance inst = instance; - auto vkCreateXlibSurfaceKHR = reinterpret_cast(wrapper.vkGetInstanceProcAddr(inst, "vkCreateXlibSurfaceKHR")); + auto vkCreateXlibSurfaceKHR = reinterpret_cast( + wrapper.vkGetInstanceProcAddr(inst, "vkCreateXlibSurfaceKHR")); if (!vkCreateXlibSurfaceKHR) return false; @@ -212,9 +217,9 @@ bool VulkanImplX11::createVulkanSurface(const VkInstance& instance, WindowHandle // Since the surface is basically attached to the window, the connection // to the X display will stay open even after we open and close it here VkXlibSurfaceCreateInfoKHR surfaceCreateInfo = VkXlibSurfaceCreateInfoKHR(); - surfaceCreateInfo.sType = VK_STRUCTURE_TYPE_XLIB_SURFACE_CREATE_INFO_KHR; - surfaceCreateInfo.dpy = OpenDisplay(); - surfaceCreateInfo.window = windowHandle; + surfaceCreateInfo.sType = VK_STRUCTURE_TYPE_XLIB_SURFACE_CREATE_INFO_KHR; + surfaceCreateInfo.dpy = OpenDisplay(); + surfaceCreateInfo.window = windowHandle; bool result = (vkCreateXlibSurfaceKHR(instance, &surfaceCreateInfo, allocator, &surface) == VK_SUCCESS); diff --git a/src/SFML/Window/Unix/VulkanImplX11.hpp b/src/SFML/Window/Unix/VulkanImplX11.hpp index 5b89e70ab..3bb188826 100644 --- a/src/SFML/Window/Unix/VulkanImplX11.hpp +++ b/src/SFML/Window/Unix/VulkanImplX11.hpp @@ -30,6 +30,7 @@ //////////////////////////////////////////////////////////// #include #include + #include @@ -44,7 +45,6 @@ namespace priv class VulkanImplX11 { public: - //////////////////////////////////////////////////////////// /// \brief Tell whether or not the system supports Vulkan /// @@ -92,7 +92,10 @@ public: /// \return True if surface creation was successful, false otherwise /// //////////////////////////////////////////////////////////// - static bool createVulkanSurface(const VkInstance& instance, WindowHandle windowHandle, VkSurfaceKHR& surface, const VkAllocationCallbacks* allocator); + static bool createVulkanSurface(const VkInstance& instance, + WindowHandle windowHandle, + VkSurfaceKHR& surface, + const VkAllocationCallbacks* allocator); }; } // namespace priv diff --git a/src/SFML/Window/Unix/WindowImplX11.cpp b/src/SFML/Window/Unix/WindowImplX11.cpp index 47391342b..94e9dd43a 100644 --- a/src/SFML/Window/Unix/WindowImplX11.cpp +++ b/src/SFML/Window/Unix/WindowImplX11.cpp @@ -26,47 +26,45 @@ // Headers //////////////////////////////////////////////////////////// -// clang-format off -#include -// clang-format on - +#include +#include +#include +#include +#include #include #include #include -#include -#include -#include -#include -#include +#include #include #undef min // Defined by `Xlibint.h`, conflicts with standard headers #undef max // Defined by `Xlibint.h`, conflicts with standard headers -#include #include -#include +#include #include -#include -#include -#include -#include -#include +#include + #include +#include +#include +#include +#include +#include #include #include #include +#include +#include +#include #include -#include -#include -#include #ifdef SFML_OPENGL_ES - #include - using ContextType = sf::priv::EglContext; +#include +using ContextType = sf::priv::EglContext; #else - #include - using ContextType = sf::priv::GlxContext; +#include +using ContextType = sf::priv::GlxContext; #endif //////////////////////////////////////////////////////////// @@ -74,435 +72,421 @@ //////////////////////////////////////////////////////////// namespace { - // A nested named namespace is used here to allow unity builds of SFML. - namespace WindowsImplX11Impl +// A nested named namespace is used here to allow unity builds of SFML. +namespace WindowsImplX11Impl +{ +sf::priv::WindowImplX11* fullscreenWindow = nullptr; +std::vector allWindows; +std::recursive_mutex allWindowsMutex; +sf::String windowManagerName; + +sf::String wmAbsPosGood[] = {"Enlightenment", "FVWM", "i3"}; + +constexpr unsigned long eventMask = FocusChangeMask | ButtonPressMask | ButtonReleaseMask | ButtonMotionMask | + PointerMotionMask | KeyPressMask | KeyReleaseMask | StructureNotifyMask | + EnterWindowMask | LeaveWindowMask | VisibilityChangeMask | PropertyChangeMask; + +constexpr unsigned int maxTrialsCount = 5; + +// Predicate we use to find key repeat events in processEvent +struct KeyRepeatFinder +{ + KeyRepeatFinder(unsigned int initalKeycode, Time initialTime) : keycode(initalKeycode), time(initialTime) { - sf::priv::WindowImplX11* fullscreenWindow = nullptr; - std::vector allWindows; - std::recursive_mutex allWindowsMutex; - sf::String windowManagerName; - - sf::String wmAbsPosGood[] = { "Enlightenment", "FVWM", "i3" }; - - constexpr unsigned long eventMask = FocusChangeMask | ButtonPressMask | - ButtonReleaseMask | ButtonMotionMask | - PointerMotionMask | KeyPressMask | - KeyReleaseMask | StructureNotifyMask | - EnterWindowMask | LeaveWindowMask | - VisibilityChangeMask | PropertyChangeMask; - - constexpr unsigned int maxTrialsCount = 5; - - // Predicate we use to find key repeat events in processEvent - struct KeyRepeatFinder - { - KeyRepeatFinder(unsigned int initalKeycode, Time initialTime) : keycode(initalKeycode), time(initialTime) {} - - // Predicate operator that checks event type, keycode and timestamp - bool operator()(const XEvent& event) - { - return ((event.type == KeyPress) && (event.xkey.keycode == keycode) && (event.xkey.time - time < 2)); - } - - unsigned int keycode; - Time time; - }; - - // Filter the events received by windows (only allow those matching a specific window) - Bool checkEvent(::Display*, XEvent* event, XPointer userData) - { - // Just check if the event matches the window - // The input method sometimes sends ClientMessages with a different window ID, - // our event loop has to process them for the IM to work - return (event->xany.window == reinterpret_cast< ::Window >(userData)) || (event->type == ClientMessage); - } - - // Find the name of the current executable - std::filesystem::path findExecutableName() - { - // We use /proc/self/cmdline to get the command line - // the user used to invoke this instance of the application - int file = ::open("/proc/self/cmdline", O_RDONLY | O_NONBLOCK); - - if (file < 0) - return "sfml"; - - std::vector buffer(256, 0); - std::size_t offset = 0; - ssize_t result = 0; - - while ((result = read(file, &buffer[offset], 256)) > 0) - { - buffer.resize(buffer.size() + static_cast(result), 0); - offset += static_cast(result); - } - - ::close(file); - - if (offset) - { - buffer[offset] = 0; - - // Remove the path to keep the executable name only - return basename(buffer.data()); - } - - // Default fallback name - return "sfml"; - } - - // Check if Extended Window Manager Hints are supported - bool ewmhSupported() - { - static bool checked = false; - static bool ewmhSupported = false; - - if (checked) - return ewmhSupported; - - checked = true; - - Atom netSupportingWmCheck = sf::priv::getAtom("_NET_SUPPORTING_WM_CHECK", true); - Atom netSupported = sf::priv::getAtom("_NET_SUPPORTED", true); - - if (!netSupportingWmCheck || !netSupported) - return false; - - ::Display* display = sf::priv::OpenDisplay(); - - Atom actualType; - int actualFormat; - unsigned long numItems; - unsigned long numBytes; - unsigned char* data; - - int result = XGetWindowProperty(display, - DefaultRootWindow(display), - netSupportingWmCheck, - 0, - 1, - False, - XA_WINDOW, - &actualType, - &actualFormat, - &numItems, - &numBytes, - &data); - - if (result != Success || actualType != XA_WINDOW || numItems != 1) - { - if (result == Success) - XFree(data); - - sf::priv::CloseDisplay(display); - return false; - } - - #pragma GCC diagnostic push - #pragma GCC diagnostic ignored "-Wcast-align" - ::Window rootWindow = *reinterpret_cast< ::Window* >(data); - #pragma GCC diagnostic pop - - XFree(data); - - if (!rootWindow) - { - sf::priv::CloseDisplay(display); - return false; - } - - result = XGetWindowProperty(display, - rootWindow, - netSupportingWmCheck, - 0, - 1, - False, - XA_WINDOW, - &actualType, - &actualFormat, - &numItems, - &numBytes, - &data); - - if (result != Success || actualType != XA_WINDOW || numItems != 1) - { - if (result == Success) - XFree(data); - - sf::priv::CloseDisplay(display); - return false; - } - - #pragma GCC diagnostic push - #pragma GCC diagnostic ignored "-Wcast-align" - ::Window childWindow = *reinterpret_cast< ::Window* >(data); - #pragma GCC diagnostic pop - - XFree(data); - - if (!childWindow) - { - sf::priv::CloseDisplay(display); - return false; - } - - // Conforming window managers should return the same window for both queries - if (rootWindow != childWindow) - { - sf::priv::CloseDisplay(display); - return false; - } - - ewmhSupported = true; - - // We try to get the name of the window manager - // for window manager specific workarounds - Atom netWmName = sf::priv::getAtom("_NET_WM_NAME", true); - - if (!netWmName) - { - sf::priv::CloseDisplay(display); - return true; - } - - Atom utf8StringType = sf::priv::getAtom("UTF8_STRING"); - - if (!utf8StringType) - utf8StringType = XA_STRING; - - result = XGetWindowProperty(display, - rootWindow, - netWmName, - 0, - 0x7fffffff, - False, - utf8StringType, - &actualType, - &actualFormat, - &numItems, - &numBytes, - &data); - - if (actualType && numItems) - { - // It seems the wm name string reply is not necessarily - // null-terminated. The work around is to get its actual - // length to build a proper string - const char* begin = reinterpret_cast(data); - const char* end = begin + numItems; - windowManagerName = sf::String::fromUtf8(begin, end); - } - - if (result == Success) - XFree(data); - - sf::priv::CloseDisplay(display); - - return true; - } - - // Get the parent window. - ::Window getParentWindow(::Display* disp, ::Window win) - { - ::Window root, parent; - ::Window* children = nullptr; - unsigned int numChildren; - - XQueryTree(disp, win, &root, &parent, &children, &numChildren); - - // Children information is not used, so must be freed. - if (children != nullptr) - XFree(children); - - return parent; - } - - // Get the Frame Extents from EWMH WMs that support it. - bool getEWMHFrameExtents(::Display* disp, ::Window win, - long& xFrameExtent, long& yFrameExtent) - { - if (!ewmhSupported()) - return false; - - Atom frameExtents = sf::priv::getAtom("_NET_FRAME_EXTENTS", true); - - if (frameExtents == None) - return false; - - bool gotFrameExtents = false; - Atom actualType; - int actualFormat; - unsigned long numItems; - unsigned long numBytesLeft; - unsigned char* data = nullptr; - - int result = XGetWindowProperty(disp, - win, - frameExtents, - 0, - 4, - False, - XA_CARDINAL, - &actualType, - &actualFormat, - &numItems, - &numBytesLeft, - &data); - - if ((result == Success) && (actualType == XA_CARDINAL) && - (actualFormat == 32) && (numItems == 4) && (numBytesLeft == 0) && - (data != nullptr)) - { - gotFrameExtents = true; - - #pragma GCC diagnostic push - #pragma GCC diagnostic ignored "-Wcast-align" - long* extents = reinterpret_cast(data); - #pragma GCC diagnostic pop - - xFrameExtent = extents[0]; // Left. - yFrameExtent = extents[2]; // Top. - } - - // Always free data. - if (data != nullptr) - XFree(data); - - return gotFrameExtents; - } - - // Check if the current WM is in the list of good WMs that provide - // a correct absolute position for the window when queried. - bool isWMAbsolutePositionGood() - { - // This can only work with EWMH, to get the name. - if (!ewmhSupported()) - return false; - - for (const sf::String& name : wmAbsPosGood) - { - if (name == windowManagerName) - return true; - } - - return false; - } - - sf::Keyboard::Key keysymToSF(KeySym symbol) - { - // clang-format off - switch (symbol) - { - case XK_Shift_L: return sf::Keyboard::LShift; - case XK_Shift_R: return sf::Keyboard::RShift; - case XK_Control_L: return sf::Keyboard::LControl; - case XK_Control_R: return sf::Keyboard::RControl; - case XK_Alt_L: return sf::Keyboard::LAlt; - case XK_Alt_R: return sf::Keyboard::RAlt; - case XK_Super_L: return sf::Keyboard::LSystem; - case XK_Super_R: return sf::Keyboard::RSystem; - case XK_Menu: return sf::Keyboard::Menu; - case XK_Escape: return sf::Keyboard::Escape; - case XK_semicolon: return sf::Keyboard::Semicolon; - case XK_slash: return sf::Keyboard::Slash; - case XK_equal: return sf::Keyboard::Equal; - case XK_minus: return sf::Keyboard::Hyphen; - case XK_bracketleft: return sf::Keyboard::LBracket; - case XK_bracketright: return sf::Keyboard::RBracket; - case XK_comma: return sf::Keyboard::Comma; - case XK_period: return sf::Keyboard::Period; - case XK_apostrophe: return sf::Keyboard::Quote; - case XK_backslash: return sf::Keyboard::Backslash; - case XK_grave: return sf::Keyboard::Tilde; - case XK_space: return sf::Keyboard::Space; - case XK_Return: return sf::Keyboard::Enter; - case XK_KP_Enter: return sf::Keyboard::Enter; - case XK_BackSpace: return sf::Keyboard::Backspace; - case XK_Tab: return sf::Keyboard::Tab; - case XK_Prior: return sf::Keyboard::PageUp; - case XK_Next: return sf::Keyboard::PageDown; - case XK_End: return sf::Keyboard::End; - case XK_Home: return sf::Keyboard::Home; - case XK_Insert: return sf::Keyboard::Insert; - case XK_Delete: return sf::Keyboard::Delete; - case XK_KP_Add: return sf::Keyboard::Add; - case XK_KP_Subtract: return sf::Keyboard::Subtract; - case XK_KP_Multiply: return sf::Keyboard::Multiply; - case XK_KP_Divide: return sf::Keyboard::Divide; - case XK_Pause: return sf::Keyboard::Pause; - case XK_F1: return sf::Keyboard::F1; - case XK_F2: return sf::Keyboard::F2; - case XK_F3: return sf::Keyboard::F3; - case XK_F4: return sf::Keyboard::F4; - case XK_F5: return sf::Keyboard::F5; - case XK_F6: return sf::Keyboard::F6; - case XK_F7: return sf::Keyboard::F7; - case XK_F8: return sf::Keyboard::F8; - case XK_F9: return sf::Keyboard::F9; - case XK_F10: return sf::Keyboard::F10; - case XK_F11: return sf::Keyboard::F11; - case XK_F12: return sf::Keyboard::F12; - case XK_F13: return sf::Keyboard::F13; - case XK_F14: return sf::Keyboard::F14; - case XK_F15: return sf::Keyboard::F15; - case XK_Left: return sf::Keyboard::Left; - case XK_Right: return sf::Keyboard::Right; - case XK_Up: return sf::Keyboard::Up; - case XK_Down: return sf::Keyboard::Down; - case XK_KP_Insert: return sf::Keyboard::Numpad0; - case XK_KP_End: return sf::Keyboard::Numpad1; - case XK_KP_Down: return sf::Keyboard::Numpad2; - case XK_KP_Page_Down: return sf::Keyboard::Numpad3; - case XK_KP_Left: return sf::Keyboard::Numpad4; - case XK_KP_Begin: return sf::Keyboard::Numpad5; - case XK_KP_Right: return sf::Keyboard::Numpad6; - case XK_KP_Home: return sf::Keyboard::Numpad7; - case XK_KP_Up: return sf::Keyboard::Numpad8; - case XK_KP_Page_Up: return sf::Keyboard::Numpad9; - case XK_a: return sf::Keyboard::A; - case XK_b: return sf::Keyboard::B; - case XK_c: return sf::Keyboard::C; - case XK_d: return sf::Keyboard::D; - case XK_e: return sf::Keyboard::E; - case XK_f: return sf::Keyboard::F; - case XK_g: return sf::Keyboard::G; - case XK_h: return sf::Keyboard::H; - case XK_i: return sf::Keyboard::I; - case XK_j: return sf::Keyboard::J; - case XK_k: return sf::Keyboard::K; - case XK_l: return sf::Keyboard::L; - case XK_m: return sf::Keyboard::M; - case XK_n: return sf::Keyboard::N; - case XK_o: return sf::Keyboard::O; - case XK_p: return sf::Keyboard::P; - case XK_q: return sf::Keyboard::Q; - case XK_r: return sf::Keyboard::R; - case XK_s: return sf::Keyboard::S; - case XK_t: return sf::Keyboard::T; - case XK_u: return sf::Keyboard::U; - case XK_v: return sf::Keyboard::V; - case XK_w: return sf::Keyboard::W; - case XK_x: return sf::Keyboard::X; - case XK_y: return sf::Keyboard::Y; - case XK_z: return sf::Keyboard::Z; - case XK_0: return sf::Keyboard::Num0; - case XK_1: return sf::Keyboard::Num1; - case XK_2: return sf::Keyboard::Num2; - case XK_3: return sf::Keyboard::Num3; - case XK_4: return sf::Keyboard::Num4; - case XK_5: return sf::Keyboard::Num5; - case XK_6: return sf::Keyboard::Num6; - case XK_7: return sf::Keyboard::Num7; - case XK_8: return sf::Keyboard::Num8; - case XK_9: return sf::Keyboard::Num9; - } - // clang-format on - - return sf::Keyboard::Unknown; - } } + + // Predicate operator that checks event type, keycode and timestamp + bool operator()(const XEvent& event) + { + return ((event.type == KeyPress) && (event.xkey.keycode == keycode) && (event.xkey.time - time < 2)); + } + + unsigned int keycode; + Time time; +}; + +// Filter the events received by windows (only allow those matching a specific window) +Bool checkEvent(::Display*, XEvent* event, XPointer userData) +{ + // Just check if the event matches the window + // The input method sometimes sends ClientMessages with a different window ID, + // our event loop has to process them for the IM to work + return (event->xany.window == reinterpret_cast<::Window>(userData)) || (event->type == ClientMessage); } +// Find the name of the current executable +std::filesystem::path findExecutableName() +{ + // We use /proc/self/cmdline to get the command line + // the user used to invoke this instance of the application + int file = ::open("/proc/self/cmdline", O_RDONLY | O_NONBLOCK); + + if (file < 0) + return "sfml"; + + std::vector buffer(256, 0); + std::size_t offset = 0; + ssize_t result = 0; + + while ((result = read(file, &buffer[offset], 256)) > 0) + { + buffer.resize(buffer.size() + static_cast(result), 0); + offset += static_cast(result); + } + + ::close(file); + + if (offset) + { + buffer[offset] = 0; + + // Remove the path to keep the executable name only + return basename(buffer.data()); + } + + // Default fallback name + return "sfml"; +} + +// Check if Extended Window Manager Hints are supported +bool ewmhSupported() +{ + static bool checked = false; + static bool ewmhSupported = false; + + if (checked) + return ewmhSupported; + + checked = true; + + Atom netSupportingWmCheck = sf::priv::getAtom("_NET_SUPPORTING_WM_CHECK", true); + Atom netSupported = sf::priv::getAtom("_NET_SUPPORTED", true); + + if (!netSupportingWmCheck || !netSupported) + return false; + + ::Display* display = sf::priv::OpenDisplay(); + + Atom actualType; + int actualFormat; + unsigned long numItems; + unsigned long numBytes; + unsigned char* data; + + int result = XGetWindowProperty(display, + DefaultRootWindow(display), + netSupportingWmCheck, + 0, + 1, + False, + XA_WINDOW, + &actualType, + &actualFormat, + &numItems, + &numBytes, + &data); + + if (result != Success || actualType != XA_WINDOW || numItems != 1) + { + if (result == Success) + XFree(data); + + sf::priv::CloseDisplay(display); + return false; + } + +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wcast-align" + ::Window rootWindow = *reinterpret_cast<::Window*>(data); +#pragma GCC diagnostic pop + + XFree(data); + + if (!rootWindow) + { + sf::priv::CloseDisplay(display); + return false; + } + + result = XGetWindowProperty(display, + rootWindow, + netSupportingWmCheck, + 0, + 1, + False, + XA_WINDOW, + &actualType, + &actualFormat, + &numItems, + &numBytes, + &data); + + if (result != Success || actualType != XA_WINDOW || numItems != 1) + { + if (result == Success) + XFree(data); + + sf::priv::CloseDisplay(display); + return false; + } + +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wcast-align" + ::Window childWindow = *reinterpret_cast<::Window*>(data); +#pragma GCC diagnostic pop + + XFree(data); + + if (!childWindow) + { + sf::priv::CloseDisplay(display); + return false; + } + + // Conforming window managers should return the same window for both queries + if (rootWindow != childWindow) + { + sf::priv::CloseDisplay(display); + return false; + } + + ewmhSupported = true; + + // We try to get the name of the window manager + // for window manager specific workarounds + Atom netWmName = sf::priv::getAtom("_NET_WM_NAME", true); + + if (!netWmName) + { + sf::priv::CloseDisplay(display); + return true; + } + + Atom utf8StringType = sf::priv::getAtom("UTF8_STRING"); + + if (!utf8StringType) + utf8StringType = XA_STRING; + + result = XGetWindowProperty(display, + rootWindow, + netWmName, + 0, + 0x7fffffff, + False, + utf8StringType, + &actualType, + &actualFormat, + &numItems, + &numBytes, + &data); + + if (actualType && numItems) + { + // It seems the wm name string reply is not necessarily + // null-terminated. The work around is to get its actual + // length to build a proper string + const char* begin = reinterpret_cast(data); + const char* end = begin + numItems; + windowManagerName = sf::String::fromUtf8(begin, end); + } + + if (result == Success) + XFree(data); + + sf::priv::CloseDisplay(display); + + return true; +} + +// Get the parent window. +::Window getParentWindow(::Display* disp, ::Window win) +{ + ::Window root, parent; + ::Window* children = nullptr; + unsigned int numChildren; + + XQueryTree(disp, win, &root, &parent, &children, &numChildren); + + // Children information is not used, so must be freed. + if (children != nullptr) + XFree(children); + + return parent; +} + +// Get the Frame Extents from EWMH WMs that support it. +bool getEWMHFrameExtents(::Display* disp, ::Window win, long& xFrameExtent, long& yFrameExtent) +{ + if (!ewmhSupported()) + return false; + + Atom frameExtents = sf::priv::getAtom("_NET_FRAME_EXTENTS", true); + + if (frameExtents == None) + return false; + + bool gotFrameExtents = false; + Atom actualType; + int actualFormat; + unsigned long numItems; + unsigned long numBytesLeft; + unsigned char* data = nullptr; + + int result = XGetWindowProperty(disp, win, frameExtents, 0, 4, False, XA_CARDINAL, &actualType, &actualFormat, &numItems, &numBytesLeft, &data); + + if ((result == Success) && (actualType == XA_CARDINAL) && (actualFormat == 32) && (numItems == 4) && + (numBytesLeft == 0) && (data != nullptr)) + { + gotFrameExtents = true; + +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wcast-align" + long* extents = reinterpret_cast(data); +#pragma GCC diagnostic pop + + xFrameExtent = extents[0]; // Left. + yFrameExtent = extents[2]; // Top. + } + + // Always free data. + if (data != nullptr) + XFree(data); + + return gotFrameExtents; +} + +// Check if the current WM is in the list of good WMs that provide +// a correct absolute position for the window when queried. +bool isWMAbsolutePositionGood() +{ + // This can only work with EWMH, to get the name. + if (!ewmhSupported()) + return false; + + for (const sf::String& name : wmAbsPosGood) + { + if (name == windowManagerName) + return true; + } + + return false; +} + +sf::Keyboard::Key keysymToSF(KeySym symbol) +{ + // clang-format off + switch (symbol) + { + case XK_Shift_L: return sf::Keyboard::LShift; + case XK_Shift_R: return sf::Keyboard::RShift; + case XK_Control_L: return sf::Keyboard::LControl; + case XK_Control_R: return sf::Keyboard::RControl; + case XK_Alt_L: return sf::Keyboard::LAlt; + case XK_Alt_R: return sf::Keyboard::RAlt; + case XK_Super_L: return sf::Keyboard::LSystem; + case XK_Super_R: return sf::Keyboard::RSystem; + case XK_Menu: return sf::Keyboard::Menu; + case XK_Escape: return sf::Keyboard::Escape; + case XK_semicolon: return sf::Keyboard::Semicolon; + case XK_slash: return sf::Keyboard::Slash; + case XK_equal: return sf::Keyboard::Equal; + case XK_minus: return sf::Keyboard::Hyphen; + case XK_bracketleft: return sf::Keyboard::LBracket; + case XK_bracketright: return sf::Keyboard::RBracket; + case XK_comma: return sf::Keyboard::Comma; + case XK_period: return sf::Keyboard::Period; + case XK_apostrophe: return sf::Keyboard::Quote; + case XK_backslash: return sf::Keyboard::Backslash; + case XK_grave: return sf::Keyboard::Tilde; + case XK_space: return sf::Keyboard::Space; + case XK_Return: return sf::Keyboard::Enter; + case XK_KP_Enter: return sf::Keyboard::Enter; + case XK_BackSpace: return sf::Keyboard::Backspace; + case XK_Tab: return sf::Keyboard::Tab; + case XK_Prior: return sf::Keyboard::PageUp; + case XK_Next: return sf::Keyboard::PageDown; + case XK_End: return sf::Keyboard::End; + case XK_Home: return sf::Keyboard::Home; + case XK_Insert: return sf::Keyboard::Insert; + case XK_Delete: return sf::Keyboard::Delete; + case XK_KP_Add: return sf::Keyboard::Add; + case XK_KP_Subtract: return sf::Keyboard::Subtract; + case XK_KP_Multiply: return sf::Keyboard::Multiply; + case XK_KP_Divide: return sf::Keyboard::Divide; + case XK_Pause: return sf::Keyboard::Pause; + case XK_F1: return sf::Keyboard::F1; + case XK_F2: return sf::Keyboard::F2; + case XK_F3: return sf::Keyboard::F3; + case XK_F4: return sf::Keyboard::F4; + case XK_F5: return sf::Keyboard::F5; + case XK_F6: return sf::Keyboard::F6; + case XK_F7: return sf::Keyboard::F7; + case XK_F8: return sf::Keyboard::F8; + case XK_F9: return sf::Keyboard::F9; + case XK_F10: return sf::Keyboard::F10; + case XK_F11: return sf::Keyboard::F11; + case XK_F12: return sf::Keyboard::F12; + case XK_F13: return sf::Keyboard::F13; + case XK_F14: return sf::Keyboard::F14; + case XK_F15: return sf::Keyboard::F15; + case XK_Left: return sf::Keyboard::Left; + case XK_Right: return sf::Keyboard::Right; + case XK_Up: return sf::Keyboard::Up; + case XK_Down: return sf::Keyboard::Down; + case XK_KP_Insert: return sf::Keyboard::Numpad0; + case XK_KP_End: return sf::Keyboard::Numpad1; + case XK_KP_Down: return sf::Keyboard::Numpad2; + case XK_KP_Page_Down: return sf::Keyboard::Numpad3; + case XK_KP_Left: return sf::Keyboard::Numpad4; + case XK_KP_Begin: return sf::Keyboard::Numpad5; + case XK_KP_Right: return sf::Keyboard::Numpad6; + case XK_KP_Home: return sf::Keyboard::Numpad7; + case XK_KP_Up: return sf::Keyboard::Numpad8; + case XK_KP_Page_Up: return sf::Keyboard::Numpad9; + case XK_a: return sf::Keyboard::A; + case XK_b: return sf::Keyboard::B; + case XK_c: return sf::Keyboard::C; + case XK_d: return sf::Keyboard::D; + case XK_e: return sf::Keyboard::E; + case XK_f: return sf::Keyboard::F; + case XK_g: return sf::Keyboard::G; + case XK_h: return sf::Keyboard::H; + case XK_i: return sf::Keyboard::I; + case XK_j: return sf::Keyboard::J; + case XK_k: return sf::Keyboard::K; + case XK_l: return sf::Keyboard::L; + case XK_m: return sf::Keyboard::M; + case XK_n: return sf::Keyboard::N; + case XK_o: return sf::Keyboard::O; + case XK_p: return sf::Keyboard::P; + case XK_q: return sf::Keyboard::Q; + case XK_r: return sf::Keyboard::R; + case XK_s: return sf::Keyboard::S; + case XK_t: return sf::Keyboard::T; + case XK_u: return sf::Keyboard::U; + case XK_v: return sf::Keyboard::V; + case XK_w: return sf::Keyboard::W; + case XK_x: return sf::Keyboard::X; + case XK_y: return sf::Keyboard::Y; + case XK_z: return sf::Keyboard::Z; + case XK_0: return sf::Keyboard::Num0; + case XK_1: return sf::Keyboard::Num1; + case XK_2: return sf::Keyboard::Num2; + case XK_3: return sf::Keyboard::Num3; + case XK_4: return sf::Keyboard::Num4; + case XK_5: return sf::Keyboard::Num5; + case XK_6: return sf::Keyboard::Num6; + case XK_7: return sf::Keyboard::Num7; + case XK_8: return sf::Keyboard::Num8; + case XK_9: return sf::Keyboard::Num9; + } + // clang-format on + + return sf::Keyboard::Unknown; +} +} // namespace WindowsImplX11Impl +} // namespace + namespace sf { @@ -510,24 +494,24 @@ namespace priv { //////////////////////////////////////////////////////////// WindowImplX11::WindowImplX11(WindowHandle handle) : -m_window (0), -m_screen (0), -m_inputMethod (nullptr), -m_inputContext (nullptr), -m_isExternal (true), -m_oldVideoMode (0), -m_oldRRCrtc (0), -m_hiddenCursor (0), -m_lastCursor (None), -m_keyRepeat (true), -m_previousSize (-1, -1), -m_useSizeHints (false), -m_fullscreen (false), -m_cursorGrabbed (false), -m_windowMapped (false), -m_iconPixmap (0), -m_iconMaskPixmap (0), -m_lastInputTime (0) +m_window(0), +m_screen(0), +m_inputMethod(nullptr), +m_inputContext(nullptr), +m_isExternal(true), +m_oldVideoMode(0), +m_oldRRCrtc(0), +m_hiddenCursor(0), +m_lastCursor(None), +m_keyRepeat(true), +m_previousSize(-1, -1), +m_useSizeHints(false), +m_fullscreen(false), +m_cursorGrabbed(false), +m_windowMapped(false), +m_iconPixmap(0), +m_iconMaskPixmap(0), +m_lastInputTime(0) { using namespace WindowsImplX11Impl; @@ -561,24 +545,24 @@ m_lastInputTime (0) //////////////////////////////////////////////////////////// WindowImplX11::WindowImplX11(VideoMode mode, const String& title, unsigned long style, const ContextSettings& settings) : -m_window (0), -m_screen (0), -m_inputMethod (nullptr), -m_inputContext (nullptr), -m_isExternal (false), -m_oldVideoMode (0), -m_oldRRCrtc (0), -m_hiddenCursor (0), -m_lastCursor (None), -m_keyRepeat (true), -m_previousSize (-1, -1), -m_useSizeHints (false), -m_fullscreen ((style & Style::Fullscreen) != 0), -m_cursorGrabbed (m_fullscreen), -m_windowMapped (false), -m_iconPixmap (0), -m_iconMaskPixmap (0), -m_lastInputTime (0) +m_window(0), +m_screen(0), +m_inputMethod(nullptr), +m_inputContext(nullptr), +m_isExternal(false), +m_oldVideoMode(0), +m_oldRRCrtc(0), +m_hiddenCursor(0), +m_lastCursor(None), +m_keyRepeat(true), +m_previousSize(-1, -1), +m_useSizeHints(false), +m_fullscreen((style & Style::Fullscreen) != 0), +m_cursorGrabbed(m_fullscreen), +m_windowMapped(false), +m_iconPixmap(0), +m_iconMaskPixmap(0), +m_lastInputTime(0) { using namespace WindowsImplX11Impl; @@ -592,7 +576,7 @@ m_lastInputTime (0) // Compute position and size Vector2i windowPosition; - if(m_fullscreen) + if (m_fullscreen) { windowPosition = getPrimaryMonitorPosition(); } @@ -606,14 +590,14 @@ m_lastInputTime (0) unsigned int height = mode.size.y; Visual* visual = nullptr; - int depth = 0; + int depth = 0; // Check if the user chose to not create an OpenGL context (settings.attributeFlags will be 0xFFFFFFFF) if (settings.attributeFlags == 0xFFFFFFFF) { // Choose default visual since the user is going to use their own rendering API visual = DefaultVisual(m_display, m_screen); - depth = DefaultDepth(m_display, m_screen); + depth = DefaultDepth(m_display, m_screen); } else { @@ -621,19 +605,21 @@ m_lastInputTime (0) XVisualInfo visualInfo = ContextType::selectBestVisual(m_display, mode.bitsPerPixel, settings); visual = visualInfo.visual; - depth = visualInfo.depth; + depth = visualInfo.depth; } // Define the window attributes XSetWindowAttributes attributes; - attributes.colormap = XCreateColormap(m_display, DefaultRootWindow(m_display), visual, AllocNone); - attributes.event_mask = eventMask; + attributes.colormap = XCreateColormap(m_display, DefaultRootWindow(m_display), visual, AllocNone); + attributes.event_mask = eventMask; attributes.override_redirect = (m_fullscreen && !ewmhSupported()) ? True : False; m_window = XCreateWindow(m_display, DefaultRootWindow(m_display), - windowPosition.x, windowPosition.y, - width, height, + windowPosition.x, + windowPosition.y, + width, + height, 0, depth, InputOutput, @@ -651,7 +637,7 @@ m_lastInputTime (0) setProtocols(); // Set the WM initial state to the normal state - XWMHints* xHints = XAllocWMHints(); + XWMHints* xHints = XAllocWMHints(); xHints->flags = StateHint; xHints->initial_state = NormalState; XSetWMHints(m_display, m_window, xHints); @@ -668,19 +654,19 @@ m_lastInputTime (0) constexpr unsigned long MWM_HINTS_DECORATIONS = 1 << 1; //constexpr unsigned long MWM_DECOR_ALL = 1 << 0; - constexpr unsigned long MWM_DECOR_BORDER = 1 << 1; - constexpr unsigned long MWM_DECOR_RESIZEH = 1 << 2; - constexpr unsigned long MWM_DECOR_TITLE = 1 << 3; - constexpr unsigned long MWM_DECOR_MENU = 1 << 4; - constexpr unsigned long MWM_DECOR_MINIMIZE = 1 << 5; - constexpr unsigned long MWM_DECOR_MAXIMIZE = 1 << 6; + constexpr unsigned long MWM_DECOR_BORDER = 1 << 1; + constexpr unsigned long MWM_DECOR_RESIZEH = 1 << 2; + constexpr unsigned long MWM_DECOR_TITLE = 1 << 3; + constexpr unsigned long MWM_DECOR_MENU = 1 << 4; + constexpr unsigned long MWM_DECOR_MINIMIZE = 1 << 5; + constexpr unsigned long MWM_DECOR_MAXIMIZE = 1 << 6; //constexpr unsigned long MWM_FUNC_ALL = 1 << 0; - constexpr unsigned long MWM_FUNC_RESIZE = 1 << 1; - constexpr unsigned long MWM_FUNC_MOVE = 1 << 2; - constexpr unsigned long MWM_FUNC_MINIMIZE = 1 << 3; - constexpr unsigned long MWM_FUNC_MAXIMIZE = 1 << 4; - constexpr unsigned long MWM_FUNC_CLOSE = 1 << 5; + constexpr unsigned long MWM_FUNC_RESIZE = 1 << 1; + constexpr unsigned long MWM_FUNC_MOVE = 1 << 2; + constexpr unsigned long MWM_FUNC_MINIMIZE = 1 << 3; + constexpr unsigned long MWM_FUNC_MAXIMIZE = 1 << 4; + constexpr unsigned long MWM_FUNC_CLOSE = 1 << 5; struct WMHints { @@ -700,17 +686,17 @@ m_lastInputTime (0) if (style & Style::Titlebar) { hints.decorations |= MWM_DECOR_BORDER | MWM_DECOR_TITLE | MWM_DECOR_MINIMIZE | MWM_DECOR_MENU; - hints.functions |= MWM_FUNC_MOVE | MWM_FUNC_MINIMIZE; + hints.functions |= MWM_FUNC_MOVE | MWM_FUNC_MINIMIZE; } if (style & Style::Resize) { hints.decorations |= MWM_DECOR_MAXIMIZE | MWM_DECOR_RESIZEH; - hints.functions |= MWM_FUNC_MAXIMIZE | MWM_FUNC_RESIZE; + hints.functions |= MWM_FUNC_MAXIMIZE | MWM_FUNC_RESIZE; } if (style & Style::Close) { hints.decorations |= 0; - hints.functions |= MWM_FUNC_CLOSE; + hints.functions |= MWM_FUNC_CLOSE; } XChangeProperty(m_display, @@ -727,13 +713,13 @@ m_lastInputTime (0) // This is a hack to force some windows managers to disable resizing if (!(style & Style::Resize)) { - m_useSizeHints = true; + m_useSizeHints = true; XSizeHints* sizeHints = XAllocSizeHints(); - sizeHints->flags = PMinSize | PMaxSize | USPosition; - sizeHints->min_width = sizeHints->max_width = static_cast(width); + sizeHints->flags = PMinSize | PMaxSize | USPosition; + sizeHints->min_width = sizeHints->max_width = static_cast(width); sizeHints->min_height = sizeHints->max_height = static_cast(height); - sizeHints->x = windowPosition.x; - sizeHints->y = windowPosition.y; + sizeHints->x = windowPosition.x; + sizeHints->y = windowPosition.y; XSetWMNormalHints(m_display, m_window, sizeHints); XFree(sizeHints); } @@ -744,7 +730,7 @@ m_lastInputTime (0) // The instance name should be something unique to this invocation // of the application but is rarely if ever used these days. // For simplicity, we retrieve it via the base executable name. - std::string executableName = findExecutableName().string(); + std::string executableName = findExecutableName().string(); std::vector windowInstance(executableName.size() + 1, 0); std::copy(executableName.begin(), executableName.end(), windowInstance.begin()); hint->res_name = windowInstance.data(); @@ -752,7 +738,7 @@ m_lastInputTime (0) // The class name identifies a class of windows that // "are of the same type". We simply use the initial window name as // the class name. - std::string ansiTitle = title.toAnsiString(); + std::string ansiTitle = title.toAnsiString(); std::vector windowClass(ansiTitle.size() + 1, 0); std::copy(ansiTitle.begin(), ansiTitle.end(), windowClass.begin()); hint->res_class = windowClass.data(); @@ -772,8 +758,8 @@ m_lastInputTime (0) { // Disable hint for min and max size, // otherwise some windows managers will not remove window decorations - XSizeHints *sizeHints = XAllocSizeHints(); - long flags = 0; + XSizeHints* sizeHints = XAllocSizeHints(); + long flags = 0; XGetWMNormalHints(m_display, m_window, sizeHints, &flags); sizeHints->flags &= ~(PMinSize | PMaxSize); XSetWMNormalHints(m_display, m_window, sizeHints); @@ -872,10 +858,9 @@ Vector2i WindowImplX11::getPosition() const // go using setPosition() and XMoveWindow(). To have the two match // as expected, we may have to subtract decorations and borders. ::Window child; - int xAbsRelToRoot, yAbsRelToRoot; + int xAbsRelToRoot, yAbsRelToRoot; - XTranslateCoordinates(m_display, m_window, DefaultRootWindow(m_display), - 0, 0, &xAbsRelToRoot, &yAbsRelToRoot, &child); + XTranslateCoordinates(m_display, m_window, DefaultRootWindow(m_display), 0, 0, &xAbsRelToRoot, &yAbsRelToRoot, &child); // CASE 1: some rare WMs actually put the window exactly where we tell // it to, even with decorations and such, which get shifted back. @@ -909,7 +894,7 @@ Vector2i WindowImplX11::getPosition() const // our window is part of decorations/borders in some way. This // seems to hold true for most reasonable WM implementations. ::Window ancestor = m_window; - ::Window root = DefaultRootWindow(m_display); + ::Window root = DefaultRootWindow(m_display); while (getParentWindow(m_display, ancestor) != root) { @@ -919,11 +904,10 @@ Vector2i WindowImplX11::getPosition() const // Get final X/Y coordinates: take the relative position to // the root of the furthest ancestor window. - int xRelToRoot, yRelToRoot; + int xRelToRoot, yRelToRoot; unsigned int width, height, borderWidth, depth; - XGetGeometry(m_display, ancestor, &root, &xRelToRoot, &yRelToRoot, - &width, &height, &borderWidth, &depth); + XGetGeometry(m_display, ancestor, &root, &xRelToRoot, &yRelToRoot, &width, &height, &borderWidth, &depth); return Vector2i(xRelToRoot, yRelToRoot); } @@ -953,8 +937,8 @@ void WindowImplX11::setSize(const Vector2u& size) if (m_useSizeHints) { XSizeHints* sizeHints = XAllocSizeHints(); - sizeHints->flags = PMinSize | PMaxSize; - sizeHints->min_width = sizeHints->max_width = static_cast(size.x); + sizeHints->flags = PMinSize | PMaxSize; + sizeHints->min_width = sizeHints->max_width = static_cast(size.x); sizeHints->min_height = sizeHints->max_height = static_cast(size.y); XSetWMNormalHints(m_display, m_window, sizeHints); XFree(sizeHints); @@ -979,16 +963,28 @@ void WindowImplX11::setTitle(const String& title) // Set the _NET_WM_NAME atom, which specifies a UTF-8 encoded window title. Atom wmName = getAtom("_NET_WM_NAME", false); - XChangeProperty(m_display, m_window, wmName, useUtf8, 8, - PropModeReplace, utf8Title.c_str(), static_cast(utf8Title.size())); + XChangeProperty(m_display, + m_window, + wmName, + useUtf8, + 8, + PropModeReplace, + utf8Title.c_str(), + static_cast(utf8Title.size())); // Set the _NET_WM_ICON_NAME atom, which specifies a UTF-8 encoded window title. Atom wmIconName = getAtom("_NET_WM_ICON_NAME", false); - XChangeProperty(m_display, m_window, wmIconName, useUtf8, 8, - PropModeReplace, utf8Title.c_str(), static_cast(utf8Title.size())); + XChangeProperty(m_display, + m_window, + wmIconName, + useUtf8, + 8, + PropModeReplace, + utf8Title.c_str(), + static_cast(utf8Title.size())); - // Set the non-Unicode title as a fallback for window managers who don't support _NET_WM_NAME. - #ifdef X_HAVE_UTF8_STRING +// Set the non-Unicode title as a fallback for window managers who don't support _NET_WM_NAME. +#ifdef X_HAVE_UTF8_STRING Xutf8SetWMProperties(m_display, m_window, title.toAnsiString().c_str(), @@ -998,17 +994,9 @@ void WindowImplX11::setTitle(const String& title) nullptr, nullptr, nullptr); - #else - XmbSetWMProperties(m_display, - m_window, - title.toAnsiString().c_str(), - title.toAnsiString().c_str(), - nullptr, - 0, - nullptr, - nullptr, - nullptr); - #endif +#else + XmbSetWMProperties(m_display, m_window, title.toAnsiString().c_str(), title.toAnsiString().c_str(), nullptr, 0, nullptr, nullptr, nullptr); +#endif } @@ -1017,7 +1005,8 @@ void WindowImplX11::setIcon(const Vector2u& size, const Uint8* pixels) { // X11 wants BGRA pixels: swap red and blue channels // Note: this memory will be freed by XDestroyImage - auto* iconPixels = static_cast(std::malloc(static_cast(size.x) * static_cast(size.y) * 4)); + auto* iconPixels = static_cast( + std::malloc(static_cast(size.x) * static_cast(size.y) * 4)); for (std::size_t i = 0; i < static_cast(size.x) * static_cast(size.y); ++i) { iconPixels[i * 4 + 0] = pixels[i * 4 + 2]; @@ -1027,9 +1016,18 @@ void WindowImplX11::setIcon(const Vector2u& size, const Uint8* pixels) } // Create the icon pixmap - Visual* defVisual = DefaultVisual(m_display, m_screen); - auto defDepth = static_cast(DefaultDepth(m_display, m_screen)); - XImage* iconImage = XCreateImage(m_display, defVisual, defDepth, ZPixmap, 0, reinterpret_cast(iconPixels), size.x, size.y, 32, 0); + Visual* defVisual = DefaultVisual(m_display, m_screen); + auto defDepth = static_cast(DefaultDepth(m_display, m_screen)); + XImage* iconImage = XCreateImage(m_display, + defVisual, + defDepth, + ZPixmap, + 0, + reinterpret_cast(iconPixels), + size.x, + size.y, + 32, + 0); if (!iconImage) { err() << "Failed to set the window's icon" << std::endl; @@ -1044,13 +1042,13 @@ void WindowImplX11::setIcon(const Vector2u& size, const Uint8* pixels) m_iconPixmap = XCreatePixmap(m_display, RootWindow(m_display, m_screen), size.x, size.y, defDepth); XGCValues values; - GC iconGC = XCreateGC(m_display, m_iconPixmap, 0, &values); + GC iconGC = XCreateGC(m_display, m_iconPixmap, 0, &values); XPutImage(m_display, m_iconPixmap, iconGC, iconImage, 0, 0, 0, 0, size.x, size.y); XFreeGC(m_display, iconGC); XDestroyImage(iconImage); // Create the mask pixmap (must have 1 bit depth) - std::size_t pitch = (size.x + 7) / 8; + std::size_t pitch = (size.x + 7) / 8; std::vector maskPixels(pitch * size.y, 0); for (std::size_t j = 0; j < size.y; ++j) { @@ -1066,10 +1064,17 @@ void WindowImplX11::setIcon(const Vector2u& size, const Uint8* pixels) } } } - m_iconMaskPixmap = XCreatePixmapFromBitmapData(m_display, m_window, reinterpret_cast(maskPixels.data()), size.x, size.y, 1, 0, 1); + m_iconMaskPixmap = XCreatePixmapFromBitmapData(m_display, + m_window, + reinterpret_cast(maskPixels.data()), + size.x, + size.y, + 1, + 0, + 1); // Send our new icon to the window through the WMHints - XWMHints* hints = XAllocWMHints(); + XWMHints* hints = XAllocWMHints(); hints->flags = IconPixmapHint | IconMaskHint; hints->icon_pixmap = m_iconPixmap; hints->icon_mask = m_iconMaskPixmap; @@ -1079,20 +1084,18 @@ void WindowImplX11::setIcon(const Vector2u& size, const Uint8* pixels) // ICCCM wants BGRA pixels: swap red and blue channels // ICCCM also wants the first 2 unsigned 32-bit values to be width and height std::vector icccmIconPixels(2 + size.x * size.y, 0); - unsigned long* ptr = icccmIconPixels.data(); + unsigned long* ptr = icccmIconPixels.data(); - #pragma GCC diagnostic push - #pragma GCC diagnostic ignored "-Wnull-dereference" // False positive. +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wnull-dereference" // False positive. *ptr++ = size.x; *ptr++ = size.y; - #pragma GCC diagnostic pop +#pragma GCC diagnostic pop for (std::size_t i = 0; i < static_cast(size.x) * static_cast(size.y); ++i) { - *ptr++ = static_cast((pixels[i * 4 + 2] << 0 ) | - (pixels[i * 4 + 1] << 8 ) | - (pixels[i * 4 + 0] << 16) | - (pixels[i * 4 + 3] << 24)); + *ptr++ = static_cast( + (pixels[i * 4 + 2] << 0) | (pixels[i * 4 + 1] << 8) | (pixels[i * 4 + 0] << 16) | (pixels[i * 4 + 3] << 24)); } Atom netWmIcon = getAtom("_NET_WM_ICON"); @@ -1117,7 +1120,7 @@ void WindowImplX11::setVisible(bool visible) { XMapWindow(m_display, m_window); - if(m_fullscreen) + if (m_fullscreen) switchToFullscreen(); XFlush(m_display); @@ -1261,8 +1264,8 @@ void WindowImplX11::requestFocus() //////////////////////////////////////////////////////////// bool WindowImplX11::hasFocus() const { - ::Window focusedWindow = 0; - int revertToReturn = 0; + ::Window focusedWindow = 0; + int revertToReturn = 0; XGetInputFocus(m_display, &focusedWindow, &revertToReturn); return (m_window == focusedWindow); @@ -1292,13 +1295,13 @@ void WindowImplX11::grabFocus() XEvent event; std::memset(&event, 0, sizeof(event)); - event.type = ClientMessage; - event.xclient.window = m_window; - event.xclient.format = 32; + event.type = ClientMessage; + event.xclient.window = m_window; + event.xclient.format = 32; event.xclient.message_type = netActiveWindow; - event.xclient.data.l[0] = 1; // Normal application - event.xclient.data.l[1] = static_cast(m_lastInputTime); - event.xclient.data.l[2] = 0; // We don't know the currently active window + event.xclient.data.l[0] = 1; // Normal application + event.xclient.data.l[1] = static_cast(m_lastInputTime); + event.xclient.data.l[2] = 0; // We don't know the currently active window int result = XSendEvent(m_display, DefaultRootWindow(m_display), @@ -1376,7 +1379,7 @@ void WindowImplX11::setVideoMode(const VideoMode& mode) } // Find RRMode to set - bool modeFound = false; + bool modeFound = false; RRMode xRandMode; for (int i = 0; (i < res->nmode) && !modeFound; ++i) @@ -1385,8 +1388,7 @@ void WindowImplX11::setVideoMode(const VideoMode& mode) std::swap(res->modes[i].height, res->modes[i].width); // Check if screen size match - if ((res->modes[i].width == mode.size.x) && - (res->modes[i].height == mode.size.y)) + if ((res->modes[i].width == mode.size.x) && (res->modes[i].height == mode.size.y)) { xRandMode = res->modes[i].id; modeFound = true; @@ -1403,19 +1405,10 @@ void WindowImplX11::setVideoMode(const VideoMode& mode) // Save the current video mode before we switch to fullscreen m_oldVideoMode = crtcInfo->mode; - m_oldRRCrtc = outputInfo->crtc; + m_oldRRCrtc = outputInfo->crtc; // Switch to fullscreen mode - XRRSetCrtcConfig(m_display, - res, - outputInfo->crtc, - CurrentTime, - crtcInfo->x, - crtcInfo->y, - xRandMode, - crtcInfo->rotation, - &output, - 1); + XRRSetCrtcConfig(m_display, res, outputInfo->crtc, CurrentTime, crtcInfo->x, crtcInfo->y, xRandMode, crtcInfo->rotation, &output, 1); // Set "this" as the current fullscreen window fullscreenWindow = this; @@ -1465,7 +1458,8 @@ void WindowImplX11::resetVideoMode() if (output == None) output = res->outputs[0]; } - else{ + else + { output = res->outputs[0]; } @@ -1515,7 +1509,7 @@ void WindowImplX11::switchToFullscreen() 1); } - Atom netWmState = getAtom("_NET_WM_STATE", true); + Atom netWmState = getAtom("_NET_WM_STATE", true); Atom netWmStateFullscreen = getAtom("_NET_WM_STATE_FULLSCREEN", true); if (!netWmState || !netWmStateFullscreen) @@ -1527,14 +1521,14 @@ void WindowImplX11::switchToFullscreen() XEvent event; std::memset(&event, 0, sizeof(event)); - event.type = ClientMessage; - event.xclient.window = m_window; - event.xclient.format = 32; + event.type = ClientMessage; + event.xclient.window = m_window; + event.xclient.format = 32; event.xclient.message_type = netWmState; - event.xclient.data.l[0] = 1; // _NET_WM_STATE_ADD - event.xclient.data.l[1] = static_cast(netWmStateFullscreen); - event.xclient.data.l[2] = 0; // No second property - event.xclient.data.l[3] = 1; // Normal window + event.xclient.data.l[0] = 1; // _NET_WM_STATE_ADD + event.xclient.data.l[1] = static_cast(netWmStateFullscreen); + event.xclient.data.l[2] = 0; // No second property + event.xclient.data.l[3] = 1; // Normal window int result = XSendEvent(m_display, DefaultRootWindow(m_display), @@ -1553,7 +1547,7 @@ void WindowImplX11::setProtocols() { using namespace WindowsImplX11Impl; - Atom wmProtocols = getAtom("WM_PROTOCOLS"); + Atom wmProtocols = getAtom("WM_PROTOCOLS"); Atom wmDeleteWindow = getAtom("WM_DELETE_WINDOW"); if (!wmProtocols) @@ -1574,12 +1568,12 @@ void WindowImplX11::setProtocols() } Atom netWmPing = None; - Atom netWmPid = None; + Atom netWmPid = None; if (ewmhSupported()) { netWmPing = getAtom("_NET_WM_PING", true); - netWmPid = getAtom("_NET_WM_PID", true); + netWmPid = getAtom("_NET_WM_PID", true); } if (netWmPing && netWmPid) @@ -1641,9 +1635,10 @@ void WindowImplX11::initialize() } if (!m_inputContext) - err() << "Failed to create input context for window -- TextEntered event won't be able to return unicode" << std::endl; + err() << "Failed to create input context for window -- TextEntered event won't be able to return unicode" + << std::endl; - Atom wmWindowType = getAtom("_NET_WM_WINDOW_TYPE", false); + Atom wmWindowType = getAtom("_NET_WM_WINDOW_TYPE", false); Atom wmWindowTypeNormal = getAtom("_NET_WM_WINDOW_TYPE_NORMAL", false); if (wmWindowType && wmWindowTypeNormal) @@ -1704,8 +1699,8 @@ void WindowImplX11::updateLastInputTime(::Time time) void WindowImplX11::createHiddenCursor() { // Create the cursor's pixmap (1x1 pixels) - Pixmap cursorPixmap = XCreatePixmap(m_display, m_window, 1, 1, 1); - GC graphicsContext = XCreateGC(m_display, cursorPixmap, 0, nullptr); + Pixmap cursorPixmap = XCreatePixmap(m_display, m_window, 1, 1, 1); + GC graphicsContext = XCreateGC(m_display, cursorPixmap, 0, nullptr); XDrawPoint(m_display, cursorPixmap, graphicsContext, 0, 0); XFreeGC(m_display, graphicsContext); @@ -1748,11 +1743,9 @@ bool WindowImplX11::processEvent(XEvent& windowEvent) if (windowEvent.type == KeyRelease) { // Find the next KeyPress event with matching keycode and time - auto it = std::find_if( - m_events.begin(), - m_events.end(), - KeyRepeatFinder(windowEvent.xkey.keycode, windowEvent.xkey.time) - ); + auto it = std::find_if(m_events.begin(), + m_events.end(), + KeyRepeatFinder(windowEvent.xkey.keycode, windowEvent.xkey.time)); if (it != m_events.end()) { @@ -1869,21 +1862,27 @@ bool WindowImplX11::processEvent(XEvent& windowEvent) if (windowEvent.xclient.message_type == wmProtocols) { static Atom wmDeleteWindow = getAtom("WM_DELETE_WINDOW"); - static Atom netWmPing = ewmhSupported() ? getAtom("_NET_WM_PING", true) : None; + static Atom netWmPing = ewmhSupported() ? getAtom("_NET_WM_PING", true) : None; - if ((windowEvent.xclient.format == 32) && (windowEvent.xclient.data.l[0]) == static_cast(wmDeleteWindow)) + if ((windowEvent.xclient.format == 32) && + (windowEvent.xclient.data.l[0]) == static_cast(wmDeleteWindow)) { // Handle the WM_DELETE_WINDOW message Event event; event.type = Event::Closed; pushEvent(event); } - else if (netWmPing && (windowEvent.xclient.format == 32) && (windowEvent.xclient.data.l[0]) == static_cast(netWmPing)) + else if (netWmPing && (windowEvent.xclient.format == 32) && + (windowEvent.xclient.data.l[0]) == static_cast(netWmPing)) { // Handle the _NET_WM_PING message, send pong back to WM to show that we are responsive windowEvent.xclient.window = DefaultRootWindow(m_display); - XSendEvent(m_display, DefaultRootWindow(m_display), False, SubstructureNotifyMask | SubstructureRedirectMask, &windowEvent); + XSendEvent(m_display, + DefaultRootWindow(m_display), + False, + SubstructureNotifyMask | SubstructureRedirectMask, + &windowEvent); } } } @@ -1919,31 +1918,30 @@ bool WindowImplX11::processEvent(XEvent& windowEvent) // Generate a TextEntered event if (!XFilterEvent(&windowEvent, None)) { - #ifdef X_HAVE_UTF8_STRING +#ifdef X_HAVE_UTF8_STRING if (m_inputContext) { Status status; Uint8 keyBuffer[64]; - int length = Xutf8LookupString( - m_inputContext, - &windowEvent.xkey, - reinterpret_cast(keyBuffer), - sizeof(keyBuffer), - nullptr, - &status - ); + int length = Xutf8LookupString(m_inputContext, + &windowEvent.xkey, + reinterpret_cast(keyBuffer), + sizeof(keyBuffer), + nullptr, + &status); if (status == XBufferOverflow) err() << "A TextEntered event has more than 64 bytes of UTF-8 input, and " "has been discarded\nThis means either you have typed a very long string " - "(more than 20 chars), or your input method is broken in obscure ways." << std::endl; + "(more than 20 chars), or your input method is broken in obscure ways." + << std::endl; else if (status == XLookupChars) { // There might be more than 1 characters in this event, // so we must iterate it Uint32 unicode = 0; - Uint8* iter = keyBuffer; + Uint8* iter = keyBuffer; while (iter < keyBuffer + length) { iter = Utf8::decode(iter, keyBuffer + length, unicode, 0); @@ -1958,10 +1956,10 @@ bool WindowImplX11::processEvent(XEvent& windowEvent) } } else - #endif +#endif { static XComposeStatus status; - char keyBuffer[16]; + char keyBuffer[16]; if (XLookupString(&windowEvent.xkey, keyBuffer, sizeof(keyBuffer), nullptr, &status)) { Event textEvent; @@ -2011,11 +2009,7 @@ bool WindowImplX11::processEvent(XEvent& windowEvent) // XXX: Why button 8 and 9? // Because 4 and 5 are the vertical wheel and 6 and 7 are horizontal wheel ;) unsigned int button = windowEvent.xbutton.button; - if ((button == Button1) || - (button == Button2) || - (button == Button3) || - (button == 8) || - (button == 9)) + if ((button == Button1) || (button == Button2) || (button == Button3) || (button == 8) || (button == 9)) { Event event; event.type = Event::MouseButtonPressed; @@ -2045,23 +2039,29 @@ bool WindowImplX11::processEvent(XEvent& windowEvent) case ButtonRelease: { unsigned int button = windowEvent.xbutton.button; - if ((button == Button1) || - (button == Button2) || - (button == Button3) || - (button == 8) || - (button == 9)) + if ((button == Button1) || (button == Button2) || (button == Button3) || (button == 8) || (button == 9)) { Event event; event.type = Event::MouseButtonReleased; event.mouseButton.x = windowEvent.xbutton.x; event.mouseButton.y = windowEvent.xbutton.y; - switch(button) + switch (button) { - case Button1: event.mouseButton.button = Mouse::Left; break; - case Button2: event.mouseButton.button = Mouse::Middle; break; - case Button3: event.mouseButton.button = Mouse::Right; break; - case 8: event.mouseButton.button = Mouse::XButton1; break; - case 9: event.mouseButton.button = Mouse::XButton2; break; + case Button1: + event.mouseButton.button = Mouse::Left; + break; + case Button2: + event.mouseButton.button = Mouse::Middle; + break; + case Button3: + event.mouseButton.button = Mouse::Right; + break; + case 8: + event.mouseButton.button = Mouse::XButton1; + break; + case 9: + event.mouseButton.button = Mouse::XButton2; + break; } pushEvent(event); } @@ -2180,7 +2180,7 @@ bool WindowImplX11::checkXRandR(int& xRandRMajor, int& xRandRMinor) } // Check XRandR version, 1.2 required - if (!XRRQueryVersion(m_display, &xRandRMajor, &xRandRMinor) || xRandRMajor < 1 || (xRandRMajor == 1 && xRandRMinor < 2 )) + if (!XRRQueryVersion(m_display, &xRandRMajor, &xRandRMinor) || xRandRMajor < 1 || (xRandRMajor == 1 && xRandRMinor < 2)) { err() << "XRandR is too old" << std::endl; return false; diff --git a/src/SFML/Window/Unix/WindowImplX11.hpp b/src/SFML/Window/Unix/WindowImplX11.hpp index 568fe3790..be8493eee 100644 --- a/src/SFML/Window/Unix/WindowImplX11.hpp +++ b/src/SFML/Window/Unix/WindowImplX11.hpp @@ -31,10 +31,12 @@ #include #include #include // Prevent conflict with macro None from Xlib + #include -#include #include +#include + namespace sf { @@ -47,7 +49,6 @@ namespace priv class WindowImplX11 : public WindowImpl { public: - //////////////////////////////////////////////////////////// /// \brief Construct the window implementation from an existing control /// @@ -186,7 +187,6 @@ public: bool hasFocus() const override; protected: - //////////////////////////////////////////////////////////// /// \brief Process incoming events from the operating system /// @@ -194,7 +194,6 @@ protected: void processEvents() override; private: - //////////////////////////////////////////////////////////// /// \brief Request the WM to make the current window active /// @@ -298,26 +297,26 @@ private: //////////////////////////////////////////////////////////// // Member data //////////////////////////////////////////////////////////// - ::Window m_window; ///< X identifier defining our window - ::Display* m_display; ///< Pointer to the display - int m_screen; ///< Screen identifier - XIM m_inputMethod; ///< Input method linked to the X display - XIC m_inputContext; ///< Input context used to get unicode input in our window - std::deque m_events; ///< Queue we use to store pending events for this window - bool m_isExternal; ///< Tell whether the window has been created externally or by SFML - RRMode m_oldVideoMode; ///< Video mode in use before we switch to fullscreen - RRCrtc m_oldRRCrtc; ///< RRCrtc in use before we switch to fullscreen - ::Cursor m_hiddenCursor; ///< As X11 doesn't provide cursor hiding, we must create a transparent one - ::Cursor m_lastCursor; ///< Last cursor used -- this data is not owned by the window and is required to be always valid - bool m_keyRepeat; ///< Is the KeyRepeat feature enabled? - Vector2i m_previousSize; ///< Previous size of the window, to find if a ConfigureNotify event is a resize event (could be a move event only) - bool m_useSizeHints; ///< Is the size of the window fixed with size hints? - bool m_fullscreen; ///< Is the window in fullscreen? - bool m_cursorGrabbed; ///< Is the mouse cursor trapped? - bool m_windowMapped; ///< Has the window been mapped by the window manager? - Pixmap m_iconPixmap; ///< The current icon pixmap if in use - Pixmap m_iconMaskPixmap; ///< The current icon mask pixmap if in use - ::Time m_lastInputTime; ///< Last time we received user input + ::Window m_window; ///< X identifier defining our window + ::Display* m_display; ///< Pointer to the display + int m_screen; ///< Screen identifier + XIM m_inputMethod; ///< Input method linked to the X display + XIC m_inputContext; ///< Input context used to get unicode input in our window + std::deque m_events; ///< Queue we use to store pending events for this window + bool m_isExternal; ///< Tell whether the window has been created externally or by SFML + RRMode m_oldVideoMode; ///< Video mode in use before we switch to fullscreen + RRCrtc m_oldRRCrtc; ///< RRCrtc in use before we switch to fullscreen + ::Cursor m_hiddenCursor; ///< As X11 doesn't provide cursor hiding, we must create a transparent one + ::Cursor m_lastCursor; ///< Last cursor used -- this data is not owned by the window and is required to be always valid + bool m_keyRepeat; ///< Is the KeyRepeat feature enabled? + Vector2i m_previousSize; ///< Previous size of the window, to find if a ConfigureNotify event is a resize event (could be a move event only) + bool m_useSizeHints; ///< Is the size of the window fixed with size hints? + bool m_fullscreen; ///< Is the window in fullscreen? + bool m_cursorGrabbed; ///< Is the mouse cursor trapped? + bool m_windowMapped; ///< Has the window been mapped by the window manager? + Pixmap m_iconPixmap; ///< The current icon pixmap if in use + Pixmap m_iconMaskPixmap; ///< The current icon mask pixmap if in use + ::Time m_lastInputTime; ///< Last time we received user input }; } // namespace priv diff --git a/src/SFML/Window/VideoMode.cpp b/src/SFML/Window/VideoMode.cpp index fcd08651c..9e4b3f201 100644 --- a/src/SFML/Window/VideoMode.cpp +++ b/src/SFML/Window/VideoMode.cpp @@ -27,6 +27,7 @@ //////////////////////////////////////////////////////////// #include #include + #include #include @@ -34,20 +35,16 @@ namespace sf { //////////////////////////////////////////////////////////// -VideoMode::VideoMode() : -size (0, 0), -bitsPerPixel(0) +VideoMode::VideoMode() : size(0, 0), bitsPerPixel(0) { - } //////////////////////////////////////////////////////////// VideoMode::VideoMode(const Vector2u& modeSize, unsigned int modeBitsPerPixel) : -size (modeSize), +size(modeSize), bitsPerPixel(modeBitsPerPixel) { - } @@ -85,22 +82,21 @@ bool VideoMode::isValid() const //////////////////////////////////////////////////////////// -bool operator ==(const VideoMode& left, const VideoMode& right) +bool operator==(const VideoMode& left, const VideoMode& right) { - return (left.size == right.size) && - (left.bitsPerPixel == right.bitsPerPixel); + return (left.size == right.size) && (left.bitsPerPixel == right.bitsPerPixel); } //////////////////////////////////////////////////////////// -bool operator !=(const VideoMode& left, const VideoMode& right) +bool operator!=(const VideoMode& left, const VideoMode& right) { return !(left == right); } //////////////////////////////////////////////////////////// -bool operator <(const VideoMode& left, const VideoMode& right) +bool operator<(const VideoMode& left, const VideoMode& right) { if (left.bitsPerPixel == right.bitsPerPixel) { @@ -121,21 +117,21 @@ bool operator <(const VideoMode& left, const VideoMode& right) //////////////////////////////////////////////////////////// -bool operator >(const VideoMode& left, const VideoMode& right) +bool operator>(const VideoMode& left, const VideoMode& right) { return right < left; } //////////////////////////////////////////////////////////// -bool operator <=(const VideoMode& left, const VideoMode& right) +bool operator<=(const VideoMode& left, const VideoMode& right) { return !(right < left); } //////////////////////////////////////////////////////////// -bool operator >=(const VideoMode& left, const VideoMode& right) +bool operator>=(const VideoMode& left, const VideoMode& right) { return !(left < right); } diff --git a/src/SFML/Window/VideoModeImpl.hpp b/src/SFML/Window/VideoModeImpl.hpp index d4990e99f..3c0d00072 100644 --- a/src/SFML/Window/VideoModeImpl.hpp +++ b/src/SFML/Window/VideoModeImpl.hpp @@ -42,7 +42,6 @@ namespace priv class VideoModeImpl { public: - //////////////////////////////////////////////////////////// /// \brief Get the list of all the supported fullscreen video modes /// diff --git a/src/SFML/Window/Vulkan.cpp b/src/SFML/Window/Vulkan.cpp index 9bf614f6c..76cafe7fe 100644 --- a/src/SFML/Window/Vulkan.cpp +++ b/src/SFML/Window/Vulkan.cpp @@ -32,18 +32,19 @@ #include using VulkanImplType = sf::priv::VulkanImplWin32; -#elif defined(SFML_SYSTEM_LINUX) || defined(SFML_SYSTEM_FREEBSD) || defined(SFML_SYSTEM_OPENBSD) || defined(SFML_SYSTEM_NETBSD) +#elif defined(SFML_SYSTEM_LINUX) || defined(SFML_SYSTEM_FREEBSD) || defined(SFML_SYSTEM_OPENBSD) || \ + defined(SFML_SYSTEM_NETBSD) - #if defined(SFML_USE_DRM) +#if defined(SFML_USE_DRM) - #define SFML_VULKAN_IMPLEMENTATION_NOT_AVAILABLE +#define SFML_VULKAN_IMPLEMENTATION_NOT_AVAILABLE - #else +#else - #include - using VulkanImplType = sf::priv::VulkanImplX11; +#include +using VulkanImplType = sf::priv::VulkanImplX11; - #endif +#endif #else diff --git a/src/SFML/Window/Win32/ClipboardImpl.cpp b/src/SFML/Window/Win32/ClipboardImpl.cpp index 7a70cf437..856f49aa3 100644 --- a/src/SFML/Window/Win32/ClipboardImpl.cpp +++ b/src/SFML/Window/Win32/ClipboardImpl.cpp @@ -25,10 +25,11 @@ //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// -#include -#include -#include #include +#include +#include +#include + #include @@ -86,7 +87,7 @@ void ClipboardImpl::setString(const String& text) } // Create a Win32-compatible string - size_t string_size = (text.getSize() + 1) * sizeof(WCHAR); + size_t string_size = (text.getSize() + 1) * sizeof(WCHAR); HANDLE string_handle = GlobalAlloc(GMEM_MOVEABLE, string_size); if (string_handle) diff --git a/src/SFML/Window/Win32/ClipboardImpl.hpp b/src/SFML/Window/Win32/ClipboardImpl.hpp index 2884fb52d..0128627e0 100644 --- a/src/SFML/Window/Win32/ClipboardImpl.hpp +++ b/src/SFML/Window/Win32/ClipboardImpl.hpp @@ -39,7 +39,6 @@ namespace priv class ClipboardImpl { public: - //////////////////////////////////////////////////////////// /// \brief Get the content of the clipboard as string data /// diff --git a/src/SFML/Window/Win32/CursorImpl.cpp b/src/SFML/Window/Win32/CursorImpl.cpp old mode 100755 new mode 100644 index 55f053d2e..be5d60f1d --- a/src/SFML/Window/Win32/CursorImpl.cpp +++ b/src/SFML/Window/Win32/CursorImpl.cpp @@ -25,11 +25,12 @@ //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// -#include -#include #include -#include +#include +#include + #include +#include namespace sf @@ -38,9 +39,7 @@ namespace priv { //////////////////////////////////////////////////////////// -CursorImpl::CursorImpl() : -m_cursor(nullptr), -m_systemCursor(false) +CursorImpl::CursorImpl() : m_cursor(nullptr), m_systemCursor(false) { // That's it. } @@ -75,15 +74,13 @@ bool CursorImpl::loadFromPixels(const Uint8* pixels, Vector2u size, Vector2u hot Uint32* bitmapData = nullptr; - HDC screenDC = GetDC(nullptr); - HBITMAP color = CreateDIBSection( - screenDC, - reinterpret_cast(&bitmapHeader), - DIB_RGB_COLORS, - reinterpret_cast(&bitmapData), - nullptr, - 0 - ); + HDC screenDC = GetDC(nullptr); + HBITMAP color = CreateDIBSection(screenDC, + reinterpret_cast(&bitmapHeader), + DIB_RGB_COLORS, + reinterpret_cast(&bitmapData), + nullptr, + 0); ReleaseDC(nullptr, screenDC); if (!color) @@ -121,7 +118,7 @@ bool CursorImpl::loadFromPixels(const Uint8* pixels, Vector2u size, Vector2u hot cursorInfo.hbmMask = mask; // Create the cursor - m_cursor = reinterpret_cast(CreateIconIndirect(&cursorInfo)); + m_cursor = reinterpret_cast(CreateIconIndirect(&cursorInfo)); m_systemCursor = false; // The data has been copied into the cursor, so get rid of these @@ -175,7 +172,7 @@ bool CursorImpl::loadFromSystem(Cursor::Type type) // clang-format on // Get the shared system cursor and make sure not to destroy it - m_cursor = LoadCursor(nullptr, shape); + m_cursor = LoadCursor(nullptr, shape); m_systemCursor = true; if (m_cursor) @@ -193,7 +190,8 @@ bool CursorImpl::loadFromSystem(Cursor::Type type) //////////////////////////////////////////////////////////// void CursorImpl::release() { - if (m_cursor && !m_systemCursor) { + if (m_cursor && !m_systemCursor) + { DestroyCursor(static_cast(m_cursor)); m_cursor = nullptr; } @@ -202,4 +200,3 @@ void CursorImpl::release() } // namespace priv } // namespace sf - diff --git a/src/SFML/Window/Win32/CursorImpl.hpp b/src/SFML/Window/Win32/CursorImpl.hpp old mode 100755 new mode 100644 index 688afd69c..212462196 --- a/src/SFML/Window/Win32/CursorImpl.hpp +++ b/src/SFML/Window/Win32/CursorImpl.hpp @@ -28,8 +28,8 @@ //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// -#include #include +#include namespace sf { @@ -43,7 +43,6 @@ namespace priv class CursorImpl { public: - //////////////////////////////////////////////////////////// /// \brief Default constructor /// @@ -89,7 +88,6 @@ public: bool loadFromSystem(Cursor::Type type); private: - friend class WindowImplWin32; //////////////////////////////////////////////////////////// @@ -110,4 +108,3 @@ private: } // namespace sf #endif // SFML_CUSROSIMPLWIN32_HPP - diff --git a/src/SFML/Window/Win32/InputImpl.cpp b/src/SFML/Window/Win32/InputImpl.cpp index c40b7b67e..bcf2f77d7 100644 --- a/src/SFML/Window/Win32/InputImpl.cpp +++ b/src/SFML/Window/Win32/InputImpl.cpp @@ -25,9 +25,9 @@ //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// -#include -#include #include +#include +#include namespace sf @@ -164,12 +164,24 @@ bool InputImpl::isMouseButtonPressed(Mouse::Button button) int vkey = 0; switch (button) { - case Mouse::Left: vkey = GetSystemMetrics(SM_SWAPBUTTON) ? VK_RBUTTON : VK_LBUTTON; break; - case Mouse::Right: vkey = GetSystemMetrics(SM_SWAPBUTTON) ? VK_LBUTTON : VK_RBUTTON; break; - case Mouse::Middle: vkey = VK_MBUTTON; break; - case Mouse::XButton1: vkey = VK_XBUTTON1; break; - case Mouse::XButton2: vkey = VK_XBUTTON2; break; - default: vkey = 0; break; + case Mouse::Left: + vkey = GetSystemMetrics(SM_SWAPBUTTON) ? VK_RBUTTON : VK_LBUTTON; + break; + case Mouse::Right: + vkey = GetSystemMetrics(SM_SWAPBUTTON) ? VK_LBUTTON : VK_RBUTTON; + break; + case Mouse::Middle: + vkey = VK_MBUTTON; + break; + case Mouse::XButton1: + vkey = VK_XBUTTON1; + break; + case Mouse::XButton2: + vkey = VK_XBUTTON2; + break; + default: + vkey = 0; + break; } return (GetAsyncKeyState(vkey) & 0x8000) != 0; diff --git a/src/SFML/Window/Win32/InputImpl.hpp b/src/SFML/Window/Win32/InputImpl.hpp index 54f1f9d64..b29588a7f 100644 --- a/src/SFML/Window/Win32/InputImpl.hpp +++ b/src/SFML/Window/Win32/InputImpl.hpp @@ -43,7 +43,6 @@ namespace priv class InputImpl { public: - //////////////////////////////////////////////////////////// /// \brief Check if a key is pressed /// diff --git a/src/SFML/Window/Win32/JoystickImpl.cpp b/src/SFML/Window/Win32/JoystickImpl.cpp index 315ff5854..3d241f50d 100644 --- a/src/SFML/Window/Win32/JoystickImpl.cpp +++ b/src/SFML/Window/Win32/JoystickImpl.cpp @@ -25,21 +25,21 @@ //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// -#include -#include #include #include #include -#include -#include -#include -#include -#include -#include -#include +#include +#include + #include #include - +#include +#include +#include +#include +#include +#include +#include //////////////////////////////////////////////////////////// @@ -54,46 +54,46 @@ namespace { - namespace guids - { - const GUID IID_IDirectInput8W = {0xbf798031, 0x483a, 0x4da2, {0xaa, 0x99, 0x5d, 0x64, 0xed, 0x36, 0x97, 0x00}}; +namespace guids +{ +const GUID IID_IDirectInput8W = {0xbf798031, 0x483a, 0x4da2, {0xaa, 0x99, 0x5d, 0x64, 0xed, 0x36, 0x97, 0x00}}; - const GUID GUID_XAxis = {0xa36d02e0, 0xc9f3, 0x11cf, {0xbf, 0xc7, 0x44, 0x45, 0x53, 0x54, 0x00, 0x00}}; - const GUID GUID_YAxis = {0xa36d02e1, 0xc9f3, 0x11cf, {0xbf, 0xc7, 0x44, 0x45, 0x53, 0x54, 0x00, 0x00}}; - const GUID GUID_ZAxis = {0xa36d02e2, 0xc9f3, 0x11cf, {0xbf, 0xc7, 0x44, 0x45, 0x53, 0x54, 0x00, 0x00}}; - const GUID GUID_RzAxis = {0xa36d02e3, 0xc9f3, 0x11cf, {0xbf, 0xc7, 0x44, 0x45, 0x53, 0x54, 0x00, 0x00}}; - const GUID GUID_Slider = {0xa36d02e4, 0xc9f3, 0x11cf, {0xbf, 0xc7, 0x44, 0x45, 0x53, 0x54, 0x00, 0x00}}; +const GUID GUID_XAxis = {0xa36d02e0, 0xc9f3, 0x11cf, {0xbf, 0xc7, 0x44, 0x45, 0x53, 0x54, 0x00, 0x00}}; +const GUID GUID_YAxis = {0xa36d02e1, 0xc9f3, 0x11cf, {0xbf, 0xc7, 0x44, 0x45, 0x53, 0x54, 0x00, 0x00}}; +const GUID GUID_ZAxis = {0xa36d02e2, 0xc9f3, 0x11cf, {0xbf, 0xc7, 0x44, 0x45, 0x53, 0x54, 0x00, 0x00}}; +const GUID GUID_RzAxis = {0xa36d02e3, 0xc9f3, 0x11cf, {0xbf, 0xc7, 0x44, 0x45, 0x53, 0x54, 0x00, 0x00}}; +const GUID GUID_Slider = {0xa36d02e4, 0xc9f3, 0x11cf, {0xbf, 0xc7, 0x44, 0x45, 0x53, 0x54, 0x00, 0x00}}; - const GUID GUID_POV = {0xa36d02f2, 0xc9f3, 0x11cf, {0xbf, 0xc7, 0x44, 0x45, 0x53, 0x54, 0x00, 0x00}}; +const GUID GUID_POV = {0xa36d02f2, 0xc9f3, 0x11cf, {0xbf, 0xc7, 0x44, 0x45, 0x53, 0x54, 0x00, 0x00}}; - const GUID GUID_RxAxis = {0xa36d02f4, 0xc9f3, 0x11cf, {0xbf, 0xc7, 0x44, 0x45, 0x53, 0x54, 0x00, 0x00}}; - const GUID GUID_RyAxis = {0xa36d02f5, 0xc9f3, 0x11cf, {0xbf, 0xc7, 0x44, 0x45, 0x53, 0x54, 0x00, 0x00}}; - } +const GUID GUID_RxAxis = {0xa36d02f4, 0xc9f3, 0x11cf, {0xbf, 0xc7, 0x44, 0x45, 0x53, 0x54, 0x00, 0x00}}; +const GUID GUID_RyAxis = {0xa36d02f5, 0xc9f3, 0x11cf, {0xbf, 0xc7, 0x44, 0x45, 0x53, 0x54, 0x00, 0x00}}; +} // namespace guids - HMODULE dinput8dll = nullptr; - IDirectInput8W* directInput = nullptr; +HMODULE dinput8dll = nullptr; +IDirectInput8W* directInput = nullptr; - struct JoystickRecord - { - GUID guid; - unsigned int index; - bool plugged; - }; +struct JoystickRecord +{ + GUID guid; + unsigned int index; + bool plugged; +}; - using JoystickList = std::vector; - JoystickList joystickList; +using JoystickList = std::vector; +JoystickList joystickList; - struct JoystickBlacklistEntry - { - unsigned int vendorId; - unsigned int productId; - }; +struct JoystickBlacklistEntry +{ + unsigned int vendorId; + unsigned int productId; +}; - using JoystickBlacklist = std::vector; - JoystickBlacklist joystickBlacklist; +using JoystickBlacklist = std::vector; +JoystickBlacklist joystickBlacklist; - const DWORD directInputEventBufferSize = 32; -} +const DWORD directInputEventBufferSize = 32; +} // namespace //////////////////////////////////////////////////////////// @@ -101,112 +101,124 @@ namespace //////////////////////////////////////////////////////////// namespace { - struct ConnectionCache +struct ConnectionCache +{ + ConnectionCache() : connected(false) { - ConnectionCache() : connected(false) {} - bool connected; - sf::Clock timer; - }; - const sf::Time connectionRefreshDelay = sf::milliseconds(500); - - ConnectionCache connectionCache[sf::Joystick::Count]; - - // If true, will only update when WM_DEVICECHANGE message is received - bool lazyUpdates = false; - - // Get a system error string from an error code - std::string getErrorString(DWORD error) - { - PTCHAR buffer; - - if (FormatMessage(FORMAT_MESSAGE_MAX_WIDTH_MASK | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, nullptr, error, 0, reinterpret_cast(&buffer), 0, nullptr) == 0) - return "Unknown error."; - - sf::String message = buffer; - LocalFree(buffer); - return message.toAnsiString(); } + bool connected; + sf::Clock timer; +}; +const sf::Time connectionRefreshDelay = sf::milliseconds(500); - // Get the joystick's name - sf::String getDeviceName(unsigned int index, JOYCAPS caps) +ConnectionCache connectionCache[sf::Joystick::Count]; + +// If true, will only update when WM_DEVICECHANGE message is received +bool lazyUpdates = false; + +// Get a system error string from an error code +std::string getErrorString(DWORD error) +{ + PTCHAR buffer; + + if (FormatMessage(FORMAT_MESSAGE_MAX_WIDTH_MASK | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, + nullptr, + error, + 0, + reinterpret_cast(&buffer), + 0, + nullptr) == 0) + return "Unknown error."; + + sf::String message = buffer; + LocalFree(buffer); + return message.toAnsiString(); +} + +// Get the joystick's name +sf::String getDeviceName(unsigned int index, JOYCAPS caps) +{ + // Give the joystick a default name + sf::String joystickDescription = "Unknown Joystick"; + + LONG result; + HKEY rootKey; + HKEY currentKey; + std::basic_string subkey; + + subkey = REGSTR_PATH_JOYCONFIG; + subkey += TEXT('\\'); + subkey += caps.szRegKey; + subkey += TEXT('\\'); + subkey += REGSTR_KEY_JOYCURR; + + rootKey = HKEY_CURRENT_USER; + result = RegOpenKeyEx(rootKey, subkey.c_str(), 0, KEY_READ, ¤tKey); + + if (result != ERROR_SUCCESS) { - // Give the joystick a default name - sf::String joystickDescription = "Unknown Joystick"; - - LONG result; - HKEY rootKey; - HKEY currentKey; - std::basic_string subkey; - - subkey = REGSTR_PATH_JOYCONFIG; - subkey += TEXT('\\'); - subkey += caps.szRegKey; - subkey += TEXT('\\'); - subkey += REGSTR_KEY_JOYCURR; - - rootKey = HKEY_CURRENT_USER; + rootKey = HKEY_LOCAL_MACHINE; result = RegOpenKeyEx(rootKey, subkey.c_str(), 0, KEY_READ, ¤tKey); if (result != ERROR_SUCCESS) { - rootKey = HKEY_LOCAL_MACHINE; - result = RegOpenKeyEx(rootKey, subkey.c_str(), 0, KEY_READ, ¤tKey); - - if (result != ERROR_SUCCESS) - { - sf::err() << "Unable to open registry for joystick at index " << index << ": " << getErrorString(static_cast(result)) << std::endl; - return joystickDescription; - } - } - - std::basic_ostringstream indexString; - indexString << index + 1; - - subkey = TEXT("Joystick"); - subkey += indexString.str(); - subkey += REGSTR_VAL_JOYOEMNAME; - - TCHAR keyData[256]; - DWORD keyDataSize = sizeof(keyData); - - result = RegQueryValueEx(currentKey, subkey.c_str(), nullptr, nullptr, reinterpret_cast(keyData), &keyDataSize); - RegCloseKey(currentKey); - - if (result != ERROR_SUCCESS) - { - sf::err() << "Unable to query registry key for joystick at index " << index << ": " << getErrorString(static_cast(result)) << std::endl; + sf::err() << "Unable to open registry for joystick at index " << index << ": " + << getErrorString(static_cast(result)) << std::endl; return joystickDescription; } + } - subkey = REGSTR_PATH_JOYOEM; - subkey += TEXT('\\'); - subkey.append(keyData, keyDataSize / sizeof(TCHAR)); + std::basic_ostringstream indexString; + indexString << index + 1; - result = RegOpenKeyEx(rootKey, subkey.c_str(), 0, KEY_READ, ¤tKey); + subkey = TEXT("Joystick"); + subkey += indexString.str(); + subkey += REGSTR_VAL_JOYOEMNAME; - if (result != ERROR_SUCCESS) - { - sf::err() << "Unable to open registry key for joystick at index " << index << ": " << getErrorString(static_cast(result)) << std::endl; - return joystickDescription; - } + TCHAR keyData[256]; + DWORD keyDataSize = sizeof(keyData); - keyDataSize = sizeof(keyData); - - result = RegQueryValueEx(currentKey, REGSTR_VAL_JOYOEMNAME, nullptr, nullptr, reinterpret_cast(keyData), &keyDataSize); - RegCloseKey(currentKey); - - if (result != ERROR_SUCCESS) - { - sf::err() << "Unable to query name for joystick at index " << index << ": " << getErrorString(static_cast(result)) << std::endl; - return joystickDescription; - } - - keyData[255] = TEXT('\0'); // Ensure null terminator in case the data is too long. - joystickDescription = keyData; + result = RegQueryValueEx(currentKey, subkey.c_str(), nullptr, nullptr, reinterpret_cast(keyData), &keyDataSize); + RegCloseKey(currentKey); + if (result != ERROR_SUCCESS) + { + sf::err() << "Unable to query registry key for joystick at index " << index << ": " + << getErrorString(static_cast(result)) << std::endl; return joystickDescription; } + + subkey = REGSTR_PATH_JOYOEM; + subkey += TEXT('\\'); + subkey.append(keyData, keyDataSize / sizeof(TCHAR)); + + result = RegOpenKeyEx(rootKey, subkey.c_str(), 0, KEY_READ, ¤tKey); + + if (result != ERROR_SUCCESS) + { + sf::err() << "Unable to open registry key for joystick at index " << index << ": " + << getErrorString(static_cast(result)) << std::endl; + return joystickDescription; + } + + keyDataSize = sizeof(keyData); + + result = RegQueryValueEx(currentKey, REGSTR_VAL_JOYOEMNAME, nullptr, nullptr, reinterpret_cast(keyData), &keyDataSize); + RegCloseKey(currentKey); + + if (result != ERROR_SUCCESS) + { + sf::err() << "Unable to query name for joystick at index " << index << ": " + << getErrorString(static_cast(result)) << std::endl; + return joystickDescription; + } + + keyData[255] = TEXT('\0'); // Ensure null terminator in case the data is too long. + joystickDescription = keyData; + + return joystickDescription; } +} // namespace namespace sf { @@ -244,7 +256,7 @@ bool JoystickImpl::isConnected(unsigned int index) if (!lazyUpdates && cache.timer.getElapsedTime() > connectionRefreshDelay) { JOYINFOEX joyInfo; - joyInfo.dwSize = sizeof(joyInfo); + joyInfo.dwSize = sizeof(joyInfo); joyInfo.dwFlags = 0; cache.connected = joyGetPosEx(JOYSTICKID1 + index, &joyInfo) == JOYERR_NOERROR; @@ -268,10 +280,10 @@ void JoystickImpl::updateConnections() for (unsigned int i = 0; i < Joystick::Count; ++i) { JOYINFOEX joyInfo; - joyInfo.dwSize = sizeof(joyInfo); - joyInfo.dwFlags = 0; + joyInfo.dwSize = sizeof(joyInfo); + joyInfo.dwFlags = 0; ConnectionCache& cache = connectionCache[i]; - cache.connected = joyGetPosEx(JOYSTICKID1 + i, &joyInfo) == JOYERR_NOERROR; + cache.connected = joyGetPosEx(JOYSTICKID1 + i, &joyInfo) == JOYERR_NOERROR; cache.timer.restart(); } @@ -358,26 +370,32 @@ JoystickState JoystickImpl::update() // Get the current joystick state JOYINFOEX pos; - pos.dwFlags = JOY_RETURNX | JOY_RETURNY | JOY_RETURNZ | JOY_RETURNR | JOY_RETURNU | JOY_RETURNV | JOY_RETURNBUTTONS; + pos.dwFlags = JOY_RETURNX | JOY_RETURNY | JOY_RETURNZ | JOY_RETURNR | JOY_RETURNU | JOY_RETURNV | JOY_RETURNBUTTONS; pos.dwFlags |= (m_caps.wCaps & JOYCAPS_POVCTS) ? JOY_RETURNPOVCTS : JOY_RETURNPOV; - pos.dwSize = sizeof(JOYINFOEX); + pos.dwSize = sizeof(JOYINFOEX); if (joyGetPosEx(m_index, &pos) == JOYERR_NOERROR) { // The joystick is connected state.connected = true; // Axes - state.axes[Joystick::X] = (static_cast(pos.dwXpos) - static_cast(m_caps.wXmax + m_caps.wXmin) / 2.f) * 200.f / static_cast(m_caps.wXmax - m_caps.wXmin); - state.axes[Joystick::Y] = (static_cast(pos.dwYpos) - static_cast(m_caps.wYmax + m_caps.wYmin) / 2.f) * 200.f / static_cast(m_caps.wYmax - m_caps.wYmin); - state.axes[Joystick::Z] = (static_cast(pos.dwZpos) - static_cast(m_caps.wZmax + m_caps.wZmin) / 2.f) * 200.f / static_cast(m_caps.wZmax - m_caps.wZmin); - state.axes[Joystick::R] = (static_cast(pos.dwRpos) - static_cast(m_caps.wRmax + m_caps.wRmin) / 2.f) * 200.f / static_cast(m_caps.wRmax - m_caps.wRmin); - state.axes[Joystick::U] = (static_cast(pos.dwUpos) - static_cast(m_caps.wUmax + m_caps.wUmin) / 2.f) * 200.f / static_cast(m_caps.wUmax - m_caps.wUmin); - state.axes[Joystick::V] = (static_cast(pos.dwVpos) - static_cast(m_caps.wVmax + m_caps.wVmin) / 2.f) * 200.f / static_cast(m_caps.wVmax - m_caps.wVmin); + state.axes[Joystick::X] = (static_cast(pos.dwXpos) - static_cast(m_caps.wXmax + m_caps.wXmin) / 2.f) * + 200.f / static_cast(m_caps.wXmax - m_caps.wXmin); + state.axes[Joystick::Y] = (static_cast(pos.dwYpos) - static_cast(m_caps.wYmax + m_caps.wYmin) / 2.f) * + 200.f / static_cast(m_caps.wYmax - m_caps.wYmin); + state.axes[Joystick::Z] = (static_cast(pos.dwZpos) - static_cast(m_caps.wZmax + m_caps.wZmin) / 2.f) * + 200.f / static_cast(m_caps.wZmax - m_caps.wZmin); + state.axes[Joystick::R] = (static_cast(pos.dwRpos) - static_cast(m_caps.wRmax + m_caps.wRmin) / 2.f) * + 200.f / static_cast(m_caps.wRmax - m_caps.wRmin); + state.axes[Joystick::U] = (static_cast(pos.dwUpos) - static_cast(m_caps.wUmax + m_caps.wUmin) / 2.f) * + 200.f / static_cast(m_caps.wUmax - m_caps.wUmin); + state.axes[Joystick::V] = (static_cast(pos.dwVpos) - static_cast(m_caps.wVmax + m_caps.wVmin) / 2.f) * + 200.f / static_cast(m_caps.wVmax - m_caps.wVmin); // Special case for POV, it is given as an angle if (pos.dwPOV != 0xFFFF) { - float angle = static_cast(pos.dwPOV) / 18000.f * 3.141592654f; + float angle = static_cast(pos.dwPOV) / 18000.f * 3.141592654f; state.axes[Joystick::PovX] = std::sin(angle) * 100; state.axes[Joystick::PovY] = std::cos(angle) * 100; } @@ -405,13 +423,18 @@ void JoystickImpl::initializeDInput() if (dinput8dll) { // Try to get the address of the DirectInput8Create entry point - using DirectInput8CreateFunc = HRESULT (WINAPI *)(HINSTANCE, DWORD, const IID &, LPVOID *, LPUNKNOWN); - auto directInput8Create = reinterpret_cast(reinterpret_cast(GetProcAddress(dinput8dll, "DirectInput8Create"))); + using DirectInput8CreateFunc = HRESULT(WINAPI*)(HINSTANCE, DWORD, const IID&, LPVOID*, LPUNKNOWN); + auto directInput8Create = reinterpret_cast( + reinterpret_cast(GetProcAddress(dinput8dll, "DirectInput8Create"))); if (directInput8Create) { // Try to acquire a DirectInput 8.x interface - HRESULT result = directInput8Create(GetModuleHandleW(nullptr), 0x0800, guids::IID_IDirectInput8W, reinterpret_cast(&directInput), nullptr); + HRESULT result = directInput8Create(GetModuleHandleW(nullptr), + 0x0800, + guids::IID_IDirectInput8W, + reinterpret_cast(&directInput), + nullptr); if (FAILED(result)) { @@ -471,7 +494,10 @@ void JoystickImpl::updateConnectionsDInput() record.plugged = false; // Enumerate devices - HRESULT result = directInput->EnumDevices(DI8DEVCLASS_GAMECTRL, &JoystickImpl::deviceEnumerationCallback, nullptr, DIEDFL_ATTACHEDONLY); + HRESULT result = directInput->EnumDevices(DI8DEVCLASS_GAMECTRL, + &JoystickImpl::deviceEnumerationCallback, + nullptr, + DIEDFL_ATTACHEDONLY); // Remove devices that were not connected during the enumeration for (auto i = joystickList.begin(); i != joystickList.end();) @@ -521,8 +547,8 @@ bool JoystickImpl::openDInput(unsigned int index) std::memset(&m_deviceCaps, 0, sizeof(DIDEVCAPS)); m_deviceCaps.dwSize = sizeof(DIDEVCAPS); - m_state = JoystickState(); - m_buffered = false; + m_state = JoystickState(); + m_buffered = false; // Search for a joystick with the given index in the connected list for (const JoystickRecord& record : joystickList) @@ -542,14 +568,14 @@ bool JoystickImpl::openDInput(unsigned int index) // Get vendor and product id of the device DIPROPDWORD property; std::memset(&property, 0, sizeof(property)); - property.diph.dwSize = sizeof(property); + property.diph.dwSize = sizeof(property); property.diph.dwHeaderSize = sizeof(property.diph); - property.diph.dwHow = DIPH_DEVICE; + property.diph.dwHow = DIPH_DEVICE; if (SUCCEEDED(m_device->GetProperty(DIPROP_VIDPID, &property.diph))) { m_identification.productId = HIWORD(property.dwData); - m_identification.vendorId = LOWORD(property.dwData); + m_identification.vendorId = LOWORD(property.dwData); // Check if device is already blacklisted if (m_identification.productId && m_identification.vendorId) @@ -557,7 +583,7 @@ bool JoystickImpl::openDInput(unsigned int index) for (const JoystickBlacklistEntry& blacklistEntry : joystickBlacklist) { if ((m_identification.productId == blacklistEntry.productId) && - (m_identification.vendorId == blacklistEntry.vendorId)) + (m_identification.vendorId == blacklistEntry.vendorId)) { // Device is blacklisted m_device->Release(); @@ -572,21 +598,21 @@ bool JoystickImpl::openDInput(unsigned int index) // Get friendly product name of the device DIPROPSTRING stringProperty; std::memset(&stringProperty, 0, sizeof(stringProperty)); - stringProperty.diph.dwSize = sizeof(stringProperty); + stringProperty.diph.dwSize = sizeof(stringProperty); stringProperty.diph.dwHeaderSize = sizeof(stringProperty.diph); - stringProperty.diph.dwHow = DIPH_DEVICE; - stringProperty.diph.dwObj = 0; + stringProperty.diph.dwHow = DIPH_DEVICE; + stringProperty.diph.dwObj = 0; if (SUCCEEDED(m_device->GetProperty(DIPROP_PRODUCTNAME, &stringProperty.diph))) m_identification.name = stringProperty.wsz; - static bool formatInitialized = false; + static bool formatInitialized = false; static DIDATAFORMAT format; if (!formatInitialized) { - const DWORD axisType = DIDFT_AXIS | DIDFT_OPTIONAL | DIDFT_ANYINSTANCE; - const DWORD povType = DIDFT_POV | DIDFT_OPTIONAL | DIDFT_ANYINSTANCE; + const DWORD axisType = DIDFT_AXIS | DIDFT_OPTIONAL | DIDFT_ANYINSTANCE; + const DWORD povType = DIDFT_POV | DIDFT_OPTIONAL | DIDFT_ANYINSTANCE; const DWORD buttonType = DIDFT_BUTTON | DIDFT_OPTIONAL | DIDFT_ANYINSTANCE; static DIOBJECTDATAFORMAT data[8 * 4 + 4 + sf::Joystick::ButtonCount]; @@ -603,16 +629,16 @@ bool JoystickImpl::openDInput(unsigned int index) data[8 * i + 7].pguid = &guids::GUID_Slider; } - data[ 0].dwOfs = DIJOFS_X; - data[ 1].dwOfs = DIJOFS_Y; - data[ 2].dwOfs = DIJOFS_Z; - data[ 3].dwOfs = DIJOFS_RX; - data[ 4].dwOfs = DIJOFS_RY; - data[ 5].dwOfs = DIJOFS_RZ; - data[ 6].dwOfs = DIJOFS_SLIDER(0); - data[ 7].dwOfs = DIJOFS_SLIDER(1); - data[ 8].dwOfs = FIELD_OFFSET(DIJOYSTATE2, lVX); - data[ 9].dwOfs = FIELD_OFFSET(DIJOYSTATE2, lVY); + data[0].dwOfs = DIJOFS_X; + data[1].dwOfs = DIJOFS_Y; + data[2].dwOfs = DIJOFS_Z; + data[3].dwOfs = DIJOFS_RX; + data[4].dwOfs = DIJOFS_RY; + data[5].dwOfs = DIJOFS_RZ; + data[6].dwOfs = DIJOFS_SLIDER(0); + data[7].dwOfs = DIJOFS_SLIDER(1); + data[8].dwOfs = FIELD_OFFSET(DIJOYSTATE2, lVX); + data[9].dwOfs = FIELD_OFFSET(DIJOYSTATE2, lVY); data[10].dwOfs = FIELD_OFFSET(DIJOYSTATE2, lVZ); data[11].dwOfs = FIELD_OFFSET(DIJOYSTATE2, lVRx); data[12].dwOfs = FIELD_OFFSET(DIJOYSTATE2, lVRy); @@ -638,32 +664,32 @@ bool JoystickImpl::openDInput(unsigned int index) for (int i = 0; i < 8 * 4; ++i) { - data[i].dwType = axisType; + data[i].dwType = axisType; data[i].dwFlags = 0; } for (int i = 0; i < 4; ++i) { - data[8 * 4 + i].pguid = &guids::GUID_POV; - data[8 * 4 + i].dwOfs = static_cast(DIJOFS_POV(static_cast(i))); - data[8 * 4 + i].dwType = povType; + data[8 * 4 + i].pguid = &guids::GUID_POV; + data[8 * 4 + i].dwOfs = static_cast(DIJOFS_POV(static_cast(i))); + data[8 * 4 + i].dwType = povType; data[8 * 4 + i].dwFlags = 0; } for (int i = 0; i < sf::Joystick::ButtonCount; ++i) { - data[8 * 4 + 4 + i].pguid = nullptr; - data[8 * 4 + 4 + i].dwOfs = static_cast(DIJOFS_BUTTON(i)); - data[8 * 4 + 4 + i].dwType = buttonType; + data[8 * 4 + 4 + i].pguid = nullptr; + data[8 * 4 + 4 + i].dwOfs = static_cast(DIJOFS_BUTTON(i)); + data[8 * 4 + 4 + i].dwType = buttonType; data[8 * 4 + 4 + i].dwFlags = 0; } - format.dwSize = sizeof(DIDATAFORMAT); - format.dwObjSize = sizeof(DIOBJECTDATAFORMAT); - format.dwFlags = DIDFT_ABSAXIS; + format.dwSize = sizeof(DIDATAFORMAT); + format.dwObjSize = sizeof(DIOBJECTDATAFORMAT); + format.dwFlags = DIDFT_ABSAXIS; format.dwDataSize = sizeof(DIJOYSTATE2); - format.dwNumObjs = 8 * 4 + 4 + sf::Joystick::ButtonCount; - format.rgodf = data; + format.dwNumObjs = 8 * 4 + 4 + sf::Joystick::ButtonCount; + format.rgodf = data; formatInitialized = true; } @@ -695,7 +721,9 @@ bool JoystickImpl::openDInput(unsigned int index) } // Enumerate device objects (axes/povs/buttons) - result = m_device->EnumObjects(&JoystickImpl::deviceObjectEnumerationCallback, this, DIDFT_AXIS | DIDFT_BUTTON | DIDFT_POV); + result = m_device->EnumObjects(&JoystickImpl::deviceObjectEnumerationCallback, + this, + DIDFT_AXIS | DIDFT_BUTTON | DIDFT_POV); if (FAILED(result)) { @@ -713,10 +741,10 @@ bool JoystickImpl::openDInput(unsigned int index) if (axis != -1) { std::memset(&property, 0, sizeof(property)); - property.diph.dwSize = sizeof(property); + property.diph.dwSize = sizeof(property); property.diph.dwHeaderSize = sizeof(property.diph); - property.diph.dwHow = DIPH_DEVICE; - property.diph.dwObj = 0; + property.diph.dwHow = DIPH_DEVICE; + property.diph.dwObj = 0; result = m_device->GetProperty(DIPROP_AXISMODE, &property.diph); @@ -736,19 +764,19 @@ bool JoystickImpl::openDInput(unsigned int index) break; std::memset(&property, 0, sizeof(property)); - property.diph.dwSize = sizeof(property); + property.diph.dwSize = sizeof(property); property.diph.dwHeaderSize = sizeof(property.diph); - property.diph.dwHow = DIPH_DEVICE; - property.dwData = DIPROPAXISMODE_ABS; + property.diph.dwHow = DIPH_DEVICE; + property.dwData = DIPROPAXISMODE_ABS; m_device->SetProperty(DIPROP_AXISMODE, &property.diph); // Check if the axis mode has been set to absolute std::memset(&property, 0, sizeof(property)); - property.diph.dwSize = sizeof(property); + property.diph.dwSize = sizeof(property); property.diph.dwHeaderSize = sizeof(property.diph); - property.diph.dwHow = DIPH_DEVICE; - property.diph.dwObj = 0; + property.diph.dwHow = DIPH_DEVICE; + property.diph.dwObj = 0; result = m_device->GetProperty(DIPROP_AXISMODE, &property.diph); @@ -770,7 +798,7 @@ bool JoystickImpl::openDInput(unsigned int index) { JoystickBlacklistEntry entry; - entry.vendorId = m_identification.vendorId; + entry.vendorId = m_identification.vendorId; entry.productId = m_identification.productId; joystickBlacklist.push_back(entry); @@ -789,10 +817,10 @@ bool JoystickImpl::openDInput(unsigned int index) // Try to enable buffering by setting the buffer size std::memset(&property, 0, sizeof(property)); - property.diph.dwSize = sizeof(property); + property.diph.dwSize = sizeof(property); property.diph.dwHeaderSize = sizeof(property.diph); - property.diph.dwHow = DIPH_DEVICE; - property.dwData = directInputEventBufferSize; + property.diph.dwHow = DIPH_DEVICE; + property.dwData = directInputEventBufferSize; result = m_device->SetProperty(DIPROP_BUFFERSIZE, &property.diph); @@ -869,7 +897,7 @@ JoystickState JoystickImpl::updateDInputBuffered() return m_state; DIDEVICEOBJECTDATA events[directInputEventBufferSize]; - DWORD eventCount = directInputEventBufferSize; + DWORD eventCount = directInputEventBufferSize; // Try to get the device data HRESULT result = m_device->GetDeviceData(sizeof(DIDEVICEOBJECTDATA), events, &eventCount, 0); @@ -998,7 +1026,8 @@ JoystickState JoystickImpl::updateDInputPolled() { if ((i == Joystick::PovX) || (i == Joystick::PovY)) { - unsigned short value = LOWORD(*reinterpret_cast(reinterpret_cast(&joystate) + m_axes[i])); + unsigned short value = LOWORD( + *reinterpret_cast(reinterpret_cast(&joystate) + m_axes[i])); if (value != 0xFFFF) { @@ -1015,7 +1044,10 @@ JoystickState JoystickImpl::updateDInputPolled() } else { - state.axes[i] = (static_cast(*reinterpret_cast(reinterpret_cast(&joystate) + m_axes[i])) + 0.5f) * 100.f / 32767.5f; + state.axes[i] = (static_cast(*reinterpret_cast( + reinterpret_cast(&joystate) + m_axes[i])) + + 0.5f) * + 100.f / 32767.5f; } } else @@ -1059,7 +1091,7 @@ BOOL CALLBACK JoystickImpl::deviceEnumerationCallback(const DIDEVICEINSTANCE* de } } - JoystickRecord record = { deviceInstance->guidInstance, sf::Joystick::Count, true }; + JoystickRecord record = {deviceInstance->guidInstance, sf::Joystick::Count, true}; joystickList.push_back(record); return DIENUM_CONTINUE; @@ -1088,7 +1120,7 @@ BOOL CALLBACK JoystickImpl::deviceObjectEnumerationCallback(const DIDEVICEOBJECT joystick.m_axes[Joystick::V] = DIJOFS_RY; else if (deviceObjectInstance->guidType == guids::GUID_Slider) { - if(joystick.m_axes[Joystick::U] == -1) + if (joystick.m_axes[Joystick::U] == -1) joystick.m_axes[Joystick::U] = DIJOFS_SLIDER(0); else joystick.m_axes[Joystick::V] = DIJOFS_SLIDER(1); @@ -1100,12 +1132,12 @@ BOOL CALLBACK JoystickImpl::deviceObjectEnumerationCallback(const DIDEVICEOBJECT DIPROPRANGE propertyRange; std::memset(&propertyRange, 0, sizeof(propertyRange)); - propertyRange.diph.dwSize = sizeof(propertyRange); + propertyRange.diph.dwSize = sizeof(propertyRange); propertyRange.diph.dwHeaderSize = sizeof(propertyRange.diph); - propertyRange.diph.dwObj = deviceObjectInstance->dwType; - propertyRange.diph.dwHow = DIPH_BYID; - propertyRange.lMin = -32768; - propertyRange.lMax = 32767; + propertyRange.diph.dwObj = deviceObjectInstance->dwType; + propertyRange.diph.dwHow = DIPH_BYID; + propertyRange.lMin = -32768; + propertyRange.lMax = 32767; HRESULT result = joystick.m_device->SetProperty(DIPROP_RANGE, &propertyRange.diph); diff --git a/src/SFML/Window/Win32/JoystickImpl.hpp b/src/SFML/Window/Win32/JoystickImpl.hpp index caa7f8ef2..91232b3c8 100644 --- a/src/SFML/Window/Win32/JoystickImpl.hpp +++ b/src/SFML/Window/Win32/JoystickImpl.hpp @@ -28,11 +28,12 @@ //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// +#include #include #include -#include -#include + #include +#include namespace sf @@ -46,7 +47,6 @@ namespace priv class JoystickImpl { public: - //////////////////////////////////////////////////////////// /// \brief Perform the global initialization of the joystick module /// @@ -192,7 +192,6 @@ public: [[nodiscard]] JoystickState updateDInputPolled(); private: - //////////////////////////////////////////////////////////// /// \brief Device enumeration callback function passed to EnumDevices in updateConnections /// @@ -218,15 +217,15 @@ private: //////////////////////////////////////////////////////////// // Member data //////////////////////////////////////////////////////////// - unsigned int m_index; //!< Index of the joystick - JOYCAPS m_caps; //!< Joystick capabilities - IDirectInputDevice8W* m_device; //!< DirectInput 8.x device - DIDEVCAPS m_deviceCaps; //!< DirectInput device capabilities - int m_axes[Joystick::AxisCount]; //!< Offsets to the bytes containing the axes states, -1 if not available - int m_buttons[Joystick::ButtonCount]; //!< Offsets to the bytes containing the button states, -1 if not available - Joystick::Identification m_identification; //!< Joystick identification - JoystickState m_state; //!< Buffered joystick state - bool m_buffered; //!< true if the device uses buffering, false if the device uses polling + unsigned int m_index; //!< Index of the joystick + JOYCAPS m_caps; //!< Joystick capabilities + IDirectInputDevice8W* m_device; //!< DirectInput 8.x device + DIDEVCAPS m_deviceCaps; //!< DirectInput device capabilities + int m_axes[Joystick::AxisCount]; //!< Offsets to the bytes containing the axes states, -1 if not available + int m_buttons[Joystick::ButtonCount]; //!< Offsets to the bytes containing the button states, -1 if not available + Joystick::Identification m_identification; //!< Joystick identification + JoystickState m_state; //!< Buffered joystick state + bool m_buffered; //!< true if the device uses buffering, false if the device uses polling }; } // namespace priv diff --git a/src/SFML/Window/Win32/SensorImpl.hpp b/src/SFML/Window/Win32/SensorImpl.hpp index de22fcbca..06f3ff8dc 100644 --- a/src/SFML/Window/Win32/SensorImpl.hpp +++ b/src/SFML/Window/Win32/SensorImpl.hpp @@ -42,7 +42,6 @@ namespace priv class SensorImpl { public: - //////////////////////////////////////////////////////////// /// \brief Perform the global initialization of the sensor module /// diff --git a/src/SFML/Window/Win32/VideoModeImpl.cpp b/src/SFML/Window/Win32/VideoModeImpl.cpp index 5ba44551f..47c3d6fc8 100644 --- a/src/SFML/Window/Win32/VideoModeImpl.cpp +++ b/src/SFML/Window/Win32/VideoModeImpl.cpp @@ -25,8 +25,9 @@ //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// -#include #include +#include + #include @@ -41,7 +42,7 @@ std::vector VideoModeImpl::getFullscreenModes() // Enumerate all available video modes for the primary display adapter DEVMODE win32Mode; - win32Mode.dmSize = sizeof(win32Mode); + win32Mode.dmSize = sizeof(win32Mode); win32Mode.dmDriverExtra = 0; for (int count = 0; EnumDisplaySettings(nullptr, static_cast(count), &win32Mode); ++count) { @@ -61,7 +62,7 @@ std::vector VideoModeImpl::getFullscreenModes() VideoMode VideoModeImpl::getDesktopMode() { DEVMODE win32Mode; - win32Mode.dmSize = sizeof(win32Mode); + win32Mode.dmSize = sizeof(win32Mode); win32Mode.dmDriverExtra = 0; EnumDisplaySettings(nullptr, ENUM_CURRENT_SETTINGS, &win32Mode); diff --git a/src/SFML/Window/Win32/VulkanImplWin32.cpp b/src/SFML/Window/Win32/VulkanImplWin32.cpp index 3e1350292..11cf7a904 100644 --- a/src/SFML/Window/Win32/VulkanImplWin32.cpp +++ b/src/SFML/Window/Win32/VulkanImplWin32.cpp @@ -25,86 +25,87 @@ //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// -#include #include +#include + +#include +#include +#include #define VK_USE_PLATFORM_WIN32_KHR #define VK_NO_PROTOTYPES #include -#include -#include -#include namespace { - struct VulkanLibraryWrapper +struct VulkanLibraryWrapper +{ + VulkanLibraryWrapper() : + library(nullptr), + vkGetInstanceProcAddr(nullptr), + vkEnumerateInstanceLayerProperties(nullptr), + vkEnumerateInstanceExtensionProperties(nullptr) { - VulkanLibraryWrapper() : - library(nullptr), - vkGetInstanceProcAddr(nullptr), - vkEnumerateInstanceLayerProperties(nullptr), - vkEnumerateInstanceExtensionProperties(nullptr) - { - } + } - ~VulkanLibraryWrapper() - { - if (library) - FreeLibrary(library); - } - - // Try to load the library and all the required entry points - bool loadLibrary() - { - if (library) - return true; - - library = LoadLibraryA("vulkan-1.dll"); - - if (!library) - return false; - - if (!loadEntryPoint(vkGetInstanceProcAddr, "vkGetInstanceProcAddr")) - { - FreeLibrary(library); - library = nullptr; - return false; - } - - if (!loadEntryPoint(vkEnumerateInstanceLayerProperties, "vkEnumerateInstanceLayerProperties")) - { - FreeLibrary(library); - library = nullptr; - return false; - } - - if (!loadEntryPoint(vkEnumerateInstanceExtensionProperties, "vkEnumerateInstanceExtensionProperties")) - { - FreeLibrary(library); - library = nullptr; - return false; - } + ~VulkanLibraryWrapper() + { + if (library) + FreeLibrary(library); + } + // Try to load the library and all the required entry points + bool loadLibrary() + { + if (library) return true; - } - template - bool loadEntryPoint(T& entryPoint, const char* name) + library = LoadLibraryA("vulkan-1.dll"); + + if (!library) + return false; + + if (!loadEntryPoint(vkGetInstanceProcAddr, "vkGetInstanceProcAddr")) { - entryPoint = reinterpret_cast(reinterpret_cast(GetProcAddress(library, name))); - - return (entryPoint != nullptr); + FreeLibrary(library); + library = nullptr; + return false; } - HMODULE library; + if (!loadEntryPoint(vkEnumerateInstanceLayerProperties, "vkEnumerateInstanceLayerProperties")) + { + FreeLibrary(library); + library = nullptr; + return false; + } - PFN_vkGetInstanceProcAddr vkGetInstanceProcAddr; - PFN_vkEnumerateInstanceLayerProperties vkEnumerateInstanceLayerProperties; - PFN_vkEnumerateInstanceExtensionProperties vkEnumerateInstanceExtensionProperties; - }; + if (!loadEntryPoint(vkEnumerateInstanceExtensionProperties, "vkEnumerateInstanceExtensionProperties")) + { + FreeLibrary(library); + library = nullptr; + return false; + } - VulkanLibraryWrapper wrapper; -} + return true; + } + + template + bool loadEntryPoint(T& entryPoint, const char* name) + { + entryPoint = reinterpret_cast(reinterpret_cast(GetProcAddress(library, name))); + + return (entryPoint != nullptr); + } + + HMODULE library; + + PFN_vkGetInstanceProcAddr vkGetInstanceProcAddr; + PFN_vkEnumerateInstanceLayerProperties vkEnumerateInstanceLayerProperties; + PFN_vkEnumerateInstanceExtensionProperties vkEnumerateInstanceExtensionProperties; +}; + +VulkanLibraryWrapper wrapper; +} // namespace namespace sf @@ -114,8 +115,8 @@ namespace priv //////////////////////////////////////////////////////////// bool VulkanImplWin32::isAvailable(bool requireGraphics) { - static bool checked = false; - static bool computeAvailable = false; + static bool checked = false; + static bool computeAvailable = false; static bool graphicsAvailable = false; if (!checked) @@ -142,7 +143,7 @@ bool VulkanImplWin32::isAvailable(bool requireGraphics) wrapper.vkEnumerateInstanceExtensionProperties(nullptr, &extensionCount, extensionProperties.data()); // Check if the necessary extensions are available - bool has_VK_KHR_surface = false; + bool has_VK_KHR_surface = false; bool has_VK_KHR_platform_surface = false; for (const VkExtensionProperties& properties : extensionProperties) @@ -195,7 +196,10 @@ const std::vector& VulkanImplWin32::getGraphicsRequiredInstanceExte //////////////////////////////////////////////////////////// -bool VulkanImplWin32::createVulkanSurface(const VkInstance& instance, WindowHandle windowHandle, VkSurfaceKHR& surface, const VkAllocationCallbacks* allocator) +bool VulkanImplWin32::createVulkanSurface(const VkInstance& instance, + WindowHandle windowHandle, + VkSurfaceKHR& surface, + const VkAllocationCallbacks* allocator) { if (!isAvailable()) return false; @@ -203,15 +207,16 @@ bool VulkanImplWin32::createVulkanSurface(const VkInstance& instance, WindowHand // Make a copy of the instance handle since we get it passed as a reference VkInstance inst = instance; - auto vkCreateWin32SurfaceKHR = reinterpret_cast(wrapper.vkGetInstanceProcAddr(inst, "vkCreateWin32SurfaceKHR")); + auto vkCreateWin32SurfaceKHR = reinterpret_cast( + wrapper.vkGetInstanceProcAddr(inst, "vkCreateWin32SurfaceKHR")); if (!vkCreateWin32SurfaceKHR) return false; VkWin32SurfaceCreateInfoKHR surfaceCreateInfo = VkWin32SurfaceCreateInfoKHR(); - surfaceCreateInfo.sType = VK_STRUCTURE_TYPE_WIN32_SURFACE_CREATE_INFO_KHR; - surfaceCreateInfo.hinstance = GetModuleHandleA(nullptr); - surfaceCreateInfo.hwnd = windowHandle; + surfaceCreateInfo.sType = VK_STRUCTURE_TYPE_WIN32_SURFACE_CREATE_INFO_KHR; + surfaceCreateInfo.hinstance = GetModuleHandleA(nullptr); + surfaceCreateInfo.hwnd = windowHandle; return (vkCreateWin32SurfaceKHR(instance, &surfaceCreateInfo, allocator, &surface) == VK_SUCCESS); } diff --git a/src/SFML/Window/Win32/VulkanImplWin32.hpp b/src/SFML/Window/Win32/VulkanImplWin32.hpp index f11b6351a..5b573f556 100644 --- a/src/SFML/Window/Win32/VulkanImplWin32.hpp +++ b/src/SFML/Window/Win32/VulkanImplWin32.hpp @@ -30,6 +30,7 @@ //////////////////////////////////////////////////////////// #include #include + #include @@ -44,7 +45,6 @@ namespace priv class VulkanImplWin32 { public: - //////////////////////////////////////////////////////////// /// \brief Tell whether or not the system supports Vulkan /// @@ -92,7 +92,10 @@ public: /// \return True if surface creation was successful, false otherwise /// //////////////////////////////////////////////////////////// - static bool createVulkanSurface(const VkInstance& instance, WindowHandle windowHandle, VkSurfaceKHR& surface, const VkAllocationCallbacks* allocator); + static bool createVulkanSurface(const VkInstance& instance, + WindowHandle windowHandle, + VkSurfaceKHR& surface, + const VkAllocationCallbacks* allocator); }; } // namespace priv diff --git a/src/SFML/Window/Win32/WglContext.cpp b/src/SFML/Window/Win32/WglContext.cpp index dbdbe2745..9ff15fc9d 100644 --- a/src/SFML/Window/Win32/WglContext.cpp +++ b/src/SFML/Window/Win32/WglContext.cpp @@ -25,9 +25,10 @@ //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// -#include // included first to avoid a warning about macro redefinition -#include #include +#include +#include + #include #include #include @@ -43,43 +44,43 @@ namespace { - namespace WglContextImpl +namespace WglContextImpl +{ +// Some drivers are bugged and don't track the current HDC/HGLRC properly +// In order to deactivate successfully, we need to track it ourselves as well +thread_local sf::priv::WglContext* currentContext(nullptr); + + +//////////////////////////////////////////////////////////// +void ensureInit() +{ + static bool initialized = false; + if (!initialized) { - // Some drivers are bugged and don't track the current HDC/HGLRC properly - // In order to deactivate successfully, we need to track it ourselves as well - thread_local sf::priv::WglContext* currentContext(nullptr); + initialized = true; - - //////////////////////////////////////////////////////////// - void ensureInit() - { - static bool initialized = false; - if (!initialized) - { - initialized = true; - - gladLoadWGL(nullptr, sf::priv::WglContext::getFunction); - } - } - - - //////////////////////////////////////////////////////////// - void ensureExtensionsInit(HDC deviceContext) - { - static bool initialized = false; - if (!initialized) - { - initialized = true; - - // We don't check the return value since the extension - // flags are cleared even if loading fails - gladLoadWGL(deviceContext, sf::priv::WglContext::getFunction); - } - } + gladLoadWGL(nullptr, sf::priv::WglContext::getFunction); } } +//////////////////////////////////////////////////////////// +void ensureExtensionsInit(HDC deviceContext) +{ + static bool initialized = false; + if (!initialized) + { + initialized = true; + + // We don't check the return value since the extension + // flags are cleared even if loading fails + gladLoadWGL(deviceContext, sf::priv::WglContext::getFunction); + } +} +} // namespace WglContextImpl +} // namespace + + namespace sf { namespace priv @@ -88,7 +89,14 @@ namespace priv String getErrorString(DWORD errorCode) { PTCHAR buffer; - if (FormatMessage(FORMAT_MESSAGE_MAX_WIDTH_MASK | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, nullptr, errorCode, 0, reinterpret_cast(&buffer), 256, nullptr) != 0) + if (FormatMessage(FORMAT_MESSAGE_MAX_WIDTH_MASK | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | + FORMAT_MESSAGE_IGNORE_INSERTS, + nullptr, + errorCode, + 0, + reinterpret_cast(&buffer), + 256, + nullptr) != 0) { String errMsg(buffer); LocalFree(buffer); @@ -102,19 +110,18 @@ String getErrorString(DWORD errorCode) //////////////////////////////////////////////////////////// -WglContext::WglContext(WglContext* shared) : -WglContext(shared, ContextSettings(), {1u, 1u}) +WglContext::WglContext(WglContext* shared) : WglContext(shared, ContextSettings(), {1u, 1u}) { } //////////////////////////////////////////////////////////// WglContext::WglContext(WglContext* shared, const ContextSettings& settings, const WindowImpl& owner, unsigned int bitsPerPixel) : -m_window (nullptr), -m_pbuffer (nullptr), +m_window(nullptr), +m_pbuffer(nullptr), m_deviceContext(nullptr), -m_context (nullptr), -m_ownsWindow (false) +m_context(nullptr), +m_ownsWindow(false) { WglContextImpl::ensureInit(); @@ -131,11 +138,11 @@ m_ownsWindow (false) //////////////////////////////////////////////////////////// WglContext::WglContext(WglContext* shared, const ContextSettings& settings, const Vector2u& size) : -m_window (nullptr), -m_pbuffer (nullptr), +m_window(nullptr), +m_pbuffer(nullptr), m_deviceContext(nullptr), -m_context (nullptr), -m_ownsWindow (false) +m_context(nullptr), +m_ownsWindow(false) { WglContextImpl::ensureInit(); @@ -222,7 +229,8 @@ bool WglContext::makeCurrent(bool current) if (wglMakeCurrent(m_deviceContext, current ? m_context : nullptr) == FALSE) { - err() << "Failed to " << (current ? "activate" : "deactivate") << " OpenGL context: " << getErrorString(GetLastError()).toAnsiString() << std::endl; + err() << "Failed to " << (current ? "activate" : "deactivate") + << " OpenGL context: " << getErrorString(GetLastError()).toAnsiString() << std::endl; return false; } @@ -276,17 +284,19 @@ int WglContext::selectBestPixelFormat(HDC deviceContext, unsigned int bitsPerPix if (SF_GLAD_WGL_ARB_pixel_format) { // Define the basic attributes we want for our window - int intAttributes[] = - { - WGL_DRAW_TO_WINDOW_ARB, GL_TRUE, - WGL_SUPPORT_OPENGL_ARB, GL_TRUE, - WGL_DOUBLE_BUFFER_ARB, GL_TRUE, - WGL_PIXEL_TYPE_ARB, WGL_TYPE_RGBA_ARB, - 0, 0 - }; + int intAttributes[] = {WGL_DRAW_TO_WINDOW_ARB, + GL_TRUE, + WGL_SUPPORT_OPENGL_ARB, + GL_TRUE, + WGL_DOUBLE_BUFFER_ARB, + GL_TRUE, + WGL_PIXEL_TYPE_ARB, + WGL_TYPE_RGBA_ARB, + 0, + 0}; // Let's check how many formats are supporting our requirements - int formats[512]; + int formats[512]; UINT nbFormats = 0; // We must initialize to 0 otherwise broken drivers might fill with garbage in the following call bool isValid = wglChoosePixelFormatARB(deviceContext, intAttributes, nullptr, 512, formats, &nbFormats) != FALSE; @@ -300,36 +310,32 @@ int WglContext::selectBestPixelFormat(HDC deviceContext, unsigned int bitsPerPix for (UINT i = 0; i < nbFormats; ++i) { // Extract the components of the current format - int values[7]; - const int attributes[] = - { - WGL_RED_BITS_ARB, - WGL_GREEN_BITS_ARB, - WGL_BLUE_BITS_ARB, - WGL_ALPHA_BITS_ARB, - WGL_DEPTH_BITS_ARB, - WGL_STENCIL_BITS_ARB, - WGL_ACCELERATION_ARB - }; + int values[7]; + const int attributes[] = {WGL_RED_BITS_ARB, + WGL_GREEN_BITS_ARB, + WGL_BLUE_BITS_ARB, + WGL_ALPHA_BITS_ARB, + WGL_DEPTH_BITS_ARB, + WGL_STENCIL_BITS_ARB, + WGL_ACCELERATION_ARB}; if (wglGetPixelFormatAttribivARB(deviceContext, formats[i], PFD_MAIN_PLANE, 7, attributes, values) == FALSE) { - err() << "Failed to retrieve pixel format information: " << getErrorString(GetLastError()).toAnsiString() << std::endl; + err() << "Failed to retrieve pixel format information: " + << getErrorString(GetLastError()).toAnsiString() << std::endl; break; } int sampleValues[2] = {0, 0}; if (SF_GLAD_WGL_ARB_multisample) { - const int sampleAttributes[] = - { - WGL_SAMPLE_BUFFERS_ARB, - WGL_SAMPLES_ARB - }; + const int sampleAttributes[] = {WGL_SAMPLE_BUFFERS_ARB, WGL_SAMPLES_ARB}; - if (wglGetPixelFormatAttribivARB(deviceContext, formats[i], PFD_MAIN_PLANE, 2, sampleAttributes, sampleValues) == FALSE) + if (wglGetPixelFormatAttribivARB(deviceContext, formats[i], PFD_MAIN_PLANE, 2, sampleAttributes, sampleValues) == + FALSE) { - err() << "Failed to retrieve pixel format multisampling information: " << getErrorString(GetLastError()).toAnsiString() << std::endl; + err() << "Failed to retrieve pixel format multisampling information: " + << getErrorString(GetLastError()).toAnsiString() << std::endl; break; } } @@ -339,25 +345,26 @@ int WglContext::selectBestPixelFormat(HDC deviceContext, unsigned int bitsPerPix { const int sRgbCapableAttribute = WGL_FRAMEBUFFER_SRGB_CAPABLE_ARB; - if (wglGetPixelFormatAttribivARB(deviceContext, formats[i], PFD_MAIN_PLANE, 1, &sRgbCapableAttribute, &sRgbCapableValue) == FALSE) + if (wglGetPixelFormatAttribivARB(deviceContext, formats[i], PFD_MAIN_PLANE, 1, &sRgbCapableAttribute, &sRgbCapableValue) == + FALSE) { - err() << "Failed to retrieve pixel format sRGB capability information: " << getErrorString(GetLastError()).toAnsiString() << std::endl; + err() << "Failed to retrieve pixel format sRGB capability information: " + << getErrorString(GetLastError()).toAnsiString() << std::endl; break; } } if (pbuffer) { - const int pbufferAttributes[] = - { - WGL_DRAW_TO_PBUFFER_ARB - }; + const int pbufferAttributes[] = {WGL_DRAW_TO_PBUFFER_ARB}; int pbufferValue = 0; - if (wglGetPixelFormatAttribivARB(deviceContext, formats[i], PFD_MAIN_PLANE, 1, pbufferAttributes, &pbufferValue) == FALSE) + if (wglGetPixelFormatAttribivARB(deviceContext, formats[i], PFD_MAIN_PLANE, 1, pbufferAttributes, &pbufferValue) == + FALSE) { - err() << "Failed to retrieve pixel format pbuffer information: " << getErrorString(GetLastError()).toAnsiString() << std::endl; + err() << "Failed to retrieve pixel format pbuffer information: " + << getErrorString(GetLastError()).toAnsiString() << std::endl; break; } @@ -367,7 +374,14 @@ int WglContext::selectBestPixelFormat(HDC deviceContext, unsigned int bitsPerPix // Evaluate the current configuration int color = values[0] + values[1] + values[2] + values[3]; - int score = evaluateFormat(bitsPerPixel, settings, color, values[4], values[5], sampleValues[0] ? sampleValues[1] : 0, values[6] == WGL_FULL_ACCELERATION_ARB, sRgbCapableValue == TRUE); + int score = evaluateFormat(bitsPerPixel, + settings, + color, + values[4], + values[5], + sampleValues[0] ? sampleValues[1] : 0, + values[6] == WGL_FULL_ACCELERATION_ARB, + sRgbCapableValue == TRUE); // Keep it if it's better than the current best if (score < bestScore) @@ -414,7 +428,8 @@ void WglContext::setDevicePixelFormat(unsigned int bitsPerPixel) if (bestFormat == 0) { - err() << "Failed to find a suitable pixel format for device context: " << getErrorString(GetLastError()).toAnsiString() << '\n' + err() << "Failed to find a suitable pixel format for device context: " + << getErrorString(GetLastError()).toAnsiString() << '\n' << "Cannot create OpenGL context" << std::endl; return; } @@ -452,14 +467,15 @@ void WglContext::updateSettingsFromPixelFormat() if (DescribePixelFormat(m_deviceContext, format, sizeof(actualFormat), &actualFormat) == 0) { - err() << "Failed to retrieve pixel format information: " << getErrorString(GetLastError()).toAnsiString() << std::endl; + err() << "Failed to retrieve pixel format information: " << getErrorString(GetLastError()).toAnsiString() + << std::endl; return; } if (SF_GLAD_WGL_ARB_pixel_format) { const int attributes[] = {WGL_DEPTH_BITS_ARB, WGL_STENCIL_BITS_ARB}; - int values[2]; + int values[2]; if (wglGetPixelFormatAttribivARB(m_deviceContext, format, PFD_MAIN_PLANE, 2, attributes, values) == TRUE) { @@ -468,7 +484,8 @@ void WglContext::updateSettingsFromPixelFormat() } else { - err() << "Failed to retrieve pixel format information: " << getErrorString(GetLastError()).toAnsiString() << std::endl; + err() << "Failed to retrieve pixel format information: " << getErrorString(GetLastError()).toAnsiString() + << std::endl; m_settings.depthBits = actualFormat.cDepthBits; m_settings.stencilBits = actualFormat.cStencilBits; } @@ -476,15 +493,17 @@ void WglContext::updateSettingsFromPixelFormat() if (SF_GLAD_WGL_ARB_multisample) { const int sampleAttributes[] = {WGL_SAMPLE_BUFFERS_ARB, WGL_SAMPLES_ARB}; - int sampleValues[2]; + int sampleValues[2]; - if (wglGetPixelFormatAttribivARB(m_deviceContext, format, PFD_MAIN_PLANE, 2, sampleAttributes, sampleValues) == TRUE) + if (wglGetPixelFormatAttribivARB(m_deviceContext, format, PFD_MAIN_PLANE, 2, sampleAttributes, sampleValues) == + TRUE) { m_settings.antialiasingLevel = static_cast(sampleValues[0] ? sampleValues[1] : 0); } else { - err() << "Failed to retrieve pixel format multisampling information: " << getErrorString(GetLastError()).toAnsiString() << std::endl; + err() << "Failed to retrieve pixel format multisampling information: " + << getErrorString(GetLastError()).toAnsiString() << std::endl; m_settings.antialiasingLevel = 0; } } @@ -496,15 +515,17 @@ void WglContext::updateSettingsFromPixelFormat() if (SF_GLAD_WGL_ARB_framebuffer_sRGB || SF_GLAD_WGL_EXT_framebuffer_sRGB) { const int sRgbCapableAttribute = WGL_FRAMEBUFFER_SRGB_CAPABLE_ARB; - int sRgbCapableValue = 0; + int sRgbCapableValue = 0; - if (wglGetPixelFormatAttribivARB(m_deviceContext, format, PFD_MAIN_PLANE, 1, &sRgbCapableAttribute, &sRgbCapableValue) == TRUE) + if (wglGetPixelFormatAttribivARB(m_deviceContext, format, PFD_MAIN_PLANE, 1, &sRgbCapableAttribute, &sRgbCapableValue) == + TRUE) { m_settings.sRgbCapable = (sRgbCapableValue == TRUE); } else { - err() << "Failed to retrieve pixel format sRGB capability information: " << getErrorString(GetLastError()).toAnsiString() << std::endl; + err() << "Failed to retrieve pixel format sRGB capability information: " + << getErrorString(GetLastError()).toAnsiString() << std::endl; m_settings.sRgbCapable = false; } } @@ -515,8 +536,8 @@ void WglContext::updateSettingsFromPixelFormat() } else { - m_settings.depthBits = actualFormat.cDepthBits; - m_settings.stencilBits = actualFormat.cStencilBits; + m_settings.depthBits = actualFormat.cDepthBits; + m_settings.stencilBits = actualFormat.cStencilBits; m_settings.antialiasingLevel = 0; } } @@ -534,16 +555,21 @@ void WglContext::createSurface(WglContext* shared, const Vector2u& size, unsigne { int attributes[] = {0, 0}; - m_pbuffer = wglCreatePbufferARB(shared->m_deviceContext, bestFormat, static_cast(size.x), static_cast(size.y), attributes); + m_pbuffer = wglCreatePbufferARB(shared->m_deviceContext, + bestFormat, + static_cast(size.x), + static_cast(size.y), + attributes); if (m_pbuffer) { - m_window = shared->m_window; + m_window = shared->m_window; m_deviceContext = wglGetPbufferDCARB(m_pbuffer); if (!m_deviceContext) { - err() << "Failed to retrieve pixel buffer device context: " << getErrorString(GetLastError()).toAnsiString() << std::endl; + err() << "Failed to retrieve pixel buffer device context: " + << getErrorString(GetLastError()).toAnsiString() << std::endl; wglDestroyPbufferARB(m_pbuffer); m_pbuffer = nullptr; @@ -563,7 +589,17 @@ void WglContext::createSurface(WglContext* shared, const Vector2u& size, unsigne // with other contexts and thus wglShareLists would always fail // Create the hidden window - m_window = CreateWindowA("STATIC", "", WS_POPUP | WS_DISABLED, 0, 0, static_cast(size.x), static_cast(size.y), nullptr, nullptr, GetModuleHandle(nullptr), nullptr); + m_window = CreateWindowA("STATIC", + "", + WS_POPUP | WS_DISABLED, + 0, + 0, + static_cast(size.x), + static_cast(size.y), + nullptr, + nullptr, + GetModuleHandle(nullptr), + nullptr); ShowWindow(m_window, SW_HIDE); m_deviceContext = GetDC(m_window); @@ -581,7 +617,7 @@ void WglContext::createSurface(WglContext* shared, const Vector2u& size, unsigne //////////////////////////////////////////////////////////// void WglContext::createSurface(HWND window, unsigned int bitsPerPixel) { - m_window = window; + m_window = window; m_deviceContext = GetDC(window); // Set the pixel format of the device context @@ -624,8 +660,10 @@ void WglContext::createContext(WglContext* shared) // Check if setting the profile is supported if (SF_GLAD_WGL_ARB_create_context_profile) { - int profile = (m_settings.attributeFlags & ContextSettings::Core) ? WGL_CONTEXT_CORE_PROFILE_BIT_ARB : WGL_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB; - int debug = (m_settings.attributeFlags & ContextSettings::Debug) ? WGL_CONTEXT_DEBUG_BIT_ARB : 0; + int profile = (m_settings.attributeFlags & ContextSettings::Core) + ? WGL_CONTEXT_CORE_PROFILE_BIT_ARB + : WGL_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB; + int debug = (m_settings.attributeFlags & ContextSettings::Debug) ? WGL_CONTEXT_DEBUG_BIT_ARB : 0; attributes.push_back(WGL_CONTEXT_PROFILE_MASK_ARB); attributes.push_back(profile); @@ -634,7 +672,8 @@ void WglContext::createContext(WglContext* shared) } else { - if ((m_settings.attributeFlags & ContextSettings::Core) || (m_settings.attributeFlags & ContextSettings::Debug)) + if ((m_settings.attributeFlags & ContextSettings::Core) || + (m_settings.attributeFlags & ContextSettings::Debug)) err() << "Selecting a profile during context creation is not supported," << "disabling comptibility and debug" << std::endl; @@ -648,13 +687,14 @@ void WglContext::createContext(WglContext* shared) if (sharedContext) { static std::recursive_mutex mutex; - std::scoped_lock lock(mutex); + std::scoped_lock lock(mutex); if (WglContextImpl::currentContext == shared) { if (wglMakeCurrent(shared->m_deviceContext, nullptr) == FALSE) { - err() << "Failed to deactivate shared context before sharing: " << getErrorString(GetLastError()).toAnsiString() << std::endl; + err() << "Failed to deactivate shared context before sharing: " + << getErrorString(GetLastError()).toAnsiString() << std::endl; return; } @@ -702,14 +742,15 @@ void WglContext::createContext(WglContext* shared) if (!m_context) { // set the context version to 1.1 (arbitrary) and disable flags - m_settings.majorVersion = 1; - m_settings.minorVersion = 1; + m_settings.majorVersion = 1; + m_settings.minorVersion = 1; m_settings.attributeFlags = ContextSettings::Default; m_context = wglCreateContext(m_deviceContext); if (!m_context) { - err() << "Failed to create an OpenGL context for this window: " << getErrorString(GetLastError()).toAnsiString() << std::endl; + err() << "Failed to create an OpenGL context for this window: " + << getErrorString(GetLastError()).toAnsiString() << std::endl; return; } @@ -718,13 +759,14 @@ void WglContext::createContext(WglContext* shared) { // wglShareLists doesn't seem to be thread-safe static std::recursive_mutex mutex; - std::scoped_lock lock(mutex); + std::scoped_lock lock(mutex); if (WglContextImpl::currentContext == shared) { if (wglMakeCurrent(shared->m_deviceContext, nullptr) == FALSE) { - err() << "Failed to deactivate shared context before sharing: " << getErrorString(GetLastError()).toAnsiString() << std::endl; + err() << "Failed to deactivate shared context before sharing: " + << getErrorString(GetLastError()).toAnsiString() << std::endl; return; } @@ -732,7 +774,8 @@ void WglContext::createContext(WglContext* shared) } if (wglShareLists(sharedContext, m_context) == FALSE) - err() << "Failed to share the OpenGL context: " << getErrorString(GetLastError()).toAnsiString() << std::endl; + err() << "Failed to share the OpenGL context: " << getErrorString(GetLastError()).toAnsiString() + << std::endl; } } diff --git a/src/SFML/Window/Win32/WglContext.hpp b/src/SFML/Window/Win32/WglContext.hpp index 605b50a6a..36fe97e72 100644 --- a/src/SFML/Window/Win32/WglContext.hpp +++ b/src/SFML/Window/Win32/WglContext.hpp @@ -29,6 +29,7 @@ // Headers //////////////////////////////////////////////////////////// #include + #include @@ -43,7 +44,6 @@ namespace priv class WglContext : public GlContext { public: - //////////////////////////////////////////////////////////// /// \brief Create a new default context /// @@ -129,10 +129,12 @@ public: /// \return The best pixel format /// //////////////////////////////////////////////////////////// - static int selectBestPixelFormat(HDC deviceContext, unsigned int bitsPerPixel, const ContextSettings& settings, bool pbuffer = false); + static int selectBestPixelFormat(HDC deviceContext, + unsigned int bitsPerPixel, + const ContextSettings& settings, + bool pbuffer = false); private: - //////////////////////////////////////////////////////////// /// \brief Set the pixel format of the device context /// diff --git a/src/SFML/Window/Win32/WindowImplWin32.cpp b/src/SFML/Window/Win32/WindowImplWin32.cpp old mode 100755 new mode 100644 index bd9d12d40..6d03eb00b --- a/src/SFML/Window/Win32/WindowImplWin32.cpp +++ b/src/SFML/Window/Win32/WindowImplWin32.cpp @@ -25,12 +25,14 @@ //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// -#include -#include -#include #include #include #include +#include +#include +#include + +#include // dbt.h is lowercase here, as a cross-compile on linux with mingw-w64 // expects lowercase, and a native compile on windows, whether via msvc // or mingw-w64 addresses files in a case insensitive manner. @@ -38,86 +40,86 @@ #include #include -#include - // MinGW lacks the definition of some Win32 constants #ifndef XBUTTON1 - #define XBUTTON1 0x0001 +#define XBUTTON1 0x0001 #endif #ifndef XBUTTON2 - #define XBUTTON2 0x0002 +#define XBUTTON2 0x0002 #endif #ifndef WM_MOUSEHWHEEL - #define WM_MOUSEHWHEEL 0x020E +#define WM_MOUSEHWHEEL 0x020E #endif #ifndef MAPVK_VK_TO_VSC - #define MAPVK_VK_TO_VSC (0) +#define MAPVK_VK_TO_VSC (0) #endif namespace { - unsigned int windowCount = 0; // Windows owned by SFML - unsigned int handleCount = 0; // All window handles - const wchar_t* className = L"SFML_Window"; - sf::priv::WindowImplWin32* fullscreenWindow = nullptr; +unsigned int windowCount = 0; // Windows owned by SFML +unsigned int handleCount = 0; // All window handles +const wchar_t* className = L"SFML_Window"; +sf::priv::WindowImplWin32* fullscreenWindow = nullptr; - const GUID GUID_DEVINTERFACE_HID = {0x4d1e55b2, 0xf16f, 0x11cf, {0x88, 0xcb, 0x00, 0x11, 0x11, 0x00, 0x00, 0x30}}; +const GUID GUID_DEVINTERFACE_HID = {0x4d1e55b2, 0xf16f, 0x11cf, {0x88, 0xcb, 0x00, 0x11, 0x11, 0x00, 0x00, 0x30}}; - void setProcessDpiAware() +void setProcessDpiAware() +{ + // Try SetProcessDpiAwareness first + HINSTANCE shCoreDll = LoadLibrary(L"Shcore.dll"); + + if (shCoreDll) { - // Try SetProcessDpiAwareness first - HINSTANCE shCoreDll = LoadLibrary(L"Shcore.dll"); - - if (shCoreDll) + enum ProcessDpiAwareness { - enum ProcessDpiAwareness - { - ProcessDpiUnaware = 0, - ProcessSystemDpiAware = 1, - ProcessPerMonitorDpiAware = 2 - }; + ProcessDpiUnaware = 0, + ProcessSystemDpiAware = 1, + ProcessPerMonitorDpiAware = 2 + }; - using SetProcessDpiAwarenessFuncType = HRESULT (WINAPI *)(ProcessDpiAwareness); - auto SetProcessDpiAwarenessFunc = reinterpret_cast(reinterpret_cast(GetProcAddress(shCoreDll, "SetProcessDpiAwareness"))); + using SetProcessDpiAwarenessFuncType = HRESULT(WINAPI*)(ProcessDpiAwareness); + auto SetProcessDpiAwarenessFunc = reinterpret_cast( + reinterpret_cast(GetProcAddress(shCoreDll, "SetProcessDpiAwareness"))); - if (SetProcessDpiAwarenessFunc) + if (SetProcessDpiAwarenessFunc) + { + // We only check for E_INVALIDARG because we would get + // E_ACCESSDENIED if the DPI was already set previously + // and S_OK means the call was successful + if (SetProcessDpiAwarenessFunc(ProcessSystemDpiAware) == E_INVALIDARG) { - // We only check for E_INVALIDARG because we would get - // E_ACCESSDENIED if the DPI was already set previously - // and S_OK means the call was successful - if (SetProcessDpiAwarenessFunc(ProcessSystemDpiAware) == E_INVALIDARG) - { - sf::err() << "Failed to set process DPI awareness" << std::endl; - } - else - { - FreeLibrary(shCoreDll); - return; - } + sf::err() << "Failed to set process DPI awareness" << std::endl; + } + else + { + FreeLibrary(shCoreDll); + return; } - - FreeLibrary(shCoreDll); } - // Fall back to SetProcessDPIAware if SetProcessDpiAwareness - // is not available on this system - HINSTANCE user32Dll = LoadLibrary(L"user32.dll"); + FreeLibrary(shCoreDll); + } - if (user32Dll) + // Fall back to SetProcessDPIAware if SetProcessDpiAwareness + // is not available on this system + HINSTANCE user32Dll = LoadLibrary(L"user32.dll"); + + if (user32Dll) + { + using SetProcessDPIAwareFuncType = BOOL(WINAPI*)(); + auto SetProcessDPIAwareFunc = reinterpret_cast( + reinterpret_cast(GetProcAddress(user32Dll, "SetProcessDPIAware"))); + + if (SetProcessDPIAwareFunc) { - using SetProcessDPIAwareFuncType = BOOL (WINAPI *)(); - auto SetProcessDPIAwareFunc = reinterpret_cast(reinterpret_cast(GetProcAddress(user32Dll, "SetProcessDPIAware"))); - - if (SetProcessDPIAwareFunc) - { - if (!SetProcessDPIAwareFunc()) - sf::err() << "Failed to set process DPI awareness" << std::endl; - } - - FreeLibrary(user32Dll); + if (!SetProcessDPIAwareFunc()) + sf::err() << "Failed to set process DPI awareness" << std::endl; } + + FreeLibrary(user32Dll); } } +} // namespace namespace sf { @@ -125,18 +127,18 @@ namespace priv { //////////////////////////////////////////////////////////// WindowImplWin32::WindowImplWin32(WindowHandle handle) : -m_handle (handle), -m_callback (0), -m_cursorVisible (true), // might need to call GetCursorInfo -m_lastCursor (LoadCursor(nullptr, IDC_ARROW)), -m_icon (nullptr), +m_handle(handle), +m_callback(0), +m_cursorVisible(true), // might need to call GetCursorInfo +m_lastCursor(LoadCursor(nullptr, IDC_ARROW)), +m_icon(nullptr), m_keyRepeatEnabled(true), -m_lastSize (0, 0), -m_resizing (false), -m_surrogate (0), -m_mouseInside (false), -m_fullscreen (false), -m_cursorGrabbed (false) +m_lastSize(0, 0), +m_resizing(false), +m_surrogate(0), +m_mouseInside(false), +m_fullscreen(false), +m_cursorGrabbed(false) { // Set that this process is DPI aware and can handle DPI scaling setProcessDpiAware(); @@ -158,18 +160,18 @@ m_cursorGrabbed (false) //////////////////////////////////////////////////////////// WindowImplWin32::WindowImplWin32(VideoMode mode, const String& title, Uint32 style, const ContextSettings& /*settings*/) : -m_handle (nullptr), -m_callback (0), -m_cursorVisible (true), // might need to call GetCursorInfo -m_lastCursor (LoadCursor(nullptr, IDC_ARROW)), -m_icon (nullptr), +m_handle(nullptr), +m_callback(0), +m_cursorVisible(true), // might need to call GetCursorInfo +m_lastCursor(LoadCursor(nullptr, IDC_ARROW)), +m_icon(nullptr), m_keyRepeatEnabled(true), -m_lastSize (mode.size), -m_resizing (false), -m_surrogate (0), -m_mouseInside (false), -m_fullscreen ((style & Style::Fullscreen) != 0), -m_cursorGrabbed (m_fullscreen) +m_lastSize(mode.size), +m_resizing(false), +m_surrogate(0), +m_mouseInside(false), +m_fullscreen((style & Style::Fullscreen) != 0), +m_cursorGrabbed(m_fullscreen) { // Set that this process is DPI aware and can handle DPI scaling setProcessDpiAware(); @@ -180,10 +182,10 @@ m_cursorGrabbed (m_fullscreen) // Compute position and size HDC screenDC = GetDC(nullptr); - int left = (GetDeviceCaps(screenDC, HORZRES) - static_cast(mode.size.x)) / 2; - int top = (GetDeviceCaps(screenDC, VERTRES) - static_cast(mode.size.y)) / 2; - int width = static_cast(mode.size.x); - int height = static_cast(mode.size.y); + int left = (GetDeviceCaps(screenDC, HORZRES) - static_cast(mode.size.x)) / 2; + int top = (GetDeviceCaps(screenDC, VERTRES) - static_cast(mode.size.y)) / 2; + int width = static_cast(mode.size.x); + int height = static_cast(mode.size.y); ReleaseDC(nullptr, screenDC); // Choose the window style according to the Style parameter @@ -194,9 +196,12 @@ m_cursorGrabbed (m_fullscreen) } else { - if (style & Style::Titlebar) win32Style |= WS_CAPTION | WS_MINIMIZEBOX; - if (style & Style::Resize) win32Style |= WS_THICKFRAME | WS_MAXIMIZEBOX; - if (style & Style::Close) win32Style |= WS_SYSMENU; + if (style & Style::Titlebar) + win32Style |= WS_CAPTION | WS_MINIMIZEBOX; + if (style & Style::Resize) + win32Style |= WS_THICKFRAME | WS_MAXIMIZEBOX; + if (style & Style::Close) + win32Style |= WS_SYSMENU; } // In windowed mode, adjust width and height so that window will have the requested client area @@ -209,10 +214,21 @@ m_cursorGrabbed (m_fullscreen) } // Create the window - m_handle = CreateWindowW(className, title.toWideString().c_str(), win32Style, left, top, width, height, nullptr, nullptr, GetModuleHandle(nullptr), this); + m_handle = CreateWindowW(className, + title.toWideString().c_str(), + win32Style, + left, + top, + width, + height, + nullptr, + nullptr, + GetModuleHandle(nullptr), + this); // Register to receive device interface change notifications (used for joystick connection handling) - DEV_BROADCAST_DEVICEINTERFACE deviceInterface = {sizeof(DEV_BROADCAST_DEVICEINTERFACE), DBT_DEVTYP_DEVICEINTERFACE, 0, GUID_DEVINTERFACE_HID, {0}}; + DEV_BROADCAST_DEVICEINTERFACE deviceInterface = + {sizeof(DEV_BROADCAST_DEVICEINTERFACE), DBT_DEVTYP_DEVICEINTERFACE, 0, GUID_DEVINTERFACE_HID, {0}}; RegisterDeviceNotification(m_handle, &deviceInterface, DEVICE_NOTIFY_WINDOW_HANDLE); // If we're the first window handle, we only need to poll for joysticks when WM_DEVICECHANGE message is received @@ -314,7 +330,7 @@ void WindowImplWin32::setPosition(const Vector2i& position) { SetWindowPos(m_handle, nullptr, position.x, position.y, 0, 0, SWP_NOSIZE | SWP_NOZORDER); - if(m_cursorGrabbed) + if (m_cursorGrabbed) grabCursor(true); } @@ -368,12 +384,18 @@ void WindowImplWin32::setIcon(const Vector2u& size, const Uint8* pixels) } // Create the icon from the pixel array - m_icon = CreateIcon(GetModuleHandleW(nullptr), static_cast(size.x), static_cast(size.y), 1, 32, nullptr, iconPixels.data()); + m_icon = CreateIcon(GetModuleHandleW(nullptr), + static_cast(size.x), + static_cast(size.y), + 1, + 32, + nullptr, + iconPixels.data()); // Set it as both big and small icon of the window if (m_icon) { - SendMessageW(m_handle, WM_SETICON, ICON_BIG, reinterpret_cast(m_icon)); + SendMessageW(m_handle, WM_SETICON, ICON_BIG, reinterpret_cast(m_icon)); SendMessageW(m_handle, WM_SETICON, ICON_SMALL, reinterpret_cast(m_icon)); } else @@ -492,7 +514,10 @@ void WindowImplWin32::switchToFullscreen(const VideoMode& mode) } // Make the window flags compatible with fullscreen mode - SetWindowLongPtr(m_handle, GWL_STYLE, static_cast(WS_POPUP) | static_cast(WS_CLIPCHILDREN) | static_cast(WS_CLIPSIBLINGS)); + SetWindowLongPtr(m_handle, + GWL_STYLE, + static_cast(WS_POPUP) | static_cast(WS_CLIPCHILDREN) | + static_cast(WS_CLIPSIBLINGS)); SetWindowLongPtr(m_handle, GWL_EXSTYLE, WS_EX_APPWINDOW); // Resize the window so that it fits the entire screen @@ -529,9 +554,9 @@ void WindowImplWin32::cleanup() void WindowImplWin32::setTracking(bool track) { TRACKMOUSEEVENT mouseEvent; - mouseEvent.cbSize = sizeof(TRACKMOUSEEVENT); - mouseEvent.dwFlags = track ? TME_LEAVE : TME_CANCEL; - mouseEvent.hwndTrack = m_handle; + mouseEvent.cbSize = sizeof(TRACKMOUSEEVENT); + mouseEvent.dwFlags = track ? TME_LEAVE : TME_CANCEL; + mouseEvent.hwndTrack = m_handle; mouseEvent.dwHoverTime = HOVER_DEFAULT; TrackMouseEvent(&mouseEvent); } @@ -575,7 +600,8 @@ void WindowImplWin32::processEvent(UINT message, WPARAM wParam, LPARAM lParam) case WM_SETCURSOR: { // The mouse has moved, if the cursor is in our window we must refresh the cursor - if (LOWORD(lParam) == HTCLIENT) { + if (LOWORD(lParam) == HTCLIENT) + { SetCursor(m_cursorVisible ? m_lastCursor : nullptr); } @@ -627,7 +653,7 @@ void WindowImplWin32::processEvent(UINT message, WPARAM wParam, LPARAM lParam) m_resizing = false; // Ignore cases where the window has only been moved - if(m_lastSize != getSize()) + if (m_lastSize != getSize()) { // Update the last handled size m_lastSize = getSize(); @@ -650,7 +676,7 @@ void WindowImplWin32::processEvent(UINT message, WPARAM wParam, LPARAM lParam) { // We override the returned information to remove the default limit // (the OS doesn't allow windows bigger than the desktop by default) - auto* info = reinterpret_cast(lParam); + auto* info = reinterpret_cast(lParam); info->ptMaxTrackSize.x = 50000; info->ptMaxTrackSize.y = 50000; break; @@ -707,7 +733,7 @@ void WindowImplWin32::processEvent(UINT message, WPARAM wParam, LPARAM lParam) // Send a TextEntered event Event event; - event.type = Event::TextEntered; + event.type = Event::TextEntered; event.text.unicode = character; pushEvent(event); } @@ -723,9 +749,9 @@ void WindowImplWin32::processEvent(UINT message, WPARAM wParam, LPARAM lParam) { Event event; event.type = Event::KeyPressed; - event.key.alt = HIWORD(GetKeyState(VK_MENU)) != 0; + event.key.alt = HIWORD(GetKeyState(VK_MENU)) != 0; event.key.control = HIWORD(GetKeyState(VK_CONTROL)) != 0; - event.key.shift = HIWORD(GetKeyState(VK_SHIFT)) != 0; + event.key.shift = HIWORD(GetKeyState(VK_SHIFT)) != 0; event.key.system = HIWORD(GetKeyState(VK_LWIN)) || HIWORD(GetKeyState(VK_RWIN)); event.key.code = virtualKeyCodeToSF(wParam, lParam); pushEvent(event); @@ -739,9 +765,9 @@ void WindowImplWin32::processEvent(UINT message, WPARAM wParam, LPARAM lParam) { Event event; event.type = Event::KeyReleased; - event.key.alt = HIWORD(GetKeyState(VK_MENU)) != 0; + event.key.alt = HIWORD(GetKeyState(VK_MENU)) != 0; event.key.control = HIWORD(GetKeyState(VK_CONTROL)) != 0; - event.key.shift = HIWORD(GetKeyState(VK_SHIFT)) != 0; + event.key.shift = HIWORD(GetKeyState(VK_SHIFT)) != 0; event.key.system = HIWORD(GetKeyState(VK_LWIN)) || HIWORD(GetKeyState(VK_RWIN)); event.key.code = virtualKeyCodeToSF(wParam, lParam); pushEvent(event); @@ -1151,4 +1177,3 @@ LRESULT CALLBACK WindowImplWin32::globalOnEvent(HWND handle, UINT message, WPARA } // namespace priv } // namespace sf - diff --git a/src/SFML/Window/Win32/WindowImplWin32.hpp b/src/SFML/Window/Win32/WindowImplWin32.hpp old mode 100755 new mode 100644 index 6216cc35a..a2ab53c0c --- a/src/SFML/Window/Win32/WindowImplWin32.hpp +++ b/src/SFML/Window/Win32/WindowImplWin32.hpp @@ -28,9 +28,9 @@ //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// +#include #include #include -#include namespace sf @@ -46,7 +46,6 @@ namespace priv class WindowImplWin32 : public WindowImpl { public: - //////////////////////////////////////////////////////////// /// \brief Construct the window implementation from an existing control /// @@ -185,7 +184,6 @@ public: bool hasFocus() const override; protected: - //////////////////////////////////////////////////////////// /// \brief Process incoming events from the operating system /// @@ -193,7 +191,6 @@ protected: void processEvents() override; private: - //////////////////////////////////////////////////////////// /// Register the window class /// @@ -272,18 +269,18 @@ private: //////////////////////////////////////////////////////////// // Member data //////////////////////////////////////////////////////////// - HWND m_handle; //!< Win32 handle of the window - LONG_PTR m_callback; //!< Stores the original event callback function of the control - bool m_cursorVisible; //!< Is the cursor visible or hidden? - HCURSOR m_lastCursor; //!< Last cursor used -- this data is not owned by the window and is required to be always valid - HICON m_icon; //!< Custom icon assigned to the window - bool m_keyRepeatEnabled; //!< Automatic key-repeat state for keydown events - Vector2u m_lastSize; //!< The last handled size of the window - bool m_resizing; //!< Is the window being resized? - Uint16 m_surrogate; //!< First half of the surrogate pair, in case we're receiving a Unicode character in two events - bool m_mouseInside; //!< Mouse is inside the window? - bool m_fullscreen; //!< Is the window fullscreen? - bool m_cursorGrabbed; //!< Is the mouse cursor trapped? + HWND m_handle; //!< Win32 handle of the window + LONG_PTR m_callback; //!< Stores the original event callback function of the control + bool m_cursorVisible; //!< Is the cursor visible or hidden? + HCURSOR m_lastCursor; //!< Last cursor used -- this data is not owned by the window and is required to be always valid + HICON m_icon; //!< Custom icon assigned to the window + bool m_keyRepeatEnabled; //!< Automatic key-repeat state for keydown events + Vector2u m_lastSize; //!< The last handled size of the window + bool m_resizing; //!< Is the window being resized? + Uint16 m_surrogate; //!< First half of the surrogate pair, in case we're receiving a Unicode character in two events + bool m_mouseInside; //!< Mouse is inside the window? + bool m_fullscreen; //!< Is the window fullscreen? + bool m_cursorGrabbed; //!< Is the mouse cursor trapped? }; } // namespace priv diff --git a/src/SFML/Window/Window.cpp b/src/SFML/Window/Window.cpp index 468398fa0..a565e39eb 100644 --- a/src/SFML/Window/Window.cpp +++ b/src/SFML/Window/Window.cpp @@ -25,28 +25,26 @@ //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// -#include -#include -#include -#include #include +#include +#include +#include +#include + #include namespace sf { //////////////////////////////////////////////////////////// -Window::Window() : -m_context (), -m_frameTimeLimit(Time::Zero) +Window::Window() : m_context(), m_frameTimeLimit(Time::Zero) { - } //////////////////////////////////////////////////////////// Window::Window(VideoMode mode, const String& title, Uint32 style, const ContextSettings& settings) : -m_context (), +m_context(), m_frameTimeLimit(Time::Zero) { Window::create(mode, title, style, settings); @@ -54,9 +52,7 @@ m_frameTimeLimit(Time::Zero) //////////////////////////////////////////////////////////// -Window::Window(WindowHandle handle, const ContextSettings& settings) : -m_context (), -m_frameTimeLimit(Time::Zero) +Window::Window(WindowHandle handle, const ContextSettings& settings) : m_context(), m_frameTimeLimit(Time::Zero) { Window::create(handle, settings); } @@ -105,16 +101,16 @@ void Window::create(VideoMode mode, const String& title, Uint32 style, const Con } } - // Check validity of style according to the underlying platform - #if defined(SFML_SYSTEM_IOS) || defined(SFML_SYSTEM_ANDROID) - if (style & Style::Fullscreen) - style &= ~static_cast(Style::Titlebar); - else - style |= Style::Titlebar; - #else - if ((style & Style::Close) || (style & Style::Resize)) - style |= Style::Titlebar; - #endif +// Check validity of style according to the underlying platform +#if defined(SFML_SYSTEM_IOS) || defined(SFML_SYSTEM_ANDROID) + if (style & Style::Fullscreen) + style &= ~static_cast(Style::Titlebar); + else + style |= Style::Titlebar; +#else + if ((style & Style::Close) || (style & Style::Resize)) + style |= Style::Titlebar; +#endif // Recreate the window implementation m_impl = priv::WindowImpl::create(mode, title, style, settings); diff --git a/src/SFML/Window/WindowBase.cpp b/src/SFML/Window/WindowBase.cpp index ac9b42f63..14757ae0c 100644 --- a/src/SFML/Window/WindowBase.cpp +++ b/src/SFML/Window/WindowBase.cpp @@ -25,47 +25,41 @@ //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// -#include -#include -#include #include +#include +#include +#include + #include namespace { - // A nested named namespace is used here to allow unity builds of SFML. - namespace WindowsBaseImpl - { - const sf::WindowBase* fullscreenWindow = nullptr; - } +// A nested named namespace is used here to allow unity builds of SFML. +namespace WindowsBaseImpl +{ +const sf::WindowBase* fullscreenWindow = nullptr; } +} // namespace namespace sf { //////////////////////////////////////////////////////////// -WindowBase::WindowBase() : -m_impl(), -m_size(0, 0) +WindowBase::WindowBase() : m_impl(), m_size(0, 0) { - } //////////////////////////////////////////////////////////// -WindowBase::WindowBase(VideoMode mode, const String& title, Uint32 style) : -m_impl(), -m_size(0, 0) +WindowBase::WindowBase(VideoMode mode, const String& title, Uint32 style) : m_impl(), m_size(0, 0) { WindowBase::create(mode, title, style); } //////////////////////////////////////////////////////////// -WindowBase::WindowBase(WindowHandle handle) : -m_impl(), -m_size(0, 0) +WindowBase::WindowBase(WindowHandle handle) : m_impl(), m_size(0, 0) { WindowBase::create(handle); } @@ -107,16 +101,16 @@ void WindowBase::create(VideoMode mode, const String& title, Uint32 style) } } - // Check validity of style according to the underlying platform - #if defined(SFML_SYSTEM_IOS) || defined(SFML_SYSTEM_ANDROID) - if (style & Style::Fullscreen) - style &= ~static_cast(Style::Titlebar); - else - style |= Style::Titlebar; - #else - if ((style & Style::Close) || (style & Style::Resize)) - style |= Style::Titlebar; - #endif +// Check validity of style according to the underlying platform +#if defined(SFML_SYSTEM_IOS) || defined(SFML_SYSTEM_ANDROID) + if (style & Style::Fullscreen) + style &= ~static_cast(Style::Titlebar); + else + style |= Style::Titlebar; +#else + if ((style & Style::Close) || (style & Style::Resize)) + style |= Style::Titlebar; +#endif // Recreate the window implementation m_impl = priv::WindowImpl::create(mode, title, style, ContextSettings(0, 0, 0, 0, 0, 0xFFFFFFFF, false)); diff --git a/src/SFML/Window/WindowImpl.cpp b/src/SFML/Window/WindowImpl.cpp index cc2293e8a..a2987019e 100644 --- a/src/SFML/Window/WindowImpl.cpp +++ b/src/SFML/Window/WindowImpl.cpp @@ -25,64 +25,66 @@ //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// -#include +#include +#include #include #include #include #include -#include -#include +#include + #include -#include #include +#include #if defined(SFML_SYSTEM_WINDOWS) - #include - using WindowImplType = sf::priv::WindowImplWin32; +#include +using WindowImplType = sf::priv::WindowImplWin32; - #include - using VulkanImplType = sf::priv::VulkanImplWin32; +#include +using VulkanImplType = sf::priv::VulkanImplWin32; -#elif defined(SFML_SYSTEM_LINUX) || defined(SFML_SYSTEM_FREEBSD) || defined(SFML_SYSTEM_OPENBSD) || defined(SFML_SYSTEM_NETBSD) +#elif defined(SFML_SYSTEM_LINUX) || defined(SFML_SYSTEM_FREEBSD) || defined(SFML_SYSTEM_OPENBSD) || \ + defined(SFML_SYSTEM_NETBSD) - #if defined(SFML_USE_DRM) +#if defined(SFML_USE_DRM) - #include - using WindowImplType = sf::priv::WindowImplDRM; +#include +using WindowImplType = sf::priv::WindowImplDRM; - #define SFML_VULKAN_IMPLEMENTATION_NOT_AVAILABLE +#define SFML_VULKAN_IMPLEMENTATION_NOT_AVAILABLE - #else +#else - #include - using WindowImplType = sf::priv::WindowImplX11; +#include +using WindowImplType = sf::priv::WindowImplX11; - #include - using VulkanImplType = sf::priv::VulkanImplX11; +#include +using VulkanImplType = sf::priv::VulkanImplX11; - #endif +#endif #elif defined(SFML_SYSTEM_MACOS) - #include - using WindowImplType = sf::priv::WindowImplCocoa; +#include +using WindowImplType = sf::priv::WindowImplCocoa; - #define SFML_VULKAN_IMPLEMENTATION_NOT_AVAILABLE +#define SFML_VULKAN_IMPLEMENTATION_NOT_AVAILABLE #elif defined(SFML_SYSTEM_IOS) - #include - using WindowImplType = sf::priv::WindowImplUIKit; +#include +using WindowImplType = sf::priv::WindowImplUIKit; - #define SFML_VULKAN_IMPLEMENTATION_NOT_AVAILABLE +#define SFML_VULKAN_IMPLEMENTATION_NOT_AVAILABLE #elif defined(SFML_SYSTEM_ANDROID) - #include - using WindowImplType = sf::priv::WindowImplAndroid; +#include +using WindowImplType = sf::priv::WindowImplAndroid; - #define SFML_VULKAN_IMPLEMENTATION_NOT_AVAILABLE +#define SFML_VULKAN_IMPLEMENTATION_NOT_AVAILABLE #endif @@ -113,9 +115,7 @@ std::unique_ptr WindowImpl::create(WindowHandle handle) //////////////////////////////////////////////////////////// -WindowImpl::WindowImpl() : -m_joystickStatesImpl(std::make_unique()), -m_joystickThreshold(0.1f) +WindowImpl::WindowImpl() : m_joystickStatesImpl(std::make_unique()), m_joystickThreshold(0.1f) { // Get the initial joystick states JoystickManager::getInstance().update(); @@ -198,7 +198,7 @@ void WindowImpl::processJoystickEvents() for (unsigned int i = 0; i < Joystick::Count; ++i) { // Copy the previous state of the joystick and get the new one - JoystickState previousState = m_joystickStatesImpl->m_states[i]; + JoystickState previousState = m_joystickStatesImpl->m_states[i]; m_joystickStatesImpl->m_states[i] = JoystickManager::getInstance().getState(i); // Connection state @@ -206,7 +206,7 @@ void WindowImpl::processJoystickEvents() if (previousState.connected ^ connected) { Event event; - event.type = connected ? Event::JoystickConnected : Event::JoystickDisconnected; + event.type = connected ? Event::JoystickConnected : Event::JoystickDisconnected; event.joystickButton.joystickId = i; pushEvent(event); @@ -224,16 +224,16 @@ void WindowImpl::processJoystickEvents() { if (caps.axes[j]) { - auto axis = static_cast(j); + auto axis = static_cast(j); float prevPos = m_previousAxes[i][axis]; float currPos = m_joystickStatesImpl->m_states[i].axes[axis]; if (std::abs(currPos - prevPos) >= m_joystickThreshold) { Event event; - event.type = Event::JoystickMoved; + event.type = Event::JoystickMoved; event.joystickMove.joystickId = i; - event.joystickMove.axis = axis; - event.joystickMove.position = currPos; + event.joystickMove.axis = axis; + event.joystickMove.position = currPos; pushEvent(event); m_previousAxes[i][axis] = currPos; @@ -252,7 +252,7 @@ void WindowImpl::processJoystickEvents() Event event; event.type = currPressed ? Event::JoystickButtonPressed : Event::JoystickButtonReleased; event.joystickButton.joystickId = i; - event.joystickButton.button = j; + event.joystickButton.button = j; pushEvent(event); } } @@ -276,17 +276,17 @@ void WindowImpl::processSensorEvents() { // Copy the previous value of the sensor and get the new one Vector3f previousValue = m_sensorValue[i]; - m_sensorValue[i] = SensorManager::getInstance().getValue(sensor); + m_sensorValue[i] = SensorManager::getInstance().getValue(sensor); // If the value has changed, trigger an event if (m_sensorValue[i] != previousValue) // @todo use a threshold? { Event event; - event.type = Event::SensorChanged; + event.type = Event::SensorChanged; event.sensor.type = sensor; - event.sensor.x = m_sensorValue[i].x; - event.sensor.y = m_sensorValue[i].y; - event.sensor.z = m_sensorValue[i].z; + event.sensor.x = m_sensorValue[i].x; + event.sensor.y = m_sensorValue[i].y; + event.sensor.z = m_sensorValue[i].z; pushEvent(event); } } @@ -295,7 +295,9 @@ void WindowImpl::processSensorEvents() //////////////////////////////////////////////////////////// -bool WindowImpl::createVulkanSurface([[maybe_unused]] const VkInstance& instance, [[maybe_unused]] VkSurfaceKHR& surface, [[maybe_unused]] const VkAllocationCallbacks* allocator) +bool WindowImpl::createVulkanSurface([[maybe_unused]] const VkInstance& instance, + [[maybe_unused]] VkSurfaceKHR& surface, + [[maybe_unused]] const VkAllocationCallbacks* allocator) { #if defined(SFML_VULKAN_IMPLEMENTATION_NOT_AVAILABLE) diff --git a/src/SFML/Window/WindowImpl.hpp b/src/SFML/Window/WindowImpl.hpp index 91a42ce94..19bd258cb 100644 --- a/src/SFML/Window/WindowImpl.hpp +++ b/src/SFML/Window/WindowImpl.hpp @@ -29,6 +29,7 @@ // Headers //////////////////////////////////////////////////////////// #include + #include #include #include @@ -38,6 +39,7 @@ #include #include #include + #include #include #include @@ -56,7 +58,6 @@ namespace priv class WindowImpl { public: - //////////////////////////////////////////////////////////// /// \brief Create a new window depending on the current OS /// @@ -81,7 +82,6 @@ public: static std::unique_ptr create(WindowHandle handle); public: - //////////////////////////////////////////////////////////// /// \brief Destructor /// @@ -250,7 +250,6 @@ public: bool createVulkanSurface(const VkInstance& instance, VkSurfaceKHR& surface, const VkAllocationCallbacks* allocator); protected: - //////////////////////////////////////////////////////////// /// \brief Default constructor /// @@ -293,11 +292,11 @@ private: //////////////////////////////////////////////////////////// // Member data //////////////////////////////////////////////////////////// - std::queue m_events; //!< Queue of available events - std::unique_ptr m_joystickStatesImpl; //!< Previous state of the joysticks (PImpl) - Vector3f m_sensorValue[Sensor::Count]; //!< Previous value of the sensors - float m_joystickThreshold; //!< Joystick threshold (minimum motion for "move" event to be generated) - float m_previousAxes[Joystick::Count][Joystick::AxisCount]; //!< Position of each axis last time a move event triggered, in range [-100, 100] + std::queue m_events; //!< Queue of available events + std::unique_ptr m_joystickStatesImpl; //!< Previous state of the joysticks (PImpl) + Vector3f m_sensorValue[Sensor::Count]; //!< Previous value of the sensors + float m_joystickThreshold; //!< Joystick threshold (minimum motion for "move" event to be generated) + float m_previousAxes[Joystick::Count][Joystick::AxisCount]; //!< Position of each axis last time a move event triggered, in range [-100, 100] }; } // namespace priv diff --git a/src/SFML/Window/iOS/ClipboardImpl.hpp b/src/SFML/Window/iOS/ClipboardImpl.hpp index 4f1e07007..270877828 100644 --- a/src/SFML/Window/iOS/ClipboardImpl.hpp +++ b/src/SFML/Window/iOS/ClipboardImpl.hpp @@ -40,7 +40,6 @@ namespace priv class ClipboardImpl { public: - //////////////////////////////////////////////////////////// /// \brief Get the content of the clipboard as string data /// @@ -72,4 +71,3 @@ public: #endif // SFML_CLIPBOARDIMPLIOS_HPP - diff --git a/src/SFML/Window/iOS/ClipboardImpl.mm b/src/SFML/Window/iOS/ClipboardImpl.mm index 376b81cf3..980687ab4 100644 --- a/src/SFML/Window/iOS/ClipboardImpl.mm +++ b/src/SFML/Window/iOS/ClipboardImpl.mm @@ -25,8 +25,8 @@ //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// -#include #include +#include #import @@ -43,8 +43,8 @@ String ClipboardImpl::getString() { NSString* data = pboard.string; - char const* utf8 = [data cStringUsingEncoding:NSUTF8StringEncoding]; - NSUInteger length = [data lengthOfBytesUsingEncoding:NSUTF8StringEncoding]; + char const* utf8 = [data cStringUsingEncoding:NSUTF8StringEncoding]; + NSUInteger length = [data lengthOfBytesUsingEncoding:NSUTF8StringEncoding]; return String::fromUtf8(utf8, utf8 + length); } @@ -59,15 +59,12 @@ String ClipboardImpl::getString() void ClipboardImpl::setString(const String& text) { std::basic_string utf8 = text.toUtf8(); - NSString* data = [[NSString alloc] initWithBytes:utf8.data() - length:utf8.length() - encoding:NSUTF8StringEncoding]; + NSString* data = [[NSString alloc] initWithBytes:utf8.data() length:utf8.length() encoding:NSUTF8StringEncoding]; UIPasteboard* pboard = [UIPasteboard generalPasteboard]; - pboard.string = data; + pboard.string = data; } } // namespace priv } // namespace sf - diff --git a/src/SFML/Window/iOS/CursorImpl.cpp b/src/SFML/Window/iOS/CursorImpl.cpp index a93bfed8f..c6fec99bf 100644 --- a/src/SFML/Window/iOS/CursorImpl.cpp +++ b/src/SFML/Window/iOS/CursorImpl.cpp @@ -58,4 +58,3 @@ bool CursorImpl::loadFromSystem(Cursor::Type /* type */) } // namespace priv } // namespace sf - diff --git a/src/SFML/Window/iOS/CursorImpl.hpp b/src/SFML/Window/iOS/CursorImpl.hpp index db4849afc..1d4f59805 100644 --- a/src/SFML/Window/iOS/CursorImpl.hpp +++ b/src/SFML/Window/iOS/CursorImpl.hpp @@ -28,8 +28,8 @@ //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// -#include #include +#include namespace sf @@ -46,7 +46,6 @@ namespace priv class CursorImpl { public: - //////////////////////////////////////////////////////////// /// \brief Default constructor /// diff --git a/src/SFML/Window/iOS/EaglContext.hpp b/src/SFML/Window/iOS/EaglContext.hpp index 4860a705f..df1664d4d 100644 --- a/src/SFML/Window/iOS/EaglContext.hpp +++ b/src/SFML/Window/iOS/EaglContext.hpp @@ -28,10 +28,11 @@ //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// +#include +#include #include #include -#include -#include + #include @@ -51,7 +52,6 @@ class WindowImplUIKit; class EaglContext : public GlContext { public: - //////////////////////////////////////////////////////////// /// \brief Create a new context, not associated to a window /// @@ -69,8 +69,7 @@ public: /// \param bitsPerPixel Pixel depth, in bits per pixel /// //////////////////////////////////////////////////////////// - EaglContext(EaglContext* shared, const ContextSettings& settings, - const WindowImpl& owner, unsigned int bitsPerPixel); + EaglContext(EaglContext* shared, const ContextSettings& settings, const WindowImpl& owner, unsigned int bitsPerPixel); //////////////////////////////////////////////////////////// /// \brief Create a new context that embeds its own rendering target @@ -80,8 +79,7 @@ public: /// \param size Back buffer width and height, in pixels /// //////////////////////////////////////////////////////////// - EaglContext(EaglContext* shared, const ContextSettings& settings, - const Vector2u& size); + EaglContext(EaglContext* shared, const ContextSettings& settings, const Vector2u& size); //////////////////////////////////////////////////////////// /// \brief Destructor @@ -130,7 +128,6 @@ public: void setVerticalSyncEnabled(bool enabled) override; protected: - //////////////////////////////////////////////////////////// /// \brief Activate the context as the current target /// for rendering @@ -143,7 +140,6 @@ protected: bool makeCurrent(bool current) override; private: - //////////////////////////////////////////////////////////// /// \brief Create the context /// @@ -153,20 +149,20 @@ private: /// \param settings Creation parameters /// //////////////////////////////////////////////////////////// - void createContext(EaglContext* shared, + void createContext(EaglContext* shared, const WindowImplUIKit& window, - unsigned int bitsPerPixel, + unsigned int bitsPerPixel, const ContextSettings& settings); //////////////////////////////////////////////////////////// // Member data //////////////////////////////////////////////////////////// - EAGLContext* m_context; ///< The internal context - GLuint m_framebuffer; ///< Frame buffer associated to the context - GLuint m_colorbuffer; ///< Color render buffer - GLuint m_depthbuffer; ///< Depth render buffer - bool m_vsyncEnabled; ///< Vertical sync activation flag - Clock m_clock; ///< Measures the elapsed time for the fake v-sync implementation + EAGLContext* m_context; ///< The internal context + GLuint m_framebuffer; ///< Frame buffer associated to the context + GLuint m_colorbuffer; ///< Color render buffer + GLuint m_depthbuffer; ///< Depth render buffer + bool m_vsyncEnabled; ///< Vertical sync activation flag + Clock m_clock; ///< Measures the elapsed time for the fake v-sync implementation }; } // namespace priv diff --git a/src/SFML/Window/iOS/EaglContext.mm b/src/SFML/Window/iOS/EaglContext.mm index 622f7a9a5..20aa9956a 100644 --- a/src/SFML/Window/iOS/EaglContext.mm +++ b/src/SFML/Window/iOS/EaglContext.mm @@ -25,12 +25,13 @@ //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// -#include -#include -#include #include #include #include +#include +#include +#include + #include #include #include @@ -39,48 +40,58 @@ #if defined(__APPLE__) - #if defined(__clang__) - #pragma clang diagnostic ignored "-Wdeprecated-declarations" - #elif defined(__GNUC__) - #pragma GCC diagnostic ignored "-Wdeprecated-declarations" - #endif +#if defined(__clang__) +#pragma clang diagnostic ignored "-Wdeprecated-declarations" +#elif defined(__GNUC__) +#pragma GCC diagnostic ignored "-Wdeprecated-declarations" +#endif #endif namespace { - PFNGLBINDFRAMEBUFFEROESPROC glBindFramebufferOESFunc = 0; - PFNGLBINDRENDERBUFFEROESPROC glBindRenderbufferOESFunc = 0; - PFNGLCHECKFRAMEBUFFERSTATUSOESPROC glCheckFramebufferStatusOESFunc = 0; - PFNGLDELETEFRAMEBUFFERSOESPROC glDeleteFramebuffersOESFunc = 0; - PFNGLDELETERENDERBUFFERSOESPROC glDeleteRenderbuffersOESFunc = 0; - PFNGLFRAMEBUFFERRENDERBUFFEROESPROC glFramebufferRenderbufferOESFunc = 0; - PFNGLGENFRAMEBUFFERSOESPROC glGenFramebuffersOESFunc = 0; - PFNGLGENRENDERBUFFERSOESPROC glGenRenderbuffersOESFunc = 0; - PFNGLGETRENDERBUFFERPARAMETERIVOESPROC glGetRenderbufferParameterivOESFunc = 0; - PFNGLRENDERBUFFERSTORAGEOESPROC glRenderbufferStorageOESFunc = 0; +PFNGLBINDFRAMEBUFFEROESPROC glBindFramebufferOESFunc = 0; +PFNGLBINDRENDERBUFFEROESPROC glBindRenderbufferOESFunc = 0; +PFNGLCHECKFRAMEBUFFERSTATUSOESPROC glCheckFramebufferStatusOESFunc = 0; +PFNGLDELETEFRAMEBUFFERSOESPROC glDeleteFramebuffersOESFunc = 0; +PFNGLDELETERENDERBUFFERSOESPROC glDeleteRenderbuffersOESFunc = 0; +PFNGLFRAMEBUFFERRENDERBUFFEROESPROC glFramebufferRenderbufferOESFunc = 0; +PFNGLGENFRAMEBUFFERSOESPROC glGenFramebuffersOESFunc = 0; +PFNGLGENRENDERBUFFERSOESPROC glGenRenderbuffersOESFunc = 0; +PFNGLGETRENDERBUFFERPARAMETERIVOESPROC glGetRenderbufferParameterivOESFunc = 0; +PFNGLRENDERBUFFERSTORAGEOESPROC glRenderbufferStorageOESFunc = 0; - void ensureInit() +void ensureInit() +{ + static bool initialized = false; + if (!initialized) { - static bool initialized = false; - if (!initialized) - { - initialized = true; + initialized = true; - glBindFramebufferOESFunc = reinterpret_cast (sf::priv::EaglContext::getFunction("glBindFramebufferOES")); - glBindRenderbufferOESFunc = reinterpret_cast (sf::priv::EaglContext::getFunction("glBindRenderbufferOES")); - glCheckFramebufferStatusOESFunc = reinterpret_cast (sf::priv::EaglContext::getFunction("glCheckFramebufferStatusOES")); - glDeleteFramebuffersOESFunc = reinterpret_cast (sf::priv::EaglContext::getFunction("glDeleteFramebuffersOES")); - glDeleteRenderbuffersOESFunc = reinterpret_cast (sf::priv::EaglContext::getFunction("glDeleteRenderbuffersOES")); - glFramebufferRenderbufferOESFunc = reinterpret_cast (sf::priv::EaglContext::getFunction("glFramebufferRenderbufferOES")); - glGenFramebuffersOESFunc = reinterpret_cast (sf::priv::EaglContext::getFunction("glGenFramebuffersOES")); - glGenRenderbuffersOESFunc = reinterpret_cast (sf::priv::EaglContext::getFunction("glGenRenderbuffersOES")); - glGetRenderbufferParameterivOESFunc = reinterpret_cast(sf::priv::EaglContext::getFunction("glGetRenderbufferParameterivOES")); - glRenderbufferStorageOESFunc = reinterpret_cast (sf::priv::EaglContext::getFunction("glRenderbufferStorageOES")); - } + glBindFramebufferOESFunc = reinterpret_cast( + sf::priv::EaglContext::getFunction("glBindFramebufferOES")); + glBindRenderbufferOESFunc = reinterpret_cast( + sf::priv::EaglContext::getFunction("glBindRenderbufferOES")); + glCheckFramebufferStatusOESFunc = reinterpret_cast( + sf::priv::EaglContext::getFunction("glCheckFramebufferStatusOES")); + glDeleteFramebuffersOESFunc = reinterpret_cast( + sf::priv::EaglContext::getFunction("glDeleteFramebuffersOES")); + glDeleteRenderbuffersOESFunc = reinterpret_cast( + sf::priv::EaglContext::getFunction("glDeleteRenderbuffersOES")); + glFramebufferRenderbufferOESFunc = reinterpret_cast( + sf::priv::EaglContext::getFunction("glFramebufferRenderbufferOES")); + glGenFramebuffersOESFunc = reinterpret_cast( + sf::priv::EaglContext::getFunction("glGenFramebuffersOES")); + glGenRenderbuffersOESFunc = reinterpret_cast( + sf::priv::EaglContext::getFunction("glGenRenderbuffersOES")); + glGetRenderbufferParameterivOESFunc = reinterpret_cast( + sf::priv::EaglContext::getFunction("glGetRenderbufferParameterivOES")); + glRenderbufferStorageOESFunc = reinterpret_cast( + sf::priv::EaglContext::getFunction("glRenderbufferStorageOES")); } } +} namespace sf @@ -89,32 +100,32 @@ namespace priv { //////////////////////////////////////////////////////////// EaglContext::EaglContext(EaglContext* shared) : -m_context (nil), -m_framebuffer (0), -m_colorbuffer (0), -m_depthbuffer (0), +m_context(nil), +m_framebuffer(0), +m_colorbuffer(0), +m_depthbuffer(0), m_vsyncEnabled(false), -m_clock () +m_clock() { ensureInit(); // Create the context if (shared) - m_context = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES1 sharegroup:[shared->m_context sharegroup]]; + m_context = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES1 + sharegroup:[shared->m_context sharegroup]]; else m_context = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES1]; } //////////////////////////////////////////////////////////// -EaglContext::EaglContext(EaglContext* shared, const ContextSettings& settings, - const WindowImpl& owner, unsigned int bitsPerPixel) : -m_context (nil), -m_framebuffer (0), -m_colorbuffer (0), -m_depthbuffer (0), +EaglContext::EaglContext(EaglContext* shared, const ContextSettings& settings, const WindowImpl& owner, unsigned int bitsPerPixel) : +m_context(nil), +m_framebuffer(0), +m_colorbuffer(0), +m_depthbuffer(0), m_vsyncEnabled(false), -m_clock () +m_clock() { ensureInit(); @@ -125,14 +136,13 @@ m_clock () //////////////////////////////////////////////////////////// -EaglContext::EaglContext(EaglContext* /* shared */, const ContextSettings& /* settings */, - const Vector2u& /* size */) : -m_context (nil), -m_framebuffer (0), -m_colorbuffer (0), -m_depthbuffer (0), +EaglContext::EaglContext(EaglContext* /* shared */, const ContextSettings& /* settings */, const Vector2u& /* size */) : +m_context(nil), +m_framebuffer(0), +m_colorbuffer(0), +m_depthbuffer(0), m_vsyncEnabled(false), -m_clock () +m_clock() { ensureInit(); @@ -175,13 +185,10 @@ GlFunctionPointer EaglContext::getFunction(const char* name) { static void* module = 0; - const int libCount = 3; - const char* libs[libCount] = - { - "libGLESv1_CM.dylib", - "/System/Library/Frameworks/OpenGLES.framework/OpenGLES", - "OpenGLES.framework/OpenGLES" - }; + const int libCount = 3; + const char* libs[libCount] = {"libGLESv1_CM.dylib", + "/System/Library/Frameworks/OpenGLES.framework/OpenGLES", + "OpenGLES.framework/OpenGLES"}; for (int i = 0; i < libCount; ++i) { @@ -190,8 +197,7 @@ GlFunctionPointer EaglContext::getFunction(const char* name) } if (module) - return reinterpret_cast( - reinterpret_cast(dlsym(module, name))); + return reinterpret_cast(reinterpret_cast(dlsym(module, name))); return 0; } @@ -225,8 +231,8 @@ void EaglContext::recreateRenderBuffers(SFView* glView) { // Find the best internal format GLenum format = m_settings.depthBits > 16 - ? (m_settings.stencilBits == 0 ? GL_DEPTH_COMPONENT24_OES : GL_DEPTH24_STENCIL8_OES) - : GL_DEPTH_COMPONENT16_OES; + ? (m_settings.stencilBits == 0 ? GL_DEPTH_COMPONENT24_OES : GL_DEPTH24_STENCIL8_OES) + : GL_DEPTH_COMPONENT16_OES; // Get the size of the color-buffer (which fits the current size of the GL view) GLint width, height; @@ -288,7 +294,7 @@ void EaglContext::setVerticalSyncEnabled(bool enabled) //////////////////////////////////////////////////////////// -void EaglContext::createContext(EaglContext* shared, +void EaglContext::createContext(EaglContext* shared, const WindowImplUIKit& window, unsigned int /* bitsPerPixel */, const ContextSettings& settings) @@ -307,7 +313,8 @@ void EaglContext::createContext(EaglContext* shared, { [EAGLContext setCurrentContext:nil]; - m_context = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES1 sharegroup:[shared->m_context sharegroup]]; + m_context = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES1 + sharegroup:[shared->m_context sharegroup]]; } else { @@ -333,4 +340,3 @@ void EaglContext::createContext(EaglContext* shared, } // namespace priv } // namespace sf - diff --git a/src/SFML/Window/iOS/InputImpl.hpp b/src/SFML/Window/iOS/InputImpl.hpp index c9c82f665..a28a101e9 100644 --- a/src/SFML/Window/iOS/InputImpl.hpp +++ b/src/SFML/Window/iOS/InputImpl.hpp @@ -43,7 +43,6 @@ namespace priv class InputImpl { public: - //////////////////////////////////////////////////////////// /// \brief Check if a key is pressed /// diff --git a/src/SFML/Window/iOS/InputImpl.mm b/src/SFML/Window/iOS/InputImpl.mm index f07d03d2a..732f4b248 100644 --- a/src/SFML/Window/iOS/InputImpl.mm +++ b/src/SFML/Window/iOS/InputImpl.mm @@ -25,11 +25,11 @@ //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// -#include -#include +#include #include #include -#include +#include +#include namespace sf diff --git a/src/SFML/Window/iOS/JoystickImpl.hpp b/src/SFML/Window/iOS/JoystickImpl.hpp index f78734555..39146d042 100644 --- a/src/SFML/Window/iOS/JoystickImpl.hpp +++ b/src/SFML/Window/iOS/JoystickImpl.hpp @@ -42,7 +42,6 @@ namespace priv class JoystickImpl { public: - //////////////////////////////////////////////////////////// /// \brief Perform the global initialization of the joystick module /// diff --git a/src/SFML/Window/iOS/ObjCType.hpp b/src/SFML/Window/iOS/ObjCType.hpp index 6c406331a..78fdf285a 100644 --- a/src/SFML/Window/iOS/ObjCType.hpp +++ b/src/SFML/Window/iOS/ObjCType.hpp @@ -28,9 +28,9 @@ // Forward declare an Objective-C class #ifdef __OBJC__ - #define SFML_DECLARE_OBJC_CLASS(c) @class c +#define SFML_DECLARE_OBJC_CLASS(c) @class c #else - #define SFML_DECLARE_OBJC_CLASS(c) typedef struct objc_object c +#define SFML_DECLARE_OBJC_CLASS(c) typedef struct objc_object c #endif diff --git a/src/SFML/Window/iOS/SFAppDelegate.hpp b/src/SFML/Window/iOS/SFAppDelegate.hpp index 7eccdfa96..eb845195f 100644 --- a/src/SFML/Window/iOS/SFAppDelegate.hpp +++ b/src/SFML/Window/iOS/SFAppDelegate.hpp @@ -29,8 +29,9 @@ // Headers //////////////////////////////////////////////////////////// #include -#include + #include +#include //////////////////////////////////////////////////////////// @@ -39,13 +40,13 @@ /// This class handles global application events. /// //////////////////////////////////////////////////////////// -@interface SFAppDelegate : NSObject +@interface SFAppDelegate : NSObject //////////////////////////////////////////////////////////// /// \brief Return the instance of the application delegate /// //////////////////////////////////////////////////////////// -+(SFAppDelegate*)getInstance; ++ (SFAppDelegate*)getInstance; //////////////////////////////////////////////////////////// /// \brief Show or hide the virtual keyboard @@ -125,11 +126,10 @@ //////////////////////////////////////////////////////////// // Member data //////////////////////////////////////////////////////////// -@property (nonatomic) sf::priv::WindowImplUIKit* sfWindow; ///< Main window of the application -@property (readonly, nonatomic) CMMotionManager* motionManager; ///< Instance of the motion manager -@property (nonatomic) CGFloat backingScaleFactor; +@property(nonatomic) sf::priv::WindowImplUIKit* sfWindow; ///< Main window of the application +@property(readonly, nonatomic) CMMotionManager* motionManager; ///< Instance of the motion manager +@property(nonatomic) CGFloat backingScaleFactor; @end #endif // SFML_SFAPPDELEGATE_HPP - diff --git a/src/SFML/Window/iOS/SFAppDelegate.mm b/src/SFML/Window/iOS/SFAppDelegate.mm index ba009058e..6b725f886 100644 --- a/src/SFML/Window/iOS/SFAppDelegate.mm +++ b/src/SFML/Window/iOS/SFAppDelegate.mm @@ -27,20 +27,21 @@ //////////////////////////////////////////////////////////// #include #include + #include namespace { - // Save the global instance of the delegate - SFAppDelegate* delegateInstance = nullptr; +// Save the global instance of the delegate +SFAppDelegate* delegateInstance = nullptr; - // Current touches positions - std::vector touchPositions; +// Current touches positions +std::vector touchPositions; } -@interface SFAppDelegate() +@interface SFAppDelegate () @property (nonatomic) CMMotionManager* motionManager; @@ -58,7 +59,7 @@ namespace { NSAssert(delegateInstance, @"SFAppDelegate instance is nil, this means SFML was not properly initialized. " - "Make sure that the file defining your main() function includes "); + "Make sure that the file defining your main() function includes "); return delegateInstance; } @@ -73,7 +74,7 @@ namespace //////////////////////////////////////////////////////////// -- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions +- (BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions { // Save the delegate instance delegateInstance = self; @@ -85,10 +86,14 @@ namespace // Register orientation changes notifications [[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications]; - [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(deviceOrientationDidChange:) name:UIDeviceOrientationDidChangeNotification object: nil]; + [[NSNotificationCenter defaultCenter] + addObserver:self + selector:@selector(deviceOrientationDidChange:) + name:UIDeviceOrientationDidChangeNotification + object:nil]; // Change the working directory to the resources directory - [[NSFileManager defaultManager] changeCurrentDirectoryPath: [[NSBundle mainBundle] resourcePath]]; + [[NSFileManager defaultManager] changeCurrentDirectoryPath:[[NSBundle mainBundle] resourcePath]]; // Schedule an indirect call to the user main, so that this call (and the whole // init sequence) can end, and the default splashscreen can be destroyed @@ -100,14 +105,14 @@ namespace - (void)initBackingScale { id data = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"NSHighResolutionCapable"]; - if(data && [data boolValue]) + if (data && [data boolValue]) backingScaleFactor = [[UIScreen mainScreen] scale]; else backingScaleFactor = 1; } //////////////////////////////////////////////////////////// -- (void)applicationWillResignActive:(UIApplication *)application +- (void)applicationWillResignActive:(UIApplication*)application { // Called when: // - the application is sent to background @@ -124,14 +129,14 @@ namespace //////////////////////////////////////////////////////////// -- (void)applicationDidEnterBackground:(UIApplication *)application +- (void)applicationDidEnterBackground:(UIApplication*)application { // Called when the application is sent to background (home button pressed) } //////////////////////////////////////////////////////////// -- (void)applicationDidBecomeActive:(UIApplication *)application +- (void)applicationDidBecomeActive:(UIApplication*)application { // Called when: // - the application is sent to foreground @@ -148,14 +153,14 @@ namespace //////////////////////////////////////////////////////////// -- (void)applicationWillEnterForeground:(UIApplication *)application +- (void)applicationWillEnterForeground:(UIApplication*)application { // Called when the application is sent to foreground (app icon pressed) } //////////////////////////////////////////////////////////// -- (void)applicationWillTerminate:(UIApplication *)application +- (void)applicationWillTerminate:(UIApplication*)application { // Generate a Closed event if (self.sfWindow) @@ -172,29 +177,30 @@ namespace return false; #if defined(__APPLE__) - #if defined(__clang__) - #pragma clang diagnostic push - #pragma clang diagnostic ignored "-Wold-style-cast" - #elif defined(__GNUC__) - #pragma GCC diagnostic push - #pragma GCC diagnostic ignored "-Wold-style-cast" - #endif +#if defined(__clang__) +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wold-style-cast" +#elif defined(__GNUC__) +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wold-style-cast" +#endif #endif UIViewController* rootViewController = [((__bridge UIWindow*)(self.sfWindow->getSystemHandle())) rootViewController]; #if defined(__APPLE__) - #if defined(__clang__) - #pragma clang diagnostic pop - #elif defined(__GNUC__) - #pragma GCC diagnostic pop - #endif +#if defined(__clang__) +#pragma clang diagnostic pop +#elif defined(__GNUC__) +#pragma GCC diagnostic pop +#endif #endif if (!rootViewController || ![rootViewController shouldAutorotate]) return false; - NSArray *supportedOrientations = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"UISupportedInterfaceOrientations"]; + NSArray* supportedOrientations = [[NSBundle mainBundle] + objectForInfoDictionaryKey:@"UISupportedInterfaceOrientations"]; if (!supportedOrientations) return (1 << orientation) & [rootViewController supportedInterfaceOrientations]; @@ -214,12 +220,12 @@ namespace - (bool)needsToFlipFrameForOrientation:(UIDeviceOrientation)orientation { sf::Vector2u size = self.sfWindow->getSize(); - return ((!UIDeviceOrientationIsLandscape(orientation) && size.x > size.y) - || (UIDeviceOrientationIsLandscape(orientation) && size.y > size.x)); + return ((!UIDeviceOrientationIsLandscape(orientation) && size.x > size.y) || + (UIDeviceOrientationIsLandscape(orientation) && size.y > size.x)); } //////////////////////////////////////////////////////////// -- (void)deviceOrientationDidChange:(NSNotification *)notification +- (void)deviceOrientationDidChange:(NSNotification*)notification { if (self.sfWindow) { @@ -236,8 +242,8 @@ namespace // Send a Resized event to the current window sf::Event event; - event.type = sf::Event::Resized; - event.size.width = size.x; + event.type = sf::Event::Resized; + event.size.width = size.x; event.size.height = size.y; sfWindow->forwardEvent(event); } @@ -277,10 +283,10 @@ namespace if (self.sfWindow) { sf::Event event; - event.type = sf::Event::TouchBegan; + event.type = sf::Event::TouchBegan; event.touch.finger = index; - event.touch.x = position.x; - event.touch.y = position.y; + event.touch.x = position.x; + event.touch.y = position.y; sfWindow->forwardEvent(event); } } @@ -301,10 +307,10 @@ namespace if (self.sfWindow) { sf::Event event; - event.type = sf::Event::TouchMoved; + event.type = sf::Event::TouchMoved; event.touch.finger = index; - event.touch.x = position.x; - event.touch.y = position.y; + event.touch.x = position.x; + event.touch.y = position.y; sfWindow->forwardEvent(event); } } @@ -321,10 +327,10 @@ namespace if (self.sfWindow) { sf::Event event; - event.type = sf::Event::TouchEnded; + event.type = sf::Event::TouchEnded; event.touch.finger = index; - event.touch.x = position.x * static_cast(backingScaleFactor); - event.touch.y = position.y * static_cast(backingScaleFactor); + event.touch.x = position.x * static_cast(backingScaleFactor); + event.touch.y = position.y * static_cast(backingScaleFactor); sfWindow->forwardEvent(event); } } @@ -336,7 +342,7 @@ namespace if (self.sfWindow) { sf::Event event; - event.type = sf::Event::TextEntered; + event.type = sf::Event::TextEntered; event.text.unicode = character; sfWindow->forwardEvent(event); } diff --git a/src/SFML/Window/iOS/SFMain.hpp b/src/SFML/Window/iOS/SFMain.hpp index b6a38b8aa..a133bd288 100644 --- a/src/SFML/Window/iOS/SFMain.hpp +++ b/src/SFML/Window/iOS/SFMain.hpp @@ -32,4 +32,3 @@ int sfmlMain(); #endif // SFML_SFMAIN_HPP - diff --git a/src/SFML/Window/iOS/SFView.hpp b/src/SFML/Window/iOS/SFView.hpp index 5ef2d1369..b4585c8b9 100644 --- a/src/SFML/Window/iOS/SFView.hpp +++ b/src/SFML/Window/iOS/SFView.hpp @@ -29,6 +29,7 @@ // Headers //////////////////////////////////////////////////////////// #include + #include @@ -37,7 +38,7 @@ /// (supports OpenGL and reports events) /// //////////////////////////////////////////////////////////// -@interface SFView : UIView +@interface SFView : UIView //////////////////////////////////////////////////////////// /// \brief Construct the view with its initial size @@ -52,7 +53,7 @@ //////////////////////////////////////////////////////////// // Member data //////////////////////////////////////////////////////////// -@property (nonatomic) sf::priv::EaglContext* context; ///< The attached EAGL context +@property(nonatomic) sf::priv::EaglContext* context; ///< The attached EAGL context @end diff --git a/src/SFML/Window/iOS/SFView.mm b/src/SFML/Window/iOS/SFView.mm index c4ddf15a6..8e951bed6 100644 --- a/src/SFML/Window/iOS/SFView.mm +++ b/src/SFML/Window/iOS/SFView.mm @@ -25,21 +25,22 @@ //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// -#include -#include #include +#include +#include + #include #include #if defined(__APPLE__) - #if defined(__clang__) - #pragma clang diagnostic ignored "-Wdeprecated-declarations" - #elif defined(__GNUC__) - #pragma GCC diagnostic ignored "-Wdeprecated-declarations" - #endif +#if defined(__clang__) +#pragma clang diagnostic ignored "-Wdeprecated-declarations" +#elif defined(__GNUC__) +#pragma GCC diagnostic ignored "-Wdeprecated-declarations" +#endif #endif -@interface SFView() +@interface SFView () @property (nonatomic) NSMutableArray* touches; @@ -52,7 +53,7 @@ //////////////////////////////////////////////////////////// --(BOOL)canBecomeFirstResponder +- (BOOL)canBecomeFirstResponder { return true; } @@ -107,7 +108,7 @@ } // get the touch position - CGPoint point = [touch locationInView:self]; + CGPoint point = [touch locationInView:self]; sf::Vector2i position(static_cast(point.x), static_cast(point.y)); // notify the application delegate @@ -126,7 +127,7 @@ if (index != NSNotFound) { // get the touch position - CGPoint point = [touch locationInView:self]; + CGPoint point = [touch locationInView:self]; sf::Vector2i position(static_cast(point.x), static_cast(point.y)); // notify the application delegate @@ -146,7 +147,7 @@ if (index != NSNotFound) { // get the touch position - CGPoint point = [touch locationInView:self]; + CGPoint point = [touch locationInView:self]; sf::Vector2i position(static_cast(point.x), static_cast(point.y)); // notify the application delegate @@ -195,23 +196,25 @@ self.touches = [NSMutableArray array]; // Configure the EAGL layer - CAEAGLLayer* eaglLayer = static_cast(self.layer); - eaglLayer.opaque = YES; - eaglLayer.drawableProperties = [NSDictionary dictionaryWithObjectsAndKeys: - [NSNumber numberWithBool:FALSE], kEAGLDrawablePropertyRetainedBacking, - kEAGLColorFormatRGBA8, kEAGLDrawablePropertyColorFormat, - nil]; + CAEAGLLayer* eaglLayer = static_cast(self.layer); + eaglLayer.opaque = YES; + eaglLayer.drawableProperties = [NSDictionary + dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:FALSE], + kEAGLDrawablePropertyRetainedBacking, + kEAGLColorFormatRGBA8, + kEAGLDrawablePropertyColorFormat, + nil]; // Enable user interactions on the view (multi-touch events) self.userInteractionEnabled = true; - self.multipleTouchEnabled = true; + self.multipleTouchEnabled = true; } return self; } //////////////////////////////////////////////////////////// -- (UITextAutocorrectionType) autocorrectionType +- (UITextAutocorrectionType)autocorrectionType { return UITextAutocorrectionTypeNo; } diff --git a/src/SFML/Window/iOS/SFViewController.hpp b/src/SFML/Window/iOS/SFViewController.hpp index 4e2ddada0..26f10c1a8 100644 --- a/src/SFML/Window/iOS/SFViewController.hpp +++ b/src/SFML/Window/iOS/SFViewController.hpp @@ -58,7 +58,7 @@ //////////////////////////////////////////////////////////// // Member data //////////////////////////////////////////////////////////// -@property (nonatomic) bool orientationCanChange; ///< Tells whether the controller's view can rotate or not +@property(nonatomic) bool orientationCanChange; ///< Tells whether the controller's view can rotate or not @end diff --git a/src/SFML/Window/iOS/SensorImpl.hpp b/src/SFML/Window/iOS/SensorImpl.hpp index e9f7dcf44..939189055 100644 --- a/src/SFML/Window/iOS/SensorImpl.hpp +++ b/src/SFML/Window/iOS/SensorImpl.hpp @@ -42,7 +42,6 @@ namespace priv class SensorImpl { public: - //////////////////////////////////////////////////////////// /// \brief Perform the global initialization of the sensor module /// @@ -98,12 +97,11 @@ public: void setEnabled(bool enabled); private: - //////////////////////////////////////////////////////////// // Member data //////////////////////////////////////////////////////////// - Sensor::Type m_sensor; ///< Type of the sensor - bool m_enabled; ///< Enable state of the sensor + Sensor::Type m_sensor; ///< Type of the sensor + bool m_enabled; ///< Enable state of the sensor }; } // namespace priv diff --git a/src/SFML/Window/iOS/SensorImpl.mm b/src/SFML/Window/iOS/SensorImpl.mm index d08095c87..3a4e3a6e5 100644 --- a/src/SFML/Window/iOS/SensorImpl.mm +++ b/src/SFML/Window/iOS/SensorImpl.mm @@ -32,12 +32,12 @@ namespace { - unsigned int deviceMotionEnabledCount = 0; +unsigned int deviceMotionEnabledCount = 0; - float toDegrees(float radians) - { - return sf::radians(radians).asDegrees(); - } +float toDegrees(float radians) +{ + return sf::radians(radians).asDegrees(); +} } @@ -133,7 +133,7 @@ void SensorImpl::close() //////////////////////////////////////////////////////////// Vector3f SensorImpl::update() { - Vector3f value; + Vector3f value; CMMotionManager* manager = [SFAppDelegate getInstance].motionManager; switch (m_sensor) diff --git a/src/SFML/Window/iOS/VideoModeImpl.mm b/src/SFML/Window/iOS/VideoModeImpl.mm index 095af56f0..51286d254 100644 --- a/src/SFML/Window/iOS/VideoModeImpl.mm +++ b/src/SFML/Window/iOS/VideoModeImpl.mm @@ -27,6 +27,7 @@ //////////////////////////////////////////////////////////// #include #include + #include namespace sf @@ -49,9 +50,10 @@ std::vector VideoModeImpl::getFullscreenModes() //////////////////////////////////////////////////////////// VideoMode VideoModeImpl::getDesktopMode() { - CGRect bounds = [[UIScreen mainScreen] bounds]; + CGRect bounds = [[UIScreen mainScreen] bounds]; double backingScale = [SFAppDelegate getInstance].backingScaleFactor; - return VideoMode({static_cast(bounds.size.width * backingScale), static_cast(bounds.size.height * backingScale)}); + return VideoMode({static_cast(bounds.size.width * backingScale), + static_cast(bounds.size.height * backingScale)}); } } // namespace priv diff --git a/src/SFML/Window/iOS/WindowImplUIKit.hpp b/src/SFML/Window/iOS/WindowImplUIKit.hpp index c1db522c5..ad41dd212 100644 --- a/src/SFML/Window/iOS/WindowImplUIKit.hpp +++ b/src/SFML/Window/iOS/WindowImplUIKit.hpp @@ -49,7 +49,6 @@ namespace priv class WindowImplUIKit : public WindowImpl { public: - //////////////////////////////////////////////////////////// /// \brief Construct the window implementation from an existing control /// @@ -188,7 +187,6 @@ public: bool hasFocus() const override; public: - //////////////////////////////////////////////////////////// /// \brief Notify an event /// @@ -214,7 +212,6 @@ public: void setVirtualKeyboardVisible(bool visible); protected: - //////////////////////////////////////////////////////////// /// \brief Process incoming events from the operating system /// @@ -222,7 +219,6 @@ protected: void processEvents() override; private: - //////////////////////////////////////////////////////////// // Member data //////////////////////////////////////////////////////////// diff --git a/src/SFML/Window/iOS/WindowImplUIKit.mm b/src/SFML/Window/iOS/WindowImplUIKit.mm index ae474f1c4..cc64e9369 100644 --- a/src/SFML/Window/iOS/WindowImplUIKit.mm +++ b/src/SFML/Window/iOS/WindowImplUIKit.mm @@ -25,20 +25,21 @@ //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// -#include +#include +#include +#include #include #include -#include -#include -#include +#include + #include #if defined(__APPLE__) - #if defined(__clang__) - #pragma clang diagnostic ignored "-Wdeprecated-declarations" - #elif defined(__GNUC__) - #pragma GCC diagnostic ignored "-Wdeprecated-declarations" - #endif +#if defined(__clang__) +#pragma clang diagnostic ignored "-Wdeprecated-declarations" +#elif defined(__GNUC__) +#pragma GCC diagnostic ignored "-Wdeprecated-declarations" +#endif #endif namespace sf @@ -53,10 +54,7 @@ WindowImplUIKit::WindowImplUIKit(WindowHandle /* handle */) //////////////////////////////////////////////////////////// -WindowImplUIKit::WindowImplUIKit(VideoMode mode, - const String& /* title */, - unsigned long style, - const ContextSettings& /* settings */) +WindowImplUIKit::WindowImplUIKit(VideoMode mode, const String& /* title */, unsigned long style, const ContextSettings& /* settings */) { m_backingScale = static_cast([SFAppDelegate getInstance].backingScaleFactor); @@ -71,8 +69,8 @@ WindowImplUIKit::WindowImplUIKit(VideoMode mode, // Create the window CGRect frame = [UIScreen mainScreen].bounds; // Ignore user size, it wouldn't make sense to use something else - m_window = [[UIWindow alloc] initWithFrame:frame]; - m_hasFocus = true; + m_window = [[UIWindow alloc] initWithFrame:frame]; + m_hasFocus = true; // Assign it to the application delegate [SFAppDelegate getInstance].sfWindow = this; @@ -84,10 +82,10 @@ WindowImplUIKit::WindowImplUIKit(VideoMode mode, [m_view resignFirstResponder]; // Create the view controller - m_viewController = [SFViewController alloc]; - m_viewController.view = m_view; + m_viewController = [SFViewController alloc]; + m_viewController.view = m_view; m_viewController.orientationCanChange = style & Style::Resize; - m_window.rootViewController = m_viewController; + m_window.rootViewController = m_viewController; // Make it the current window [m_window makeKeyAndVisible]; @@ -112,23 +110,23 @@ void WindowImplUIKit::processEvents() WindowHandle WindowImplUIKit::getSystemHandle() const { #if defined(__APPLE__) - #if defined(__clang__) - #pragma clang diagnostic push - #pragma clang diagnostic ignored "-Wold-style-cast" - #elif defined(__GNUC__) - #pragma GCC diagnostic push - #pragma GCC diagnostic ignored "-Wold-style-cast" - #endif +#if defined(__clang__) +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wold-style-cast" +#elif defined(__GNUC__) +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wold-style-cast" +#endif #endif return (__bridge WindowHandle)m_window; #if defined(__APPLE__) - #if defined(__clang__) - #pragma clang diagnostic pop - #elif defined(__GNUC__) - #pragma GCC diagnostic pop - #endif +#if defined(__clang__) +#pragma clang diagnostic pop +#elif defined(__GNUC__) +#pragma GCC diagnostic pop +#endif #endif } @@ -137,7 +135,8 @@ WindowHandle WindowImplUIKit::getSystemHandle() const Vector2i WindowImplUIKit::getPosition() const { CGPoint origin = m_window.frame.origin; - return Vector2i(static_cast(origin.x * static_cast(m_backingScale)), static_cast(origin.y * static_cast(m_backingScale))); + return Vector2i(static_cast(origin.x * static_cast(m_backingScale)), + static_cast(origin.y * static_cast(m_backingScale))); } @@ -151,7 +150,8 @@ void WindowImplUIKit::setPosition(const Vector2i& /* position */) Vector2u WindowImplUIKit::getSize() const { CGRect physicalFrame = m_window.frame; - return Vector2u(static_cast(physicalFrame.size.width * static_cast(m_backingScale)), static_cast(physicalFrame.size.height * static_cast(m_backingScale))); + return Vector2u(static_cast(physicalFrame.size.width * static_cast(m_backingScale)), + static_cast(physicalFrame.size.height * static_cast(m_backingScale))); } diff --git a/test/Graphics/BlendMode.cpp b/test/Graphics/BlendMode.cpp index c63befd31..97f760dfa 100644 --- a/test/Graphics/BlendMode.cpp +++ b/test/Graphics/BlendMode.cpp @@ -1,8 +1,9 @@ #include -#include #include +#include + TEST_CASE("sf::BlendMode class - [graphics]") { SUBCASE("Construction") @@ -12,10 +13,10 @@ TEST_CASE("sf::BlendMode class - [graphics]") const sf::BlendMode blendMode; CHECK(blendMode.colorSrcFactor == sf::BlendMode::SrcAlpha); CHECK(blendMode.colorDstFactor == sf::BlendMode::OneMinusSrcAlpha); - CHECK(blendMode.colorEquation == sf::BlendMode::Add); + CHECK(blendMode.colorEquation == sf::BlendMode::Add); CHECK(blendMode.alphaSrcFactor == sf::BlendMode::One); CHECK(blendMode.alphaDstFactor == sf::BlendMode::OneMinusSrcAlpha); - CHECK(blendMode.alphaEquation == sf::BlendMode::Add); + CHECK(blendMode.alphaEquation == sf::BlendMode::Add); } SUBCASE("Combined color and alpha constructor using default parameter") @@ -23,10 +24,10 @@ TEST_CASE("sf::BlendMode class - [graphics]") const sf::BlendMode blendMode(sf::BlendMode::Zero, sf::BlendMode::SrcColor); CHECK(blendMode.colorSrcFactor == sf::BlendMode::Zero); CHECK(blendMode.colorDstFactor == sf::BlendMode::SrcColor); - CHECK(blendMode.colorEquation == sf::BlendMode::Add); + CHECK(blendMode.colorEquation == sf::BlendMode::Add); CHECK(blendMode.alphaSrcFactor == sf::BlendMode::Zero); CHECK(blendMode.alphaDstFactor == sf::BlendMode::SrcColor); - CHECK(blendMode.alphaEquation == sf::BlendMode::Add); + CHECK(blendMode.alphaEquation == sf::BlendMode::Add); } SUBCASE("Combined color and alpha constructor") @@ -34,22 +35,26 @@ TEST_CASE("sf::BlendMode class - [graphics]") const sf::BlendMode blendMode(sf::BlendMode::Zero, sf::BlendMode::SrcColor, sf::BlendMode::ReverseSubtract); CHECK(blendMode.colorSrcFactor == sf::BlendMode::Zero); CHECK(blendMode.colorDstFactor == sf::BlendMode::SrcColor); - CHECK(blendMode.colorEquation == sf::BlendMode::ReverseSubtract); + CHECK(blendMode.colorEquation == sf::BlendMode::ReverseSubtract); CHECK(blendMode.alphaSrcFactor == sf::BlendMode::Zero); CHECK(blendMode.alphaDstFactor == sf::BlendMode::SrcColor); - CHECK(blendMode.alphaEquation == sf::BlendMode::ReverseSubtract); + CHECK(blendMode.alphaEquation == sf::BlendMode::ReverseSubtract); } SUBCASE("Separate color and alpha constructor") { - const sf::BlendMode blendMode(sf::BlendMode::Zero, sf::BlendMode::SrcColor, sf::BlendMode::ReverseSubtract, - sf::BlendMode::OneMinusDstAlpha, sf::BlendMode::DstAlpha, sf::BlendMode::Max); + const sf::BlendMode blendMode(sf::BlendMode::Zero, + sf::BlendMode::SrcColor, + sf::BlendMode::ReverseSubtract, + sf::BlendMode::OneMinusDstAlpha, + sf::BlendMode::DstAlpha, + sf::BlendMode::Max); CHECK(blendMode.colorSrcFactor == sf::BlendMode::Zero); CHECK(blendMode.colorDstFactor == sf::BlendMode::SrcColor); - CHECK(blendMode.colorEquation == sf::BlendMode::ReverseSubtract); + CHECK(blendMode.colorEquation == sf::BlendMode::ReverseSubtract); CHECK(blendMode.alphaSrcFactor == sf::BlendMode::OneMinusDstAlpha); CHECK(blendMode.alphaDstFactor == sf::BlendMode::DstAlpha); - CHECK(blendMode.alphaEquation == sf::BlendMode::Max); + CHECK(blendMode.alphaEquation == sf::BlendMode::Max); } } @@ -58,35 +63,73 @@ TEST_CASE("sf::BlendMode class - [graphics]") SUBCASE("operator==") { CHECK(sf::BlendMode() == sf::BlendMode()); - CHECK(sf::BlendMode(sf::BlendMode::Zero, sf::BlendMode::One) == sf::BlendMode(sf::BlendMode::Zero, sf::BlendMode::One)); - CHECK(sf::BlendMode(sf::BlendMode::Zero, sf::BlendMode::SrcColor, sf::BlendMode::ReverseSubtract, - sf::BlendMode::OneMinusDstAlpha, sf::BlendMode::DstAlpha, sf::BlendMode::Max) - == sf::BlendMode(sf::BlendMode::Zero, sf::BlendMode::SrcColor, sf::BlendMode::ReverseSubtract, - sf::BlendMode::OneMinusDstAlpha, sf::BlendMode::DstAlpha, sf::BlendMode::Max)); + CHECK(sf::BlendMode(sf::BlendMode::Zero, sf::BlendMode::One) == + sf::BlendMode(sf::BlendMode::Zero, sf::BlendMode::One)); + CHECK(sf::BlendMode(sf::BlendMode::Zero, + sf::BlendMode::SrcColor, + sf::BlendMode::ReverseSubtract, + sf::BlendMode::OneMinusDstAlpha, + sf::BlendMode::DstAlpha, + sf::BlendMode::Max) == + sf::BlendMode(sf::BlendMode::Zero, + sf::BlendMode::SrcColor, + sf::BlendMode::ReverseSubtract, + sf::BlendMode::OneMinusDstAlpha, + sf::BlendMode::DstAlpha, + sf::BlendMode::Max)); CHECK_FALSE(sf::BlendMode() == sf::BlendMode(sf::BlendMode::Zero, sf::BlendMode::One)); - CHECK_FALSE(sf::BlendMode(sf::BlendMode::Zero, sf::BlendMode::One) == sf::BlendMode(sf::BlendMode::One, sf::BlendMode::Zero)); - CHECK_FALSE(sf::BlendMode(sf::BlendMode::Zero, sf::BlendMode::SrcColor, sf::BlendMode::ReverseSubtract, - sf::BlendMode::OneMinusDstAlpha, sf::BlendMode::DstAlpha, sf::BlendMode::Max) - == sf::BlendMode(sf::BlendMode::One, sf::BlendMode::SrcColor, sf::BlendMode::ReverseSubtract, - sf::BlendMode::OneMinusDstAlpha, sf::BlendMode::DstAlpha, sf::BlendMode::Max)); + CHECK_FALSE(sf::BlendMode(sf::BlendMode::Zero, sf::BlendMode::One) == + sf::BlendMode(sf::BlendMode::One, sf::BlendMode::Zero)); + CHECK_FALSE( + sf::BlendMode(sf::BlendMode::Zero, + sf::BlendMode::SrcColor, + sf::BlendMode::ReverseSubtract, + sf::BlendMode::OneMinusDstAlpha, + sf::BlendMode::DstAlpha, + sf::BlendMode::Max) == + sf::BlendMode(sf::BlendMode::One, + sf::BlendMode::SrcColor, + sf::BlendMode::ReverseSubtract, + sf::BlendMode::OneMinusDstAlpha, + sf::BlendMode::DstAlpha, + sf::BlendMode::Max)); } SUBCASE("operator!=") { CHECK_FALSE(sf::BlendMode() != sf::BlendMode()); - CHECK_FALSE(sf::BlendMode(sf::BlendMode::Zero, sf::BlendMode::One) != sf::BlendMode(sf::BlendMode::Zero, sf::BlendMode::One)); - CHECK_FALSE(sf::BlendMode(sf::BlendMode::Zero, sf::BlendMode::SrcColor, sf::BlendMode::ReverseSubtract, - sf::BlendMode::OneMinusDstAlpha, sf::BlendMode::DstAlpha, sf::BlendMode::Max) - != sf::BlendMode(sf::BlendMode::Zero, sf::BlendMode::SrcColor, sf::BlendMode::ReverseSubtract, - sf::BlendMode::OneMinusDstAlpha, sf::BlendMode::DstAlpha, sf::BlendMode::Max)); + CHECK_FALSE(sf::BlendMode(sf::BlendMode::Zero, sf::BlendMode::One) != + sf::BlendMode(sf::BlendMode::Zero, sf::BlendMode::One)); + CHECK_FALSE( + sf::BlendMode(sf::BlendMode::Zero, + sf::BlendMode::SrcColor, + sf::BlendMode::ReverseSubtract, + sf::BlendMode::OneMinusDstAlpha, + sf::BlendMode::DstAlpha, + sf::BlendMode::Max) != + sf::BlendMode(sf::BlendMode::Zero, + sf::BlendMode::SrcColor, + sf::BlendMode::ReverseSubtract, + sf::BlendMode::OneMinusDstAlpha, + sf::BlendMode::DstAlpha, + sf::BlendMode::Max)); CHECK(sf::BlendMode() != sf::BlendMode(sf::BlendMode::Zero, sf::BlendMode::One)); - CHECK(sf::BlendMode(sf::BlendMode::Zero, sf::BlendMode::One) != sf::BlendMode(sf::BlendMode::One, sf::BlendMode::Zero)); - CHECK(sf::BlendMode(sf::BlendMode::Zero, sf::BlendMode::SrcColor, sf::BlendMode::ReverseSubtract, - sf::BlendMode::OneMinusDstAlpha, sf::BlendMode::DstAlpha, sf::BlendMode::Max) - != sf::BlendMode(sf::BlendMode::One, sf::BlendMode::SrcColor, sf::BlendMode::ReverseSubtract, - sf::BlendMode::OneMinusDstAlpha, sf::BlendMode::DstAlpha, sf::BlendMode::Max)); + CHECK(sf::BlendMode(sf::BlendMode::Zero, sf::BlendMode::One) != + sf::BlendMode(sf::BlendMode::One, sf::BlendMode::Zero)); + CHECK(sf::BlendMode(sf::BlendMode::Zero, + sf::BlendMode::SrcColor, + sf::BlendMode::ReverseSubtract, + sf::BlendMode::OneMinusDstAlpha, + sf::BlendMode::DstAlpha, + sf::BlendMode::Max) != + sf::BlendMode(sf::BlendMode::One, + sf::BlendMode::SrcColor, + sf::BlendMode::ReverseSubtract, + sf::BlendMode::OneMinusDstAlpha, + sf::BlendMode::DstAlpha, + sf::BlendMode::Max)); } } @@ -94,44 +137,44 @@ TEST_CASE("sf::BlendMode class - [graphics]") { CHECK(sf::BlendAlpha.colorSrcFactor == sf::BlendMode::SrcAlpha); CHECK(sf::BlendAlpha.colorDstFactor == sf::BlendMode::OneMinusSrcAlpha); - CHECK(sf::BlendAlpha.colorEquation == sf::BlendMode::Add); + CHECK(sf::BlendAlpha.colorEquation == sf::BlendMode::Add); CHECK(sf::BlendAlpha.alphaSrcFactor == sf::BlendMode::One); CHECK(sf::BlendAlpha.alphaDstFactor == sf::BlendMode::OneMinusSrcAlpha); - CHECK(sf::BlendAlpha.alphaEquation == sf::BlendMode::Add); + CHECK(sf::BlendAlpha.alphaEquation == sf::BlendMode::Add); CHECK(sf::BlendAdd.colorSrcFactor == sf::BlendMode::SrcAlpha); CHECK(sf::BlendAdd.colorDstFactor == sf::BlendMode::One); - CHECK(sf::BlendAdd.colorEquation == sf::BlendMode::Add); + CHECK(sf::BlendAdd.colorEquation == sf::BlendMode::Add); CHECK(sf::BlendAdd.alphaSrcFactor == sf::BlendMode::One); CHECK(sf::BlendAdd.alphaDstFactor == sf::BlendMode::One); - CHECK(sf::BlendAdd.alphaEquation == sf::BlendMode::Add); + CHECK(sf::BlendAdd.alphaEquation == sf::BlendMode::Add); CHECK(sf::BlendMultiply.colorSrcFactor == sf::BlendMode::DstColor); CHECK(sf::BlendMultiply.colorDstFactor == sf::BlendMode::Zero); - CHECK(sf::BlendMultiply.colorEquation == sf::BlendMode::Add); + CHECK(sf::BlendMultiply.colorEquation == sf::BlendMode::Add); CHECK(sf::BlendMultiply.alphaSrcFactor == sf::BlendMode::DstColor); CHECK(sf::BlendMultiply.alphaDstFactor == sf::BlendMode::Zero); - CHECK(sf::BlendMultiply.alphaEquation == sf::BlendMode::Add); + CHECK(sf::BlendMultiply.alphaEquation == sf::BlendMode::Add); CHECK(sf::BlendMin.colorSrcFactor == sf::BlendMode::One); CHECK(sf::BlendMin.colorDstFactor == sf::BlendMode::One); - CHECK(sf::BlendMin.colorEquation == sf::BlendMode::Min); + CHECK(sf::BlendMin.colorEquation == sf::BlendMode::Min); CHECK(sf::BlendMin.alphaSrcFactor == sf::BlendMode::One); CHECK(sf::BlendMin.alphaDstFactor == sf::BlendMode::One); - CHECK(sf::BlendMin.alphaEquation == sf::BlendMode::Min); + CHECK(sf::BlendMin.alphaEquation == sf::BlendMode::Min); CHECK(sf::BlendMax.colorSrcFactor == sf::BlendMode::One); CHECK(sf::BlendMax.colorDstFactor == sf::BlendMode::One); - CHECK(sf::BlendMax.colorEquation == sf::BlendMode::Max); + CHECK(sf::BlendMax.colorEquation == sf::BlendMode::Max); CHECK(sf::BlendMax.alphaSrcFactor == sf::BlendMode::One); CHECK(sf::BlendMax.alphaDstFactor == sf::BlendMode::One); - CHECK(sf::BlendMax.alphaEquation == sf::BlendMode::Max); + CHECK(sf::BlendMax.alphaEquation == sf::BlendMode::Max); CHECK(sf::BlendNone.colorSrcFactor == sf::BlendMode::One); CHECK(sf::BlendNone.colorDstFactor == sf::BlendMode::Zero); - CHECK(sf::BlendNone.colorEquation == sf::BlendMode::Add); + CHECK(sf::BlendNone.colorEquation == sf::BlendMode::Add); CHECK(sf::BlendNone.alphaSrcFactor == sf::BlendMode::One); CHECK(sf::BlendNone.alphaDstFactor == sf::BlendMode::Zero); - CHECK(sf::BlendNone.alphaEquation == sf::BlendMode::Add); + CHECK(sf::BlendNone.alphaEquation == sf::BlendMode::Add); } } diff --git a/test/Graphics/CircleShape.cpp b/test/Graphics/CircleShape.cpp index 253b80c8b..ba1c677a0 100644 --- a/test/Graphics/CircleShape.cpp +++ b/test/Graphics/CircleShape.cpp @@ -1,8 +1,9 @@ #include -#include #include +#include + TEST_CASE("sf::CircleShape class - [graphics]") { SUBCASE("Default constructor") diff --git a/test/Graphics/Color.cpp b/test/Graphics/Color.cpp index fb60573e9..b7bffceb0 100644 --- a/test/Graphics/Color.cpp +++ b/test/Graphics/Color.cpp @@ -1,8 +1,9 @@ #include -#include #include +#include + TEST_CASE("sf::Color class - [graphics]") { SUBCASE("Construction") diff --git a/test/Graphics/ConvexShape.cpp b/test/Graphics/ConvexShape.cpp index 5273fe7c7..6086b2491 100644 --- a/test/Graphics/ConvexShape.cpp +++ b/test/Graphics/ConvexShape.cpp @@ -1,8 +1,9 @@ #include -#include #include +#include + TEST_CASE("sf::ConvexShape class - [graphics]") { SUBCASE("Default constructor") diff --git a/test/Graphics/Glyph.cpp b/test/Graphics/Glyph.cpp index 52e767454..183cd2166 100644 --- a/test/Graphics/Glyph.cpp +++ b/test/Graphics/Glyph.cpp @@ -1,8 +1,9 @@ #include -#include #include +#include + TEST_CASE("sf::Glyph class - [graphics]") { SUBCASE("Construction") diff --git a/test/Graphics/Image.cpp b/test/Graphics/Image.cpp index 033908eb8..92e0abc9a 100644 --- a/test/Graphics/Image.cpp +++ b/test/Graphics/Image.cpp @@ -1,9 +1,10 @@ #include -#include -#include #include +#include +#include + TEST_CASE("sf::Image - [graphics]") { SUBCASE("Default constructor") @@ -54,7 +55,7 @@ TEST_CASE("sf::Image - [graphics]") std::array pixels; for (std::size_t i = 0; i < pixels.size(); i += 4) { - pixels[i] = 255; // r + pixels[i] = 255; // r pixels[i + 1] = 0; // g pixels[i + 2] = 0; // b pixels[i + 3] = 255; // a @@ -135,9 +136,12 @@ TEST_CASE("sf::Image - [graphics]") // Create the composited colour for via the alpha composite over operation const auto a = static_cast(source.a + (dest.a * (255 - source.a)) / 255); - const auto r = static_cast(((source.r * source.a) + (((dest.r * dest.a) * (255 - source.a))) / 255) / a); - const auto g = static_cast(((source.g * source.a) + (((dest.g * dest.a) * (255 - source.a))) / 255) / a); - const auto b = static_cast(((source.b * source.a) + (((dest.b * dest.a) * (255 - source.a))) / 255) / a); + const auto r = static_cast( + ((source.r * source.a) + (((dest.r * dest.a) * (255 - source.a))) / 255) / a); + const auto g = static_cast( + ((source.g * source.a) + (((dest.g * dest.a) * (255 - source.a))) / 255) / a); + const auto b = static_cast( + ((source.b * source.a) + (((dest.b * dest.a) * (255 - source.a))) / 255) / a); const sf::Color composite(r, g, b, a); sf::Image image1; diff --git a/test/Graphics/Rect.cpp b/test/Graphics/Rect.cpp index e83c3cf33..7269f0395 100644 --- a/test/Graphics/Rect.cpp +++ b/test/Graphics/Rect.cpp @@ -1,9 +1,10 @@ #include #include -#include #include +#include + TEST_CASE("sf::Rect class template - [graphics]") { SUBCASE("Construction") @@ -30,7 +31,7 @@ TEST_CASE("sf::Rect class template - [graphics]") { sf::Vector2i position(1, 2); sf::Vector2i dimension(3, 4); - sf::IntRect rectangle(position, dimension); + sf::IntRect rectangle(position, dimension); CHECK(rectangle.left == 1); CHECK(rectangle.top == 2); @@ -41,7 +42,7 @@ TEST_CASE("sf::Rect class template - [graphics]") SUBCASE("Conversion constructor") { sf::FloatRect sourceRectangle({1.0f, 2.0f}, {3.0f, 4.0f}); - sf::IntRect rectangle(sourceRectangle); + sf::IntRect rectangle(sourceRectangle); CHECK(rectangle.left == static_cast(sourceRectangle.left)); CHECK(rectangle.top == static_cast(sourceRectangle.top)); diff --git a/test/Graphics/RectangleShape.cpp b/test/Graphics/RectangleShape.cpp index d90dc05de..dad3778fa 100644 --- a/test/Graphics/RectangleShape.cpp +++ b/test/Graphics/RectangleShape.cpp @@ -1,8 +1,9 @@ #include -#include #include +#include + TEST_CASE("sf::RectangleShape class - [graphics]") { SUBCASE("Default constructor") diff --git a/test/Graphics/RenderStates.cpp b/test/Graphics/RenderStates.cpp index 32cedcc7c..211593259 100644 --- a/test/Graphics/RenderStates.cpp +++ b/test/Graphics/RenderStates.cpp @@ -1,8 +1,9 @@ #include -#include #include +#include + TEST_CASE("sf::RenderStates class - [graphics]") { SUBCASE("Construction") @@ -18,8 +19,12 @@ TEST_CASE("sf::RenderStates class - [graphics]") SUBCASE("BlendMode constructor") { - const sf::BlendMode blendMode(sf::BlendMode::Zero, sf::BlendMode::SrcColor, sf::BlendMode::ReverseSubtract, - sf::BlendMode::OneMinusDstAlpha, sf::BlendMode::DstAlpha, sf::BlendMode::Max); + const sf::BlendMode blendMode(sf::BlendMode::Zero, + sf::BlendMode::SrcColor, + sf::BlendMode::ReverseSubtract, + sf::BlendMode::OneMinusDstAlpha, + sf::BlendMode::DstAlpha, + sf::BlendMode::Max); const sf::RenderStates renderStates(blendMode); CHECK(renderStates.blendMode == blendMode); CHECK(renderStates.transform == sf::Transform()); @@ -29,7 +34,7 @@ TEST_CASE("sf::RenderStates class - [graphics]") SUBCASE("Transform constructor") { - const sf::Transform transform(10, 9, 8, 7, 6, 5, 4, 3, 2); + const sf::Transform transform(10, 9, 8, 7, 6, 5, 4, 3, 2); const sf::RenderStates renderStates(transform); CHECK(renderStates.blendMode == sf::BlendMode()); CHECK(renderStates.transform == transform); @@ -39,7 +44,7 @@ TEST_CASE("sf::RenderStates class - [graphics]") SUBCASE("Texture constructor") { - const sf::Texture* texture = nullptr; + const sf::Texture* texture = nullptr; const sf::RenderStates renderStates(texture); CHECK(renderStates.blendMode == sf::BlendMode()); CHECK(renderStates.transform == sf::Transform()); @@ -49,7 +54,7 @@ TEST_CASE("sf::RenderStates class - [graphics]") SUBCASE("Shader constructor") { - const sf::Shader* shader = nullptr; + const sf::Shader* shader = nullptr; const sf::RenderStates renderStates(shader); CHECK(renderStates.blendMode == sf::BlendMode()); CHECK(renderStates.transform == sf::Transform()); @@ -59,9 +64,13 @@ TEST_CASE("sf::RenderStates class - [graphics]") SUBCASE("Verbose constructor") { - const sf::BlendMode blendMode(sf::BlendMode::One, sf::BlendMode::SrcColor, sf::BlendMode::ReverseSubtract, - sf::BlendMode::OneMinusDstAlpha, sf::BlendMode::DstAlpha, sf::BlendMode::Max); - const sf::Transform transform(10, 2, 3, 4, 50, 40, 30, 20, 10); + const sf::BlendMode blendMode(sf::BlendMode::One, + sf::BlendMode::SrcColor, + sf::BlendMode::ReverseSubtract, + sf::BlendMode::OneMinusDstAlpha, + sf::BlendMode::DstAlpha, + sf::BlendMode::Max); + const sf::Transform transform(10, 2, 3, 4, 50, 40, 30, 20, 10); const sf::RenderStates renderStates(blendMode, transform, nullptr, nullptr); CHECK(renderStates.blendMode == blendMode); CHECK(renderStates.transform == transform); diff --git a/test/Graphics/Shape.cpp b/test/Graphics/Shape.cpp index b8e704ba1..33c0c669d 100644 --- a/test/Graphics/Shape.cpp +++ b/test/Graphics/Shape.cpp @@ -1,13 +1,13 @@ #include -#include #include +#include + class TriangleShape : public sf::Shape { public: - explicit TriangleShape(const sf::Vector2f& size) - : m_size(size) + explicit TriangleShape(const sf::Vector2f& size) : m_size(size) { update(); } @@ -22,9 +22,12 @@ public: switch (index) { default: - case 0: return sf::Vector2f(m_size.x / 2, 0); - case 1: return sf::Vector2f(0, m_size.y); - case 2: return sf::Vector2f(m_size.x, m_size.y); + case 0: + return sf::Vector2f(m_size.x / 2, 0); + case 1: + return sf::Vector2f(0, m_size.y); + case 2: + return sf::Vector2f(m_size.x, m_size.y); } } diff --git a/test/Graphics/Transform.cpp b/test/Graphics/Transform.cpp index ff59c5552..c15a3a792 100644 --- a/test/Graphics/Transform.cpp +++ b/test/Graphics/Transform.cpp @@ -1,10 +1,11 @@ #include #include -#include -#include #include +#include +#include + namespace std { std::ostream& operator<<(std::ostream& out, const std::vector& vector) @@ -15,7 +16,7 @@ std::ostream& operator<<(std::ostream& out, const std::vector& vector) out << vector.back() << " }"; return out; } -} +} // namespace std TEST_CASE("sf::Transform class - [graphics]") { @@ -28,31 +29,27 @@ TEST_CASE("sf::Transform class - [graphics]") SUBCASE("3x3 matrix constructor") { - const sf::Transform transform(10.0f, 11.0f, 12.0f, - 13.0f, 14.0f, 15.0f, - 16.0f, 17.0f, 18.0f); + const sf::Transform transform(10.0f, 11.0f, 12.0f, 13.0f, 14.0f, 15.0f, 16.0f, 17.0f, 18.0f); const std::vector matrix(transform.getMatrix(), transform.getMatrix() + 16); - CHECK(matrix == std::vector{10.0f, 13.0f, 0.0f, 16.0f, - 11.0f, 14.0f, 0.0f, 17.0f, - 0.0f, 0.0f, 1.0f, 0.0f, - 12.0f, 15.0f, 0.0f, 18.0f}); + CHECK( + matrix == + std::vector{10.0f, 13.0f, 0.0f, 16.0f, 11.0f, 14.0f, 0.0f, 17.0f, 0.0f, 0.0f, 1.0f, 0.0f, 12.0f, 15.0f, 0.0f, 18.0f}); } } SUBCASE("Identity matrix") { const std::vector matrix(sf::Transform::Identity.getMatrix(), sf::Transform::Identity.getMatrix() + 16); - CHECK(matrix == std::vector{1.0f, 0.0f, 0.0f, 0.0f, - 0.0f, 1.0f, 0.0f, 0.0f, - 0.0f, 0.0f, 1.0f, 0.0f, - 0.0f, 0.0f, 0.0f, 1.0f}); + CHECK(matrix == + std::vector{1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f}); } SUBCASE("getInverse()") { CHECK(sf::Transform::Identity.getInverse() == sf::Transform::Identity); CHECK(sf::Transform(1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f, 7.0f, 8.0f, 9.0f).getInverse() == sf::Transform::Identity); - CHECK(sf::Transform(1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 4.0f, 3.0f, 2.0f, 1.0f).getInverse() == sf::Transform(0.375f, -0.5f, 0.875f, -1.0f, 1.0f, -1.0f, 0.875f, -0.5f, 0.375f)); + CHECK(sf::Transform(1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 4.0f, 3.0f, 2.0f, 1.0f).getInverse() == + sf::Transform(0.375f, -0.5f, 0.875f, -1.0f, 1.0f, -1.0f, 0.875f, -0.5f, 0.375f)); } SUBCASE("transformPoint()") @@ -65,9 +62,7 @@ TEST_CASE("sf::Transform class - [graphics]") CHECK(sf::Transform::Identity.transformPoint({1.0f, 1.0f}) == sf::Vector2f(1.0f, 1.0f)); CHECK(sf::Transform::Identity.transformPoint({10.0f, 10.0f}) == sf::Vector2f(10.0f, 10.0f)); - const sf::Transform transform(1.0f, 2.0f, 3.0f, - 4.0f, 5.0f, 4.0f, - 3.0f, 2.0f, 1.0f); + const sf::Transform transform(1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 4.0f, 3.0f, 2.0f, 1.0f); CHECK(transform.transformPoint({-1.0f, -1.0f}) == sf::Vector2f(0.0f, -5.0f)); CHECK(transform.transformPoint({0.0f, 0.0f}) == sf::Vector2f(3.0f, 4.0f)); CHECK(transform.transformPoint({1.0f, 1.0f}) == sf::Vector2f(6.0f, 13.0f)); @@ -75,16 +70,19 @@ TEST_CASE("sf::Transform class - [graphics]") SUBCASE("transformRect()") { - CHECK(sf::Transform::Identity.transformRect({{-200.0f, -200.0f}, {-100.0f, -100.0f}}) == sf::FloatRect({-300.0f, -300.0f}, {100.0f, 100.0f})); - CHECK(sf::Transform::Identity.transformRect({{0.0f, 0.0f}, {0.0f, 0.0f}}) == sf::FloatRect({0.0f, 0.0f}, {0.0f, 0.0f})); - CHECK(sf::Transform::Identity.transformRect({{100.0f, 100.0f}, {200.0f, 200.0f}}) == sf::FloatRect({100.0f, 100.0f}, {200.0f, 200.0f})); + CHECK(sf::Transform::Identity.transformRect({{-200.0f, -200.0f}, {-100.0f, -100.0f}}) == + sf::FloatRect({-300.0f, -300.0f}, {100.0f, 100.0f})); + CHECK(sf::Transform::Identity.transformRect({{0.0f, 0.0f}, {0.0f, 0.0f}}) == + sf::FloatRect({0.0f, 0.0f}, {0.0f, 0.0f})); + CHECK(sf::Transform::Identity.transformRect({{100.0f, 100.0f}, {200.0f, 200.0f}}) == + sf::FloatRect({100.0f, 100.0f}, {200.0f, 200.0f})); - const sf::Transform transform(1.0f, 2.0f, 3.0f, - 4.0f, 5.0f, 4.0f, - 3.0f, 2.0f, 1.0f); - CHECK(transform.transformRect({{-100.0f, -100.0f}, {200.0f, 200.0f}}) == sf::FloatRect({-297.0f, -896.0f}, {600.0f, 1800.0f})); + const sf::Transform transform(1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 4.0f, 3.0f, 2.0f, 1.0f); + CHECK(transform.transformRect({{-100.0f, -100.0f}, {200.0f, 200.0f}}) == + sf::FloatRect({-297.0f, -896.0f}, {600.0f, 1800.0f})); CHECK(transform.transformRect({{0.0f, 0.0f}, {0.0f, 0.0f}}) == sf::FloatRect({3.0f, 4.0f}, {0.0f, 0.0f})); - CHECK(transform.transformRect({{100.0f, 100.0f}, {200.0f, 200.0f}}) == sf::FloatRect({303.0f, 904.0f}, {600.0f, 1800.0f})); + CHECK(transform.transformRect({{100.0f, 100.0f}, {200.0f, 200.0f}}) == + sf::FloatRect({303.0f, 904.0f}, {600.0f, 1800.0f})); } SUBCASE("combine()") @@ -93,20 +91,12 @@ TEST_CASE("sf::Transform class - [graphics]") CHECK(identity.combine(sf::Transform::Identity) == sf::Transform::Identity); CHECK(identity.combine(sf::Transform::Identity).combine(sf::Transform::Identity) == sf::Transform::Identity); - sf::Transform transform(1.0f, 2.0f, 3.0f, - 4.0f, 5.0f, 4.0f, - 3.0f, 2.0f, 1.0f); + sf::Transform transform(1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 4.0f, 3.0f, 2.0f, 1.0f); CHECK(identity.combine(transform) == transform); CHECK(transform.combine(sf::Transform::Identity) == transform); - CHECK(transform.combine(transform) == sf::Transform(18.0f, 18.0f, 14.0f, - 36.0f, 41.0f, 36.0f, - 14.0f, 18.0f, 18.0f)); - CHECK(transform.combine(sf::Transform(10.0f, 2.0f, 3.0f, - 4.0f, 50.0f, 40.0f, - 30.0f, 20.0f, 10.0f)) - == sf::Transform( 672.0f, 1216.0f, 914.0f, - 1604.0f, 2842.0f, 2108.0f, - 752.0f, 1288.0f, 942.0f)); + CHECK(transform.combine(transform) == sf::Transform(18.0f, 18.0f, 14.0f, 36.0f, 41.0f, 36.0f, 14.0f, 18.0f, 18.0f)); + CHECK(transform.combine(sf::Transform(10.0f, 2.0f, 3.0f, 4.0f, 50.0f, 40.0f, 30.0f, 20.0f, 10.0f)) == + sf::Transform(672.0f, 1216.0f, 914.0f, 1604.0f, 2842.0f, 2108.0f, 752.0f, 1288.0f, 942.0f)); } SUBCASE("translate()") @@ -122,18 +112,14 @@ TEST_CASE("sf::Transform class - [graphics]") { sf::Transform transform; transform.rotate(sf::degrees(90)); - CHECK(transform == Approx(sf::Transform(0, -1, 0, - 1, 0, 0, - 0, 0, 1))); + CHECK(transform == Approx(sf::Transform(0, -1, 0, 1, 0, 0, 0, 0, 1))); } SUBCASE("Around custom point") { sf::Transform transform; transform.rotate(sf::degrees(90), {1.0f, 0.0f}); - CHECK(transform == Approx(sf::Transform(0, -1, 1, - 1, 0, -1, - 0, 0, 1))); + CHECK(transform == Approx(sf::Transform(0, -1, 1, 1, 0, -1, 0, 0, 1))); } } @@ -162,39 +148,23 @@ TEST_CASE("sf::Transform class - [graphics]") CHECK(sf::Transform::Identity * sf::Transform::Identity == sf::Transform::Identity); CHECK(sf::Transform::Identity * sf::Transform::Identity * sf::Transform::Identity == sf::Transform::Identity); - const sf::Transform transform(1.0f, 2.0f, 3.0f, - 4.0f, 5.0f, 4.0f, - 3.0f, 2.0f, 1.0f); + const sf::Transform transform(1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 4.0f, 3.0f, 2.0f, 1.0f); CHECK(sf::Transform::Identity * transform == transform); CHECK(transform * sf::Transform::Identity == transform); - CHECK(transform * transform == sf::Transform(18.0f, 18.0f, 14.0f, - 36.0f, 41.0f, 36.0f, - 14.0f, 18.0f, 18.0f)); - CHECK(transform * sf::Transform(10.0f, 2.0f, 3.0f, - 4.0f, 50.0f, 40.0f, - 30.0f, 20.0f, 10.0f) - == sf::Transform(108.0f, 162.0f, 113.0f, - 180.0f, 338.0f, 252.0f, - 68.0f, 126.0f, 99.0f)); + CHECK(transform * transform == sf::Transform(18.0f, 18.0f, 14.0f, 36.0f, 41.0f, 36.0f, 14.0f, 18.0f, 18.0f)); + CHECK(transform * sf::Transform(10.0f, 2.0f, 3.0f, 4.0f, 50.0f, 40.0f, 30.0f, 20.0f, 10.0f) == + sf::Transform(108.0f, 162.0f, 113.0f, 180.0f, 338.0f, 252.0f, 68.0f, 126.0f, 99.0f)); } SUBCASE("operator*=") { - sf::Transform transform(1.0f, 2.0f, 3.0f, - 4.0f, 5.0f, 4.0f, - 3.0f, 2.0f, 1.0f); + sf::Transform transform(1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 4.0f, 3.0f, 2.0f, 1.0f); transform *= sf::Transform::Identity; CHECK(transform == sf::Transform(1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 4.0f, 3.0f, 2.0f, 1.0f)); transform *= transform; - CHECK(transform == sf::Transform(18.0f, 18.0f, 14.0f, - 36.0f, 41.0f, 36.0f, - 14.0f, 18.0f, 18.0f)); - transform *= sf::Transform(10.0f, 2.0f, 3.0f, - 4.0f, 50.0f, 40.0f, - 30.0f, 20.0f, 10.0f); - CHECK(transform == sf::Transform( 672.0f, 1216.0f, 914.0f, - 1604.0f, 2842.0f, 2108.0f, - 752.0f, 1288.0f, 942.0f)); + CHECK(transform == sf::Transform(18.0f, 18.0f, 14.0f, 36.0f, 41.0f, 36.0f, 14.0f, 18.0f, 18.0f)); + transform *= sf::Transform(10.0f, 2.0f, 3.0f, 4.0f, 50.0f, 40.0f, 30.0f, 20.0f, 10.0f); + CHECK(transform == sf::Transform(672.0f, 1216.0f, 914.0f, 1604.0f, 2842.0f, 2108.0f, 752.0f, 1288.0f, 942.0f)); } SUBCASE("operator* with vector") @@ -207,9 +177,7 @@ TEST_CASE("sf::Transform class - [graphics]") CHECK(sf::Transform::Identity * sf::Vector2f(1.0f, 1.0f) == sf::Vector2f(1.0f, 1.0f)); CHECK(sf::Transform::Identity * sf::Vector2f(10.0f, 10.0f) == sf::Vector2f(10.0f, 10.0f)); - const sf::Transform transform(1.0f, 2.0f, 3.0f, - 4.0f, 5.0f, 4.0f, - 3.0f, 2.0f, 1.0f); + const sf::Transform transform(1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 4.0f, 3.0f, 2.0f, 1.0f); CHECK(transform * sf::Vector2f(-1.0f, -1.0f) == sf::Vector2f(0.0f, -5.0f)); CHECK(transform * sf::Vector2f(0.0f, 0.0f) == sf::Vector2f(3.0f, 4.0f)); CHECK(transform * sf::Vector2f(1.0f, 1.0f) == sf::Vector2f(6.0f, 13.0f)); @@ -220,10 +188,10 @@ TEST_CASE("sf::Transform class - [graphics]") CHECK(sf::Transform::Identity == sf::Transform::Identity); CHECK(sf::Transform() == sf::Transform()); CHECK(sf::Transform(0, 0, 0, 0, 0, 0, 0, 0, 0) == sf::Transform(0, 0, 0, 0, 0, 0, 0, 0, 0)); - CHECK(sf::Transform(0.0001f, 0.0001f, 0.0001f, 0.0001f, 0.0001f, 0.0001f, 0.0001f, 0.0001f, 0.0001f) - == sf::Transform(0.0001f, 0.0001f, 0.0001f, 0.0001f, 0.0001f, 0.0001f, 0.0001f, 0.0001f, 0.0001f)); - CHECK(sf::Transform(1000.0f, 1000.0f, 1000.0f, 1000.0f, 1000.0f, 1000.0f, 1000.0f, 1000.0f, 1000.0f) - == sf::Transform(1000.0f, 1000.0f, 1000.0f, 1000.0f, 1000.0f, 1000.0f, 1000.0f, 1000.0f, 1000.0f)); + CHECK(sf::Transform(0.0001f, 0.0001f, 0.0001f, 0.0001f, 0.0001f, 0.0001f, 0.0001f, 0.0001f, 0.0001f) == + sf::Transform(0.0001f, 0.0001f, 0.0001f, 0.0001f, 0.0001f, 0.0001f, 0.0001f, 0.0001f, 0.0001f)); + CHECK(sf::Transform(1000.0f, 1000.0f, 1000.0f, 1000.0f, 1000.0f, 1000.0f, 1000.0f, 1000.0f, 1000.0f) == + sf::Transform(1000.0f, 1000.0f, 1000.0f, 1000.0f, 1000.0f, 1000.0f, 1000.0f, 1000.0f, 1000.0f)); } SUBCASE("operator!=") @@ -231,10 +199,10 @@ TEST_CASE("sf::Transform class - [graphics]") CHECK_FALSE(sf::Transform::Identity != sf::Transform::Identity); CHECK_FALSE(sf::Transform() != sf::Transform()); CHECK_FALSE(sf::Transform(0, 0, 0, 0, 0, 0, 0, 0, 0) != sf::Transform(0, 0, 0, 0, 0, 0, 0, 0, 0)); - CHECK_FALSE(sf::Transform(0.0001f, 0.0001f, 0.0001f, 0.0001f, 0.0001f, 0.0001f, 0.0001f, 0.0001f, 0.0001f) - != sf::Transform(0.0001f, 0.0001f, 0.0001f, 0.0001f, 0.0001f, 0.0001f, 0.0001f, 0.0001f, 0.0001f)); - CHECK_FALSE(sf::Transform(1000.0f, 1000.0f, 1000.0f, 1000.0f, 1000.0f, 1000.0f, 1000.0f, 1000.0f, 1000.0f) - != sf::Transform(1000.0f, 1000.0f, 1000.0f, 1000.0f, 1000.0f, 1000.0f, 1000.0f, 1000.0f, 1000.0f)); + CHECK_FALSE(sf::Transform(0.0001f, 0.0001f, 0.0001f, 0.0001f, 0.0001f, 0.0001f, 0.0001f, 0.0001f, 0.0001f) != + sf::Transform(0.0001f, 0.0001f, 0.0001f, 0.0001f, 0.0001f, 0.0001f, 0.0001f, 0.0001f, 0.0001f)); + CHECK_FALSE(sf::Transform(1000.0f, 1000.0f, 1000.0f, 1000.0f, 1000.0f, 1000.0f, 1000.0f, 1000.0f, 1000.0f) != + sf::Transform(1000.0f, 1000.0f, 1000.0f, 1000.0f, 1000.0f, 1000.0f, 1000.0f, 1000.0f, 1000.0f)); CHECK(sf::Transform(1, 0, 0, 0, 0, 0, 0, 0, 0) != sf::Transform(0, 0, 0, 0, 0, 0, 0, 0, 0)); CHECK(sf::Transform(0, 1, 0, 0, 0, 0, 0, 0, 0) != sf::Transform(0, 0, 0, 0, 0, 0, 0, 0, 0)); diff --git a/test/Graphics/Transformable.cpp b/test/Graphics/Transformable.cpp index d69eebfa9..56197d096 100644 --- a/test/Graphics/Transformable.cpp +++ b/test/Graphics/Transformable.cpp @@ -1,8 +1,9 @@ #include -#include #include +#include + TEST_CASE("sf::Transformable class - [graphics]") { SUBCASE("Construction") diff --git a/test/Graphics/Vertex.cpp b/test/Graphics/Vertex.cpp index 8356b1577..45e233ab9 100644 --- a/test/Graphics/Vertex.cpp +++ b/test/Graphics/Vertex.cpp @@ -1,8 +1,9 @@ #include -#include #include +#include + TEST_CASE("sf::Vertex class - [graphics]") { SUBCASE("Construction") diff --git a/test/Graphics/VertexArray.cpp b/test/Graphics/VertexArray.cpp index 0ba3e563d..5da0397e1 100644 --- a/test/Graphics/VertexArray.cpp +++ b/test/Graphics/VertexArray.cpp @@ -1,8 +1,9 @@ #include -#include #include +#include + TEST_CASE("sf::VertexArray class - [graphics]") { SUBCASE("Construction") @@ -61,7 +62,7 @@ TEST_CASE("sf::VertexArray class - [graphics]") SUBCASE("Append to array") { - sf::VertexArray vertexArray; + sf::VertexArray vertexArray; const sf::Vertex vertex({1, 2}, {3, 4, 5, 6}, {7, 8}); vertexArray.append(vertex); CHECK(vertexArray.getVertexCount() == 1); diff --git a/test/Graphics/View.cpp b/test/Graphics/View.cpp index 2ff53c942..dd76c5c36 100644 --- a/test/Graphics/View.cpp +++ b/test/Graphics/View.cpp @@ -1,8 +1,9 @@ #include -#include #include +#include + TEST_CASE("sf::View class - [graphics]") { SUBCASE("Construction") @@ -64,12 +65,16 @@ TEST_CASE("sf::View class - [graphics]") sf::View view; view.setRotation(sf::degrees(-345)); CHECK(view.getRotation() == sf::degrees(15)); - CHECK(view.getTransform() == Approx(sf::Transform(0.00193185f, 0.000517638f, -1.22474f, 0.000517638f, -0.00193185f, 0.707107f, 0, 0, 1))); - CHECK(view.getInverseTransform() == Approx(sf::Transform(482.963f, 129.41f, 500, 129.41f, -482.963f, 500, 0, 0, 1))); + CHECK(view.getTransform() == + Approx(sf::Transform(0.00193185f, 0.000517638f, -1.22474f, 0.000517638f, -0.00193185f, 0.707107f, 0, 0, 1))); + CHECK(view.getInverseTransform() == + Approx(sf::Transform(482.963f, 129.41f, 500, 129.41f, -482.963f, 500, 0, 0, 1))); view.setRotation(sf::degrees(400)); CHECK(view.getRotation() == sf::degrees(40)); - CHECK(view.getTransform() == Approx(sf::Transform(0.00153209f, 0.00128558f, -1.40883f, 0.00128558f, -0.00153209f, 0.123257f, 0, 0, 1 ))); - CHECK(view.getInverseTransform() == Approx(sf::Transform(383.022f, 321.394f, 500, 321.394f, -383.022f, 500, 0, 0, 1))); + CHECK(view.getTransform() == + Approx(sf::Transform(0.00153209f, 0.00128558f, -1.40883f, 0.00128558f, -0.00153209f, 0.123257f, 0, 0, 1))); + CHECK(view.getInverseTransform() == + Approx(sf::Transform(383.022f, 321.394f, 500, 321.394f, -383.022f, 500, 0, 0, 1))); } SUBCASE("Set/get viewport") @@ -93,7 +98,7 @@ TEST_CASE("sf::View class - [graphics]") CHECK(view.getSize() == sf::Vector2f(3, 4)); CHECK(view.getRotation() == sf::Angle::Zero); CHECK(view.getViewport() == sf::FloatRect({150, 250}, {500, 750})); - CHECK(view.getTransform() == Approx(sf::Transform(0.666667f, 0, -1.66667f, 0, -0.5f, 2, 0, 0, 1 ))); + CHECK(view.getTransform() == Approx(sf::Transform(0.666667f, 0, -1.66667f, 0, -0.5f, 2, 0, 0, 1))); CHECK(view.getInverseTransform() == Approx(sf::Transform(1.5f, 0, 2.5f, 0, -2, 4, 0, 0, 1))); } @@ -113,7 +118,8 @@ TEST_CASE("sf::View class - [graphics]") view.setRotation(sf::degrees(45)); view.rotate(sf::degrees(-15)); CHECK(view.getRotation() == sf::degrees(30)); - CHECK(view.getTransform() == Approx(sf::Transform(0.00173205f, 0.001f, -1.36603f, 0.001f, -0.00173205f, 0.366025f, 0, 0, 1))); + CHECK(view.getTransform() == + Approx(sf::Transform(0.00173205f, 0.001f, -1.36603f, 0.001f, -0.00173205f, 0.366025f, 0, 0, 1))); CHECK(view.getInverseTransform() == Approx(sf::Transform(433.013f, 250, 500, 250, -433.013f, 500, 0, 0, 1))); } diff --git a/test/Network/Packet.cpp b/test/Network/Packet.cpp index 7ad8504c7..4da3bb24d 100644 --- a/test/Network/Packet.cpp +++ b/test/Network/Packet.cpp @@ -1,6 +1,7 @@ #include #include + #include template diff --git a/test/System/Angle.cpp b/test/System/Angle.cpp index 834983e99..2a5614374 100644 --- a/test/System/Angle.cpp +++ b/test/System/Angle.cpp @@ -1,8 +1,9 @@ #include -#include #include +#include + TEST_CASE("sf::Angle class - [system]") { SUBCASE("Construction") @@ -274,15 +275,15 @@ TEST_CASE("sf::Angle class - [system]") using namespace sf::Literals; CHECK(0.0_rad == sf::Angle::Zero); CHECK(1.0_rad == sf::radians(1)); - CHECK(-1.0_rad ==sf::radians(-1)); + CHECK(-1.0_rad == sf::radians(-1)); CHECK(3.14_rad == sf::radians(3.14f)); CHECK(-3.14_rad == sf::radians(-3.14f)); CHECK(0_rad == sf::Angle::Zero); CHECK(1_rad == sf::radians(1)); CHECK(-1_rad == sf::radians(-1)); - CHECK(100_rad ==sf::radians(100)); - CHECK(-100_rad ==sf::radians(-100)); + CHECK(100_rad == sf::radians(100)); + CHECK(-100_rad == sf::radians(-100)); } } diff --git a/test/System/Clock.cpp b/test/System/Clock.cpp index 3d28afa9a..5e07b7dec 100644 --- a/test/System/Clock.cpp +++ b/test/System/Clock.cpp @@ -1,10 +1,11 @@ #include #include -#include -#include #include +#include +#include + TEST_CASE("sf::Clock class - [system]") { SUBCASE("getElapsedTime()") diff --git a/test/System/Err.cpp b/test/System/Err.cpp index 9468d4bc3..aed9563f2 100644 --- a/test/System/Err.cpp +++ b/test/System/Err.cpp @@ -1,8 +1,9 @@ #include -#include #include +#include + TEST_CASE("sf::err - [system]") { SUBCASE("Overflow default buffer") @@ -10,8 +11,8 @@ TEST_CASE("sf::err - [system]") // No assertion macros in this subcase since nothing about this can be directly observed. // Intention is to ensure DefaultErrStreamBuf::overflow gets called. sf::err() << "SFML is a simple, fast, cross-platform and object-oriented multimedia API." - "It provides access to windowing, graphics, audio and network." - "It is written in C++, and has bindings for various languages such as C, .Net, Ruby, Python."; + "It provides access to windowing, graphics, audio and network." + "It is written in C++, and has bindings for various languages such as C, .Net, Ruby, Python."; } SUBCASE("Redirect buffer to observe contents") diff --git a/test/System/FileInputStream.cpp b/test/System/FileInputStream.cpp index ee95f870f..367a755ef 100644 --- a/test/System/FileInputStream.cpp +++ b/test/System/FileInputStream.cpp @@ -1,12 +1,13 @@ #include + +#include + #include #include #include #include #include -#include - static std::string getTemporaryFilePath() { static int counter = 0; @@ -29,8 +30,7 @@ private: public: // Create a temporary file with a randomly generated path, containing 'contents'. - TemporaryFile(const std::string& contents) - : m_path(getTemporaryFilePath()) + TemporaryFile(const std::string& contents) : m_path(getTemporaryFilePath()) { std::ofstream ofs(m_path); assert(ofs); @@ -73,7 +73,7 @@ TEST_CASE("sf::FileInputStream class - [system]") { const std::string fileContents = "hello world"; - TemporaryFile tmpFile(fileContents); + TemporaryFile tmpFile(fileContents); sf::FileInputStream fis; REQUIRE(fis.open(tmpFile.getPath())); diff --git a/test/System/MemoryInputStream.cpp b/test/System/MemoryInputStream.cpp index ae6b724c1..82bdf9880 100644 --- a/test/System/MemoryInputStream.cpp +++ b/test/System/MemoryInputStream.cpp @@ -1,9 +1,10 @@ #include -#include -#include #include +#include +#include + TEST_CASE("sf::MemoryInputStream class - [system]") { SUBCASE("Empty stream") @@ -19,7 +20,7 @@ TEST_CASE("sf::MemoryInputStream class - [system]") SUBCASE("Open memory stream") { using namespace std::literals::string_view_literals; - constexpr auto memoryContents = "hello world"sv; + constexpr auto memoryContents = "hello world"sv; sf::MemoryInputStream mis; mis.open(memoryContents.data(), sizeof(char) * memoryContents.size()); diff --git a/test/System/Time.cpp b/test/System/Time.cpp index 8d2d07302..f71a88a6e 100644 --- a/test/System/Time.cpp +++ b/test/System/Time.cpp @@ -1,8 +1,9 @@ #include -#include #include +#include + TEST_CASE("sf::Time class - [system]") { SUBCASE("Construction") diff --git a/test/System/Vector2.cpp b/test/System/Vector2.cpp index 276365539..a7c31a2c6 100644 --- a/test/System/Vector2.cpp +++ b/test/System/Vector2.cpp @@ -1,10 +1,11 @@ #include -#include -#include -#include #include +#include +#include +#include + using namespace sf::Literals; // Use sf::Vector2i for tests (except for float vector algebra). @@ -77,9 +78,11 @@ TEST_CASE("sf::Vector2 class template - [system]") CHECK(sf::Vector2f(-1, -360_deg) == Approx(sf::Vector2f(-1, 0))); CHECK(sf::Vector2f(4.2f, 0_deg) == sf::Vector2f(4.2f, 0)); - CHECK(sf::Vector2f(4.2f, 45_deg) == Approx(sf::Vector2f(4.2f * std::sqrt(2.f) / 2.f, 4.2f * std::sqrt(2.f) / 2.f))); + CHECK(sf::Vector2f(4.2f, 45_deg) == + Approx(sf::Vector2f(4.2f * std::sqrt(2.f) / 2.f, 4.2f * std::sqrt(2.f) / 2.f))); CHECK(sf::Vector2f(4.2f, 90_deg) == Approx(sf::Vector2f(0, 4.2f))); - CHECK(sf::Vector2f(4.2f, 135_deg) == Approx(sf::Vector2f(-4.2f * std::sqrt(2.f) / 2.f, 4.2f * std::sqrt(2.f) / 2.f))); + CHECK(sf::Vector2f(4.2f, 135_deg) == + Approx(sf::Vector2f(-4.2f * std::sqrt(2.f) / 2.f, 4.2f * std::sqrt(2.f) / 2.f))); CHECK(sf::Vector2f(4.2f, 180_deg) == Approx(sf::Vector2f(-4.2f, 0))); CHECK(sf::Vector2f(4.2f, 270_deg) == Approx(sf::Vector2f(0, -4.2f))); CHECK(sf::Vector2f(4.2f, 360_deg) == Approx(sf::Vector2f(4.2f, 0))); @@ -104,7 +107,7 @@ TEST_CASE("sf::Vector2 class template - [system]") SUBCASE("Arithmetic operations between two vectors") { - sf::Vector2i firstVector(2, 5); + sf::Vector2i firstVector(2, 5); const sf::Vector2i secondVector(8, 3); SUBCASE("vector += vector") @@ -143,7 +146,7 @@ TEST_CASE("sf::Vector2 class template - [system]") SUBCASE("Arithmetic operations between vector and scalar value") { sf::Vector2i vector(26, 12); - int scalar = 2; + int scalar = 2; SUBCASE("vector * scalar") { @@ -273,7 +276,7 @@ TEST_CASE("sf::Vector2 class template - [system]") CHECK(w.angleTo(v) == Approx(158.9902_deg)); const float ratio = w.length() / v.length(); - CHECK(v.rotatedBy(-158.9902_deg) * ratio == Approx(w)); + CHECK(v.rotatedBy(-158.9902_deg) * ratio == Approx(w)); CHECK(w.rotatedBy(158.9902_deg) / ratio == Approx(v)); CHECK(v.perpendicular() == sf::Vector2f(-3.0f, 2.4f)); diff --git a/test/System/Vector3.cpp b/test/System/Vector3.cpp index f838d84f5..32f55644d 100644 --- a/test/System/Vector3.cpp +++ b/test/System/Vector3.cpp @@ -1,9 +1,10 @@ #include -#include -#include #include +#include +#include + // Use sf::Vector3i for tests (except for float vector algebra). // Test coverage is given, as there are no template specializations. @@ -96,7 +97,7 @@ TEST_CASE("sf::Vector3 class template - [system]") SUBCASE("Arithmetic operations between vector and scalar value") { sf::Vector3i vector(26, 12, 6); - int scalar = 2; + int scalar = 2; SUBCASE("vector * scalar") { diff --git a/test/TestUtilities/GraphicsUtil.cpp b/test/TestUtilities/GraphicsUtil.cpp index 58e132662..d22a5c14e 100644 --- a/test/TestUtilities/GraphicsUtil.cpp +++ b/test/TestUtilities/GraphicsUtil.cpp @@ -1,53 +1,49 @@ -#include - #include #include #include +#include #include namespace sf { - std::ostream& operator <<(std::ostream& os, const sf::BlendMode& blendMode) - { - os << "( " << blendMode.colorSrcFactor << ", " << blendMode.colorDstFactor << ", " - << blendMode.colorEquation << ", " << blendMode.alphaSrcFactor << ", " - << blendMode.alphaDstFactor << ", " << blendMode.alphaEquation << " )"; +std::ostream& operator<<(std::ostream& os, const sf::BlendMode& blendMode) +{ + os << "( " << blendMode.colorSrcFactor << ", " << blendMode.colorDstFactor << ", " << blendMode.colorEquation << ", " + << blendMode.alphaSrcFactor << ", " << blendMode.alphaDstFactor << ", " << blendMode.alphaEquation << " )"; - return os; - } - - std::ostream& operator <<(std::ostream& os, const sf::Color& color) - { - os << "0x" << std::hex << color.toInteger() << std::dec - << " (r=" << static_cast(color.r) - << ", g=" << static_cast(color.g) - << ", b=" << static_cast(color.b) - << ", a=" << static_cast(color.a) << ")"; - - return os; - } - - std::ostream& operator <<(std::ostream& os, const sf::Transform& transform) - { - const auto& matrix = transform.getMatrix(); - os << matrix[0] << ", " << matrix[4] << ", " << matrix[12] << ", "; - os << matrix[1] << ", " << matrix[5] << ", " << matrix[13] << ", "; - os << matrix[3] << ", " << matrix[7] << ", " << matrix[15]; - - return os; - } + return os; } +std::ostream& operator<<(std::ostream& os, const sf::Color& color) +{ + os << "0x" << std::hex << color.toInteger() << std::dec << " (r=" << static_cast(color.r) + << ", g=" << static_cast(color.g) << ", b=" << static_cast(color.b) + << ", a=" << static_cast(color.a) << ")"; + + return os; +} + +std::ostream& operator<<(std::ostream& os, const sf::Transform& transform) +{ + const auto& matrix = transform.getMatrix(); + os << matrix[0] << ", " << matrix[4] << ", " << matrix[12] << ", "; + os << matrix[1] << ", " << matrix[5] << ", " << matrix[13] << ", "; + os << matrix[3] << ", " << matrix[7] << ", " << matrix[15]; + + return os; +} +} // namespace sf + bool operator==(const sf::Transform& lhs, const Approx& rhs) { - return lhs.getMatrix()[0] == Approx(rhs.value.getMatrix()[0]) - && lhs.getMatrix()[4] == Approx(rhs.value.getMatrix()[4]) - && lhs.getMatrix()[12] == Approx(rhs.value.getMatrix()[12]) - && lhs.getMatrix()[1] == Approx(rhs.value.getMatrix()[1]) - && lhs.getMatrix()[5] == Approx(rhs.value.getMatrix()[5]) - && lhs.getMatrix()[13] == Approx(rhs.value.getMatrix()[13]) - && lhs.getMatrix()[3] == Approx(rhs.value.getMatrix()[3]) - && lhs.getMatrix()[7] == Approx(rhs.value.getMatrix()[7]) - && lhs.getMatrix()[15] == Approx(rhs.value.getMatrix()[15]); + return lhs.getMatrix()[0] == Approx(rhs.value.getMatrix()[0]) && + lhs.getMatrix()[4] == Approx(rhs.value.getMatrix()[4]) && + lhs.getMatrix()[12] == Approx(rhs.value.getMatrix()[12]) && + lhs.getMatrix()[1] == Approx(rhs.value.getMatrix()[1]) && + lhs.getMatrix()[5] == Approx(rhs.value.getMatrix()[5]) && + lhs.getMatrix()[13] == Approx(rhs.value.getMatrix()[13]) && + lhs.getMatrix()[3] == Approx(rhs.value.getMatrix()[3]) && + lhs.getMatrix()[7] == Approx(rhs.value.getMatrix()[7]) && + lhs.getMatrix()[15] == Approx(rhs.value.getMatrix()[15]); } diff --git a/test/TestUtilities/GraphicsUtil.hpp b/test/TestUtilities/GraphicsUtil.hpp index 737fb9386..fa4332863 100644 --- a/test/TestUtilities/GraphicsUtil.hpp +++ b/test/TestUtilities/GraphicsUtil.hpp @@ -6,32 +6,32 @@ #ifndef SFML_TESTUTILITIES_GRAPHICS_HPP #define SFML_TESTUTILITIES_GRAPHICS_HPP -#include - #include + +#include #include #include namespace sf { - struct BlendMode; - class Color; - class Transform; +struct BlendMode; +class Color; +class Transform; - std::ostream& operator <<(std::ostream& os, const BlendMode& blendMode); - std::ostream& operator <<(std::ostream& os, const Color& color); - std::ostream& operator <<(std::ostream& os, const Transform& transform); +std::ostream& operator<<(std::ostream& os, const BlendMode& blendMode); +std::ostream& operator<<(std::ostream& os, const Color& color); +std::ostream& operator<<(std::ostream& os, const Transform& transform); - template - std::ostream& operator <<(std::ostream& os, const sf::Rect& rect) - { - const auto flags = os.flags(); - os << std::fixed << std::setprecision(std::numeric_limits::max_digits10); - os << "(left=" << rect.left << ", top=" << rect.top << ", width=" << rect.width << ", height=" << rect.height << ")"; - os.flags(flags); - return os; - } +template +std::ostream& operator<<(std::ostream& os, const sf::Rect& rect) +{ + const auto flags = os.flags(); + os << std::fixed << std::setprecision(std::numeric_limits::max_digits10); + os << "(left=" << rect.left << ", top=" << rect.top << ", width=" << rect.width << ", height=" << rect.height << ")"; + os.flags(flags); + return os; } +} // namespace sf bool operator==(const sf::Transform& lhs, const Approx& rhs); diff --git a/test/TestUtilities/SystemUtil.cpp b/test/TestUtilities/SystemUtil.cpp index 99e6e0752..a1ad09af3 100644 --- a/test/TestUtilities/SystemUtil.cpp +++ b/test/TestUtilities/SystemUtil.cpp @@ -1,33 +1,33 @@ -#include - #include #include #include #include // for Approx +#include + namespace sf { - std::ostream& operator <<(std::ostream& os, const sf::Angle& angle) - { - os << std::fixed << std::setprecision(std::numeric_limits::max_digits10); - os << angle.asDegrees() << " deg"; - return os; - } - - std::ostream& operator <<(std::ostream& os, const sf::String& string) - { - os << string.toAnsiString(); - return os; - } - - std::ostream& operator <<(std::ostream& os, sf::Time time) - { - os << time.asMicroseconds() << "us"; - return os; - } +std::ostream& operator<<(std::ostream& os, const sf::Angle& angle) +{ + os << std::fixed << std::setprecision(std::numeric_limits::max_digits10); + os << angle.asDegrees() << " deg"; + return os; } +std::ostream& operator<<(std::ostream& os, const sf::String& string) +{ + os << string.toAnsiString(); + return os; +} + +std::ostream& operator<<(std::ostream& os, sf::Time time) +{ + os << time.asMicroseconds() << "us"; + return os; +} +} // namespace sf + bool operator==(const float& lhs, const Approx& rhs) { return static_cast(lhs) == doctest::Approx(static_cast(rhs.value)); diff --git a/test/TestUtilities/SystemUtil.hpp b/test/TestUtilities/SystemUtil.hpp index 9b268548a..cfd4d689e 100644 --- a/test/TestUtilities/SystemUtil.hpp +++ b/test/TestUtilities/SystemUtil.hpp @@ -16,30 +16,30 @@ // String conversions for doctest framework namespace sf { - class Angle; - class String; - class Time; +class Angle; +class String; +class Time; - std::ostream& operator <<(std::ostream& os, const sf::Angle& angle); - std::ostream& operator <<(std::ostream& os, const sf::String& string); - std::ostream& operator <<(std::ostream& os, sf::Time time); +std::ostream& operator<<(std::ostream& os, const sf::Angle& angle); +std::ostream& operator<<(std::ostream& os, const sf::String& string); +std::ostream& operator<<(std::ostream& os, sf::Time time); - template - std::ostream& operator <<(std::ostream& os, const sf::Vector2& vector) - { - os << std::fixed << std::setprecision(std::numeric_limits::max_digits10); - os << "(" << vector.x << ", " << vector.y << ")"; - return os; - } - - template - std::ostream& operator <<(std::ostream& os, const sf::Vector3& vector) - { - os << "(" << vector.x << ", " << vector.y << ", " << vector.z << ")"; - return os; - } +template +std::ostream& operator<<(std::ostream& os, const sf::Vector2& vector) +{ + os << std::fixed << std::setprecision(std::numeric_limits::max_digits10); + os << "(" << vector.x << ", " << vector.y << ")"; + return os; } +template +std::ostream& operator<<(std::ostream& os, const sf::Vector3& vector) +{ + os << "(" << vector.x << ", " << vector.y << ", " << vector.z << ")"; + return os; +} +} // namespace sf + //////////////////////////////////////////////////////////// /// Class template for creating custom approximate comparisons. /// To register a new type, simply implement a custom operator== @@ -48,7 +48,9 @@ namespace sf template struct Approx { - explicit Approx(const T& t) : value(t) {} + explicit Approx(const T& t) : value(t) + { + } const T& value; }; @@ -58,7 +60,7 @@ bool operator==(const sf::Vector3f& lhs, const Approx& rhs); bool operator==(const sf::Angle& lhs, const Approx& rhs); template -std::ostream& operator <<(std::ostream& os, const Approx& approx) +std::ostream& operator<<(std::ostream& os, const Approx& approx) { return os << approx.value; } diff --git a/test/TestUtilities/WindowUtil.cpp b/test/TestUtilities/WindowUtil.cpp index 5463559ab..eb8a79cab 100644 --- a/test/TestUtilities/WindowUtil.cpp +++ b/test/TestUtilities/WindowUtil.cpp @@ -1,12 +1,13 @@ // Note: No need to increase compile time by including TestUtilities/Window.hpp #include + #include namespace sf { - std::ostream& operator <<(std::ostream& os, const sf::VideoMode& videoMode) - { - os << videoMode.size.x << "x" << videoMode.size.y << "x" << videoMode.bitsPerPixel; - return os; - } +std::ostream& operator<<(std::ostream& os, const sf::VideoMode& videoMode) +{ + os << videoMode.size.x << "x" << videoMode.size.y << "x" << videoMode.bitsPerPixel; + return os; } +} // namespace sf diff --git a/test/TestUtilities/WindowUtil.hpp b/test/TestUtilities/WindowUtil.hpp index a0d0bc1a2..56b4cf646 100644 --- a/test/TestUtilities/WindowUtil.hpp +++ b/test/TestUtilities/WindowUtil.hpp @@ -11,9 +11,9 @@ // String conversions for doctest framework namespace sf { - class VideoMode; +class VideoMode; - std::ostream& operator <<(std::ostream& os, const sf::VideoMode& videoMode); -} +std::ostream& operator<<(std::ostream& os, const sf::VideoMode& videoMode); +} // namespace sf #endif // SFML_TESTUTILITIES_WINDOW_HPP diff --git a/test/Window/VideoMode.cpp b/test/Window/VideoMode.cpp index 195045e3c..f7073bb83 100644 --- a/test/Window/VideoMode.cpp +++ b/test/Window/VideoMode.cpp @@ -1,8 +1,9 @@ #include -#include #include +#include + TEST_CASE("sf::VideoMode class - [window]") { SUBCASE("Construction") diff --git a/tools/xcode/templates/SFML/SFML App.xctemplate/ResourcePath.mm b/tools/xcode/templates/SFML/SFML App.xctemplate/ResourcePath.mm index 3c1e0aba9..254f820f2 100644 --- a/tools/xcode/templates/SFML/SFML App.xctemplate/ResourcePath.mm +++ b/tools/xcode/templates/SFML/SFML App.xctemplate/ResourcePath.mm @@ -27,6 +27,7 @@ // Headers //////////////////////////////////////////////////////////// #include "ResourcePath.hpp" + #import #include @@ -36,15 +37,18 @@ std::filesystem::path resourcePath() NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; std::filesystem::path rpath; - NSBundle* bundle = [NSBundle mainBundle]; + NSBundle* bundle = [NSBundle mainBundle]; - if (bundle == nil) { + if (bundle == nil) + { #ifdef DEBUG NSLog(@"bundle is nil... thus no resources path can be found."); #endif - } else { + } + else + { NSString* path = [bundle resourcePath]; - rpath = [path UTF8String] + std::string("/"); + rpath = [path UTF8String] + std::string("/"); } [pool drain]; diff --git a/tools/xcode/templates/SFML/SFML App.xctemplate/main.cpp b/tools/xcode/templates/SFML/SFML App.xctemplate/main.cpp index b4d5875e4..75f58cd1f 100644 --- a/tools/xcode/templates/SFML/SFML App.xctemplate/main.cpp +++ b/tools/xcode/templates/SFML/SFML App.xctemplate/main.cpp @@ -27,21 +27,24 @@ int main(int, char const**) // Set the Icon sf::Image icon; - if (!icon.loadFromFile(resourcePath() + "icon.png")) { + if (!icon.loadFromFile(resourcePath() + "icon.png")) + { return EXIT_FAILURE; } window.setIcon(icon.getSize().x, icon.getSize().y, icon.getPixelsPtr()); // Load a sprite to display sf::Texture texture; - if (!texture.loadFromFile(resourcePath() + "background.jpg")) { + if (!texture.loadFromFile(resourcePath() + "background.jpg")) + { return EXIT_FAILURE; } sf::Sprite sprite(texture); // Create a graphical text to display sf::Font font; - if (!font.loadFromFile(resourcePath() + "tuffy.ttf")) { + if (!font.loadFromFile(resourcePath() + "tuffy.ttf")) + { return EXIT_FAILURE; } sf::Text text("Hello SFML", font, 50); @@ -49,7 +52,8 @@ int main(int, char const**) // Load a music to play sf::Music music; - if (!music.openFromFile(resourcePath() + "doodle_pop.ogg")) { + if (!music.openFromFile(resourcePath() + "doodle_pop.ogg")) + { return EXIT_FAILURE; } @@ -63,12 +67,14 @@ int main(int, char const**) for (sf::Event event; window.pollEvent(event);) { // Close window: exit - if (event.type == sf::Event::Closed) { + if (event.type == sf::Event::Closed) + { window.close(); } // Escape pressed: exit - if (event.type == sf::Event::KeyPressed && event.key.code == sf::Keyboard::Escape) { + if (event.type == sf::Event::KeyPressed && event.key.code == sf::Keyboard::Escape) + { window.close(); } } diff --git a/tools/xcode/templates/SFML/SFML CLT.xctemplate/main.cpp b/tools/xcode/templates/SFML/SFML CLT.xctemplate/main.cpp index 1eb6feaf6..ab05f5fd2 100644 --- a/tools/xcode/templates/SFML/SFML CLT.xctemplate/main.cpp +++ b/tools/xcode/templates/SFML/SFML CLT.xctemplate/main.cpp @@ -25,21 +25,24 @@ int main(int argc, char const** argv) // Set the Icon sf::Image icon; - if (!icon.loadFromFile("icon.png")) { + if (!icon.loadFromFile("icon.png")) + { return EXIT_FAILURE; } window.setIcon(icon.getSize().x, icon.getSize().y, icon.getPixelsPtr()); // Load a sprite to display sf::Texture texture; - if (!texture.loadFromFile("background.jpg")) { + if (!texture.loadFromFile("background.jpg")) + { return EXIT_FAILURE; } sf::Sprite sprite(texture); // Create a graphical text to display sf::Font font; - if (!font.loadFromFile("tuffy.ttf")) { + if (!font.loadFromFile("tuffy.ttf")) + { return EXIT_FAILURE; } sf::Text text("Hello SFML", font, 50); @@ -47,7 +50,8 @@ int main(int argc, char const** argv) // Load a music to play sf::Music music; - if (!music.openFromFile("doodle_pop.ogg")) { + if (!music.openFromFile("doodle_pop.ogg")) + { return EXIT_FAILURE; } @@ -61,12 +65,14 @@ int main(int argc, char const** argv) for (sf::Event event; window.pollEvent(event);) { // Close window: exit - if (event.type == sf::Event::Closed) { + if (event.type == sf::Event::Closed) + { window.close(); } // Escape pressed: exit - if (event.type == sf::Event::KeyPressed && event.key.code == sf::Keyboard::Escape) { + if (event.type == sf::Event::KeyPressed && event.key.code == sf::Keyboard::Escape) + { window.close(); } }