From fb1cfdc48d37dbb6ce383311ae5805c1f98db5d1 Mon Sep 17 00:00:00 2001 From: Chris Thrasher Date: Tue, 14 Feb 2023 20:42:12 -0700 Subject: [PATCH] Add `misc-const-correctness` clang-tidy check --- .clang-tidy | 1 - examples/ftp/Ftp.cpp | 10 +-- examples/island/Island.cpp | 56 +++++++------- examples/opengl/OpenGL.cpp | 14 ++-- examples/shader/Shader.cpp | 18 ++--- examples/tennis/Tennis.cpp | 14 ++-- examples/voip/Server.cpp | 8 +- examples/vulkan/Vulkan.cpp | 50 ++++++------ examples/win32/Win32.cpp | 4 +- examples/window/Window.cpp | 6 +- include/SFML/Graphics/Transform.inl | 24 +++--- include/SFML/System/Utf.inl | 10 +-- src/SFML/Audio/ALCheck.cpp | 2 +- src/SFML/Audio/AlResource.cpp | 4 +- src/SFML/Audio/Music.cpp | 18 ++--- src/SFML/Audio/SoundBuffer.cpp | 12 +-- src/SFML/Audio/SoundFileReaderFlac.cpp | 14 ++-- src/SFML/Audio/SoundFileReaderMp3.cpp | 4 +- src/SFML/Audio/SoundFileReaderOgg.cpp | 8 +- src/SFML/Audio/SoundFileReaderWav.cpp | 4 +- src/SFML/Audio/SoundFileWriterFlac.cpp | 2 +- src/SFML/Audio/SoundFileWriterWav.cpp | 14 ++-- src/SFML/Audio/SoundRecorder.cpp | 4 +- src/SFML/Audio/SoundStream.cpp | 32 ++++---- src/SFML/Graphics/CircleShape.cpp | 2 +- src/SFML/Graphics/Font.cpp | 50 ++++++------ src/SFML/Graphics/GLCheck.cpp | 2 +- src/SFML/Graphics/Image.cpp | 10 +-- src/SFML/Graphics/ImageLoader.cpp | 4 +- src/SFML/Graphics/RenderTarget.cpp | 46 +++++------ .../Graphics/RenderTextureImplDefault.cpp | 2 +- src/SFML/Graphics/RenderTextureImplFBO.cpp | 40 +++++----- src/SFML/Graphics/Shader.cpp | 76 +++++++++---------- src/SFML/Graphics/Shape.cpp | 29 +++---- src/SFML/Graphics/Sprite.cpp | 16 ++-- src/SFML/Graphics/Text.cpp | 70 ++++++++--------- src/SFML/Graphics/Texture.cpp | 68 ++++++++--------- src/SFML/Graphics/Transform.cpp | 24 +++--- src/SFML/Graphics/Transformable.cpp | 18 ++--- src/SFML/Graphics/VertexArray.cpp | 2 +- src/SFML/Graphics/VertexBuffer.cpp | 12 +-- src/SFML/Graphics/View.cpp | 18 ++--- src/SFML/Network/Ftp.cpp | 16 ++-- src/SFML/Network/Http.cpp | 14 ++-- src/SFML/Network/IpAddress.cpp | 8 +- src/SFML/Network/Packet.cpp | 16 ++-- src/SFML/Network/Socket.cpp | 2 +- src/SFML/Network/SocketSelector.cpp | 8 +- src/SFML/Network/TcpListener.cpp | 2 +- src/SFML/Network/TcpSocket.cpp | 22 +++--- src/SFML/Network/UdpSocket.cpp | 8 +- src/SFML/Network/Unix/SocketImpl.cpp | 2 +- src/SFML/System/Err.cpp | 2 +- src/SFML/System/FileInputStream.cpp | 4 +- src/SFML/System/MemoryInputStream.cpp | 4 +- src/SFML/System/String.cpp | 10 +-- src/SFML/Window/Context.cpp | 2 +- src/SFML/Window/GlContext.cpp | 26 +++---- src/SFML/Window/OSX/ClipboardImpl.mm | 19 +++-- src/SFML/Window/OSX/CursorImpl.mm | 14 ++-- src/SFML/Window/OSX/HIDInputManager.mm | 38 +++++----- src/SFML/Window/OSX/InputImpl.mm | 42 +++++----- src/SFML/Window/OSX/JoystickImpl.cpp | 58 +++++++------- src/SFML/Window/OSX/SFContext.mm | 28 +++---- .../Window/OSX/SFKeyboardModifiersHelper.mm | 6 +- src/SFML/Window/OSX/VideoModeImpl.cpp | 8 +- src/SFML/Window/OSX/WindowImplCocoa.mm | 60 +++++++-------- src/SFML/Window/OSX/cpp_objc_conversion.mm | 6 +- src/SFML/Window/Win32/ClipboardImpl.cpp | 4 +- src/SFML/Window/Win32/InputImpl.cpp | 20 ++--- src/SFML/Window/Win32/JoystickImpl.cpp | 42 +++++----- src/SFML/Window/Win32/VideoModeImpl.cpp | 2 +- src/SFML/Window/Win32/WglContext.cpp | 40 +++++----- src/SFML/Window/Win32/WindowImplWin32.cpp | 18 ++--- src/SFML/Window/WindowImpl.cpp | 22 +++--- test/Graphics/Image.test.cpp | 4 +- test/Graphics/Rect.test.cpp | 16 ++-- test/Graphics/Texture.test.cpp | 6 +- test/System/Err.test.cpp | 2 +- test/System/FileInputStream.test.cpp | 2 +- test/Window/Window.test.cpp | 5 +- test/install/Install.cpp | 40 +++++----- 82 files changed, 739 insertions(+), 731 deletions(-) diff --git a/.clang-tidy b/.clang-tidy index 819e31d4..e5292892 100644 --- a/.clang-tidy +++ b/.clang-tidy @@ -24,7 +24,6 @@ Checks: > -clang-analyzer-optin.osx.*, -clang-analyzer-osx.*, -clang-analyzer-unix.Malloc, - -misc-const-correctness, -misc-misplaced-const, -misc-no-recursion, -misc-non-private-member-variables-in-classes, diff --git a/examples/ftp/Ftp.cpp b/examples/ftp/Ftp.cpp index f49ea6df..6eb5786a 100644 --- a/examples/ftp/Ftp.cpp +++ b/examples/ftp/Ftp.cpp @@ -36,8 +36,8 @@ int main() } while (!address.has_value()); // Connect to the server - sf::Ftp server; - sf::Ftp::Response connectResponse = server.connect(address.value()); + sf::Ftp server; + const sf::Ftp::Response connectResponse = server.connect(address.value()); std::cout << connectResponse << std::endl; if (!connectResponse.isOk()) return EXIT_FAILURE; @@ -51,7 +51,7 @@ int main() std::cin >> password; // Login to the server - sf::Ftp::Response loginResponse = server.login(user, password); + const sf::Ftp::Response loginResponse = server.login(user, password); std::cout << loginResponse << std::endl; if (!loginResponse.isOk()) return EXIT_FAILURE; @@ -93,7 +93,7 @@ int main() case 1: { // Print the current server directory - sf::Ftp::DirectoryResponse response = server.getWorkingDirectory(); + const sf::Ftp::DirectoryResponse response = server.getWorkingDirectory(); std::cout << response << '\n' << "Current directory is " << response.getDirectory() << std::endl; break; } @@ -101,7 +101,7 @@ int main() case 2: { // Print the contents of the current server directory - sf::Ftp::ListingResponse response = server.getDirectoryListing(); + const sf::Ftp::ListingResponse response = server.getDirectoryListing(); std::cout << response << '\n'; for (const std::string& name : response.getListing()) std::cout << name << '\n'; diff --git a/examples/island/Island.cpp b/examples/island/Island.cpp index 368c4d6e..46ebb601 100644 --- a/examples/island/Island.cpp +++ b/examples/island/Island.cpp @@ -96,11 +96,11 @@ int main() return EXIT_FAILURE; // Create all of our graphics resources - sf::Text hudText(font); - sf::Text statusText(font); - sf::Shader terrainShader; - sf::RenderStates terrainStates(&terrainShader); - sf::VertexBuffer terrain(sf::PrimitiveType::Triangles, sf::VertexBuffer::Static); + sf::Text hudText(font); + sf::Text statusText(font); + sf::Shader terrainShader; + const sf::RenderStates terrainStates(&terrainShader); + sf::VertexBuffer terrain(sf::PrimitiveType::Triangles, sf::VertexBuffer::Static); // Set up our text drawables statusText.setCharacterSize(28); @@ -223,7 +223,7 @@ int main() if (prerequisitesSupported) { { - std::lock_guard lock(workQueueMutex); + const std::lock_guard lock(workQueueMutex); // Don't bother updating/drawing the VertexBuffer while terrain is being regenerated if (!pendingWorkCount) @@ -266,7 +266,7 @@ int main() // Shut down our thread pool { - std::lock_guard lock(workQueueMutex); + const std::lock_guard lock(workQueueMutex); workPending = false; } @@ -302,9 +302,9 @@ float getElevation(float x, float y) 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::clamp(elevation, 0.0f, 1.0f); + const float distance = 2.0f * std::sqrt(x * x + y * y); + elevation = (elevation + heightBase) * (1.0f - edgeFactor * std::pow(distance, edgeDropoffExponent)); + elevation = std::clamp(elevation, 0.0f, 1.0f); return elevation; } @@ -324,7 +324,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); + const 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; } @@ -369,14 +369,14 @@ sf::Color getLowlandsTerrainColor(float moisture) //////////////////////////////////////////////////////////// sf::Color getHighlandsTerrainColor(float elevation, float moisture) { - sf::Color lowlandsColor = getLowlandsTerrainColor(moisture); + const 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)); - float factor = std::min((elevation - 0.4f) / 0.1f, 1.f); + const float factor = std::min((elevation - 0.4f) / 0.1f, 1.f); color.r = static_cast(lowlandsColor.r * (1.f - factor) + color.r * factor); color.g = static_cast(lowlandsColor.g * (1.f - factor) + color.g * factor); @@ -393,11 +393,11 @@ sf::Color getHighlandsTerrainColor(float elevation, float moisture) //////////////////////////////////////////////////////////// sf::Color getSnowcapTerrainColor(float elevation, float moisture) { - sf::Color highlandsColor = getHighlandsTerrainColor(elevation, moisture); + const sf::Color highlandsColor = getHighlandsTerrainColor(elevation, moisture); sf::Color color = sf::Color::White; - float factor = std::min((elevation - snowcapHeight) / 0.05f, 1.f); + const float factor = std::min((elevation - snowcapHeight) / 0.05f, 1.f); color.r = static_cast(highlandsColor.r * (1.f - factor) + color.r * factor); color.g = static_cast(highlandsColor.g * (1.f - factor) + color.g * factor); @@ -440,8 +440,8 @@ sf::Color getTerrainColor(float elevation, float moisture) //////////////////////////////////////////////////////////// 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); + const sf::Vector3f deltaX(1, 0, (std::pow(right, heightFlatten) - std::pow(left, heightFlatten)) * heightFactor); + const 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, @@ -463,14 +463,14 @@ 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; + const unsigned int rowBlockSize = (resolutionY / blockCount) + 1; + const unsigned int rowStart = rowBlockSize * workItem.index; if (rowStart >= resolutionY) return; - unsigned int rowEnd = std::min(rowStart + rowBlockSize, resolutionY); - unsigned int rowCount = rowEnd - rowStart; + const unsigned int rowEnd = std::min(rowStart + rowBlockSize, resolutionY); + const unsigned int rowCount = rowEnd - rowStart; const float scalingFactorX = static_cast(windowWidth) / static_cast(resolutionX); const float scalingFactorY = static_cast(windowHeight) / static_cast(resolutionY); @@ -479,7 +479,7 @@ void processWorkItem(std::vector& vertices, const WorkItem& workItem { for (unsigned int x = 0; x < resolutionX; ++x) { - unsigned int arrayIndexBase = ((y - rowStart) * resolutionX + x) * 6; + const unsigned int arrayIndexBase = ((y - rowStart) * resolutionX + x) * 6; // Top left corner (first triangle) if (x > 0) @@ -565,7 +565,7 @@ void processWorkItem(std::vector& vertices, const WorkItem& workItem //////////////////////////////////////////////////////////// void threadFunction() { - unsigned int rowBlockSize = (resolutionY / blockCount) + 1; + const unsigned int rowBlockSize = (resolutionY / blockCount) + 1; std::vector vertices(resolutionX * rowBlockSize * 6); @@ -578,7 +578,7 @@ void threadFunction() // Check if there are new work items in the queue { - std::lock_guard lock(workQueueMutex); + const std::lock_guard lock(workQueueMutex); if (!workPending) return; @@ -601,7 +601,7 @@ void threadFunction() processWorkItem(vertices, workItem); { - std::lock_guard lock(workQueueMutex); + const std::lock_guard lock(workQueueMutex); --pendingWorkCount; } @@ -623,7 +623,7 @@ void generateTerrain(sf::Vertex* buffer) for (;;) { { - std::lock_guard lock(workQueueMutex); + const std::lock_guard lock(workQueueMutex); if (workQueue.empty()) break; @@ -634,11 +634,11 @@ void generateTerrain(sf::Vertex* buffer) // Queue all the new work items { - std::lock_guard lock(workQueueMutex); + const std::lock_guard lock(workQueueMutex); for (unsigned int i = 0; i < blockCount; ++i) { - WorkItem workItem = {buffer, i}; + const WorkItem workItem = {buffer, i}; workQueue.push_back(workItem); } diff --git a/examples/opengl/OpenGL.cpp b/examples/opengl/OpenGL.cpp index 340749f1..7c4f1d54 100644 --- a/examples/opengl/OpenGL.cpp +++ b/examples/opengl/OpenGL.cpp @@ -56,7 +56,7 @@ int main() backgroundTexture.setSrgb(sRgb); if (!backgroundTexture.loadFromFile(resourcesDir() / "background.jpg")) return EXIT_FAILURE; - sf::Sprite background(backgroundTexture); + const sf::Sprite background(backgroundTexture); // Create some text to draw on top of our OpenGL object sf::Font font; @@ -115,7 +115,7 @@ int main() // Setup a perspective projection glMatrixMode(GL_PROJECTION); glLoadIdentity(); - GLfloat ratio = static_cast(window.getSize().x) / static_cast(window.getSize().y); + const GLfloat ratio = static_cast(window.getSize().x) / static_cast(window.getSize().y); #ifdef SFML_OPENGL_ES glFrustumf(-ratio, ratio, -1.f, 1.f, 1.f, 500.f); #else @@ -193,7 +193,7 @@ int main() } // Create a clock for measuring the time elapsed - sf::Clock clock; + const sf::Clock clock; // Flag to track whether mipmapping is currently enabled bool mipmapEnabled = true; @@ -245,7 +245,7 @@ int main() // Adjust the viewport when the window is resized if (event.type == sf::Event::Resized) { - sf::Vector2u textureSize = backgroundTexture.getSize(); + const sf::Vector2u textureSize = backgroundTexture.getSize(); // Make the window the active window for OpenGL calls if (!window.setActive(true)) @@ -257,7 +257,7 @@ int main() glViewport(0, 0, static_cast(event.size.width), static_cast(event.size.height)); glMatrixMode(GL_PROJECTION); glLoadIdentity(); - GLfloat newRatio = static_cast(event.size.width) / static_cast(event.size.height); + const GLfloat newRatio = static_cast(event.size.width) / static_cast(event.size.height); #ifdef SFML_OPENGL_ES glFrustumf(-newRatio, newRatio, -1.f, 1.f, 1.f, 500.f); #else @@ -303,8 +303,8 @@ int main() pos = sf::Mouse::getPosition(window); #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; + const float x = static_cast(pos.x) * 200.f / static_cast(window.getSize().x) - 100.f; + const float y = -static_cast(pos.y) * 200.f / static_cast(window.getSize().y) + 100.f; // Apply some transformations glMatrixMode(GL_MODELVIEW); diff --git a/examples/shader/Shader.cpp b/examples/shader/Shader.cpp index 210254c1..01c8d4d9 100644 --- a/examples/shader/Shader.cpp +++ b/examples/shader/Shader.cpp @@ -139,11 +139,11 @@ public: m_points.setPrimitiveType(sf::PrimitiveType::Points); for (int i = 0; i < 40000; ++i) { - auto x = xDistribution(rng); - auto y = yDistribution(rng); - auto r = static_cast(colorDistribution(rng)); - auto g = static_cast(colorDistribution(rng)); - auto b = static_cast(colorDistribution(rng)); + const auto x = xDistribution(rng); + const auto y = yDistribution(rng); + const auto r = static_cast(colorDistribution(rng)); + const auto g = static_cast(colorDistribution(rng)); + const auto b = static_cast(colorDistribution(rng)); m_points.append(sf::Vertex(sf::Vector2f(x, y), sf::Color(r, g, b))); } @@ -153,7 +153,7 @@ public: void onUpdate(float time, float x, float y) override { - float radius = 200 + std::cos(time) * 150; + const float radius = 200 + std::cos(time) * 150; m_shader.setUniform("storm_position", sf::Vector2f(x * 800, y * 600)); m_shader.setUniform("storm_inner_radius", radius / 3); m_shader.setUniform("storm_total_radius", radius); @@ -205,7 +205,7 @@ public: // Load the moving entities for (int i = 0; i < 6; ++i) { - sf::Sprite entity(m_entityTexture, sf::IntRect({96 * i, 0}, {96, 96})); + const sf::Sprite entity(m_entityTexture, sf::IntRect({96 * i, 0}, {96, 96})); m_entities.push_back(entity); } @@ -308,7 +308,7 @@ public: m_transform.rotate(sf::degrees(x * 360.f)); // Adjust billboard size to scale between 25 and 75 - float size = 25 + std::abs(y) * 50; + const float size = 25 + std::abs(y) * 50; // Update the shader parameter m_shader.setUniform("size", sf::Vector2f(size, size)); @@ -387,7 +387,7 @@ int main() instructions.setFillColor(sf::Color(80, 80, 80)); // Start the game loop - sf::Clock clock; + const sf::Clock clock; while (window.isOpen()) { // Process events diff --git a/examples/tennis/Tennis.cpp b/examples/tennis/Tennis.cpp index 44869b95..32791dc7 100644 --- a/examples/tennis/Tennis.cpp +++ b/examples/tennis/Tennis.cpp @@ -33,10 +33,10 @@ int main() std::mt19937 rng(rd()); // Define some constants - const float gameWidth = 800; - const float gameHeight = 600; - sf::Vector2f paddleSize(25, 100); - float ballRadius = 10.f; + const float gameWidth = 800; + const float gameHeight = 600; + const sf::Vector2f paddleSize(25, 100); + const float ballRadius = 10.f; // Create the window of the application sf::RenderWindow window(sf::VideoMode({static_cast(gameWidth), static_cast(gameHeight)}, 32), @@ -157,7 +157,7 @@ int main() if (isPlaying) { - float deltaTime = clock.restart().asSeconds(); + const 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)) @@ -172,8 +172,8 @@ int main() if (sf::Touch::isDown(0)) { - sf::Vector2i pos = sf::Touch::getPosition(0); - sf::Vector2f mappedPos = window.mapPixelToCoords(pos); + const sf::Vector2i pos = sf::Touch::getPosition(0); + const sf::Vector2f mappedPos = window.mapPixelToCoords(pos); leftPaddle.setPosition({leftPaddle.getPosition().x, mappedPos.y}); } diff --git a/examples/voip/Server.cpp b/examples/voip/Server.cpp index 6893a402..5410fb32 100644 --- a/examples/voip/Server.cpp +++ b/examples/voip/Server.cpp @@ -83,7 +83,7 @@ private: // Copy samples into a local buffer to avoid synchronization problems // (don't forget that we run in two separate threads) { - std::lock_guard lock(m_mutex); + const std::lock_guard lock(m_mutex); m_tempBuffer.assign(m_samples.begin() + static_cast::difference_type>(m_offset), m_samples.end()); } @@ -127,13 +127,13 @@ private: if (id == serverAudioData) { // Extract audio samples from the packet, and append it to our samples buffer - std::size_t sampleCount = (packet.getDataSize() - 1) / sizeof(std::int16_t); + const std::size_t sampleCount = (packet.getDataSize() - 1) / sizeof(std::int16_t); // Don't forget that the other thread can access the sample array at any time // (so we protect any operation on it with the mutex) { - std::lock_guard lock(m_mutex); - std::size_t oldSize = m_samples.size(); + const std::lock_guard lock(m_mutex); + const std::size_t oldSize = m_samples.size(); m_samples.resize(oldSize + sampleCount); std::memcpy(&(m_samples[oldSize]), static_cast(packet.getData()) + 1, diff --git a/examples/vulkan/Vulkan.cpp b/examples/vulkan/Vulkan.cpp index c0e136ab..51bd4bc8 100644 --- a/examples/vulkan/Vulkan.cpp +++ b/examples/vulkan/Vulkan.cpp @@ -46,10 +46,10 @@ void matrixMultiply(Matrix& result, const Matrix& left, const Matrix& right) // Rotate a matrix around the x-axis void matrixRotateX(Matrix& result, sf::Angle angle) { - float rad = angle.asRadians(); + const float rad = angle.asRadians(); // clang-format off - Matrix matrix = { + const 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}, @@ -63,10 +63,10 @@ void matrixRotateX(Matrix& result, sf::Angle angle) // Rotate a matrix around the y-axis void matrixRotateY(Matrix& result, sf::Angle angle) { - float rad = angle.asRadians(); + const float rad = angle.asRadians(); // clang-format off - Matrix matrix = { + const 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}, @@ -80,10 +80,10 @@ void matrixRotateY(Matrix& result, sf::Angle angle) // Rotate a matrix around the z-axis void matrixRotateZ(Matrix& result, sf::Angle angle) { - float rad = angle.asRadians(); + const float rad = angle.asRadians(); // clang-format off - Matrix matrix = { + const 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}, @@ -711,7 +711,7 @@ public: return; } - float queuePriority = 1.0f; + const float queuePriority = 1.0f; VkDeviceQueueCreateInfo deviceQueueCreateInfo = VkDeviceQueueCreateInfo(); deviceQueueCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO; @@ -774,7 +774,7 @@ public: } else if (!surfaceFormats.empty()) { - for (VkSurfaceFormatKHR& surfaceFormat : surfaceFormats) + for (const VkSurfaceFormatKHR& surfaceFormat : surfaceFormats) { if ((surfaceFormat.format == VK_FORMAT_B8G8R8A8_UNORM) && (surfaceFormat.colorSpace == VK_COLOR_SPACE_SRGB_NONLINEAR_KHR)) @@ -815,7 +815,7 @@ public: // Prefer mailbox over FIFO if it is available VkPresentModeKHR presentMode = VK_PRESENT_MODE_FIFO_KHR; - for (VkPresentModeKHR& i : presentModes) + for (const VkPresentModeKHR& i : presentModes) { if (i == VK_PRESENT_MODE_MAILBOX_KHR) { @@ -840,7 +840,7 @@ public: surfaceCapabilities.minImageExtent.height, surfaceCapabilities.maxImageExtent.height); - auto imageCount = std::clamp(2u, surfaceCapabilities.minImageCount, surfaceCapabilities.maxImageCount); + const auto imageCount = std::clamp(2u, surfaceCapabilities.minImageCount, surfaceCapabilities.maxImageCount); VkSwapchainCreateInfoKHR swapchainCreateInfo = VkSwapchainCreateInfoKHR(); swapchainCreateInfo.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR; @@ -1809,7 +1809,7 @@ public: } // Create a staging buffer to transfer the data with - VkDeviceSize imageSize = imageData.getSize().x * imageData.getSize().y * 4; + const VkDeviceSize imageSize = imageData.getSize().x * imageData.getSize().y * 4; VkBuffer stagingBuffer = {}; VkDeviceMemory stagingBufferMemory = {}; @@ -2305,7 +2305,7 @@ public: vkCmdBindPipeline(commandBuffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, graphicsPipeline); // Bind our vertex buffer - VkDeviceSize offset = 0; + const VkDeviceSize offset = 0; vkCmdBindVertexBuffers(commandBuffers[i], 0, 1, &vertexBuffer, &offset); @@ -2403,10 +2403,10 @@ public: matrixRotateZ(model, sf::degrees(elapsed * 109.0f)); // 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 = std::clamp(mousePosition.x * 2.f / windowSize.x - 1.f, -1.0f, 1.0f) * 2.0f; - float y = std::clamp(-mousePosition.y * 2.f / windowSize.y + 1.f, -1.0f, 1.0f) * 1.5f; + const sf::Vector2f mousePosition = sf::Vector2f(sf::Mouse::getPosition(window)); + const sf::Vector2f windowSize = sf::Vector2f(window.getSize()); + const float x = std::clamp(mousePosition.x * 2.f / windowSize.x - 1.f, -1.0f, 1.0f) * 2.0f; + const float y = std::clamp(-mousePosition.y * 2.f / windowSize.y + 1.f, -1.0f, 1.0f) * 1.5f; model[3][0] -= x; model[3][2] += y; @@ -2458,12 +2458,12 @@ public: { // Get the next image in the swapchain - VkResult result = vkAcquireNextImageKHR(device, - swapchain, - std::numeric_limits::max(), - imageAvailableSemaphores[currentFrame], - VK_NULL_HANDLE, - &imageIndex); + const 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) @@ -2482,7 +2482,7 @@ public: } // Wait for the swapchain image to be available in the color attachment stage before submitting the queue - VkPipelineStageFlags waitStages = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; + const VkPipelineStageFlags waitStages = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; // Signal the render finished semaphore once the queue has been processed VkSubmitInfo submitInfo = VkSubmitInfo(); @@ -2514,7 +2514,7 @@ public: { // Queue presentation - VkResult result = vkQueuePresentKHR(queue, &presentInfo); + const VkResult result = vkQueuePresentKHR(queue, &presentInfo); // Check if we need to re-create the swapchain (e.g. if the window was resized) if ((result == VK_ERROR_OUT_OF_DATE_KHR) || (result == VK_SUBOPTIMAL_KHR) || swapchainOutOfDate) @@ -2535,7 +2535,7 @@ public: void run() { - sf::Clock clock; + const sf::Clock clock; // Start game loop while (window.isOpen()) diff --git a/examples/win32/Win32.cpp b/examples/win32/Win32.cpp index dcd96ae3..2768671c 100644 --- a/examples/win32/Win32.cpp +++ b/examples/win32/Win32.cpp @@ -122,7 +122,7 @@ int main() sprite1.setPosition(sprite1.getOrigin()); // Create a clock for measuring elapsed time - sf::Clock clock; + const sf::Clock clock; // Loop until a WM_QUIT message is received MSG message; @@ -137,7 +137,7 @@ int main() } else { - float time = clock.getElapsedTime().asSeconds(); + const float time = clock.getElapsedTime().asSeconds(); // Clear views sfmlView1.clear(); diff --git a/examples/window/Window.cpp b/examples/window/Window.cpp index 98bd3a7b..ce8c5ff7 100644 --- a/examples/window/Window.cpp +++ b/examples/window/Window.cpp @@ -68,7 +68,7 @@ int main() // Setup a perspective projection glMatrixMode(GL_PROJECTION); glLoadIdentity(); - GLfloat ratio = static_cast(window.getSize().x) / static_cast(window.getSize().y); + const GLfloat ratio = static_cast(window.getSize().x) / static_cast(window.getSize().y); #ifdef SFML_OPENGL_ES glFrustumf(-ratio, ratio, -1.f, 1.f, 1.f, 500.f); #else @@ -135,7 +135,7 @@ int main() glDisableClientState(GL_TEXTURE_COORD_ARRAY); // Create a clock for measuring the time elapsed - sf::Clock clock; + const sf::Clock clock; // Start the game loop while (window.isOpen()) @@ -157,7 +157,7 @@ int main() glViewport(0, 0, static_cast(event.size.width), static_cast(event.size.height)); glMatrixMode(GL_PROJECTION); glLoadIdentity(); - GLfloat newRatio = static_cast(event.size.width) / static_cast(event.size.height); + const GLfloat newRatio = static_cast(event.size.width) / static_cast(event.size.height); #ifdef SFML_OPENGL_ES glFrustumf(-newRatio, newRatio, -1.f, 1.f, 1.f, 500.f); #else diff --git a/include/SFML/Graphics/Transform.inl b/include/SFML/Graphics/Transform.inl index ffc936a0..80a71eb0 100644 --- a/include/SFML/Graphics/Transform.inl +++ b/include/SFML/Graphics/Transform.inl @@ -53,9 +53,9 @@ constexpr Transform Transform::getInverse() const { // clang-format off // Compute the determinant - float det = m_matrix[0] * (m_matrix[15] * m_matrix[5] - m_matrix[7] * m_matrix[13]) - - m_matrix[1] * (m_matrix[15] * m_matrix[4] - m_matrix[7] * m_matrix[12]) + - m_matrix[3] * (m_matrix[13] * m_matrix[4] - m_matrix[5] * m_matrix[12]); + const float det = m_matrix[0] * (m_matrix[15] * m_matrix[5] - m_matrix[7] * m_matrix[13]) - + m_matrix[1] * (m_matrix[15] * m_matrix[4] - m_matrix[7] * m_matrix[12]) + + m_matrix[3] * (m_matrix[13] * m_matrix[4] - m_matrix[5] * m_matrix[12]); // clang-format on // Compute the inverse if the determinant is not zero @@ -145,9 +145,9 @@ constexpr Transform& Transform::combine(const Transform& transform) constexpr Transform& Transform::translate(const Vector2f& offset) { // clang-format off - Transform translation(1, 0, offset.x, - 0, 1, offset.y, - 0, 0, 1); + const Transform translation(1, 0, offset.x, + 0, 1, offset.y, + 0, 0, 1); // clang-format on return combine(translation); @@ -158,9 +158,9 @@ constexpr Transform& Transform::translate(const Vector2f& offset) constexpr Transform& Transform::scale(const Vector2f& factors) { // clang-format off - Transform scaling(factors.x, 0, 0, - 0, factors.y, 0, - 0, 0, 1); + const Transform scaling(factors.x, 0, 0, + 0, factors.y, 0, + 0, 0, 1); // clang-format on return combine(scaling); @@ -171,9 +171,9 @@ constexpr Transform& Transform::scale(const Vector2f& factors) constexpr Transform& Transform::scale(const Vector2f& factors, const Vector2f& center) { // clang-format off - Transform scaling(factors.x, 0, center.x * (1 - factors.x), - 0, factors.y, center.y * (1 - factors.y), - 0, 0, 1); + const Transform scaling(factors.x, 0, center.x * (1 - factors.x), + 0, factors.y, center.y * (1 - factors.y), + 0, 0, 1); // clang-format on return combine(scaling); diff --git a/include/SFML/System/Utf.inl b/include/SFML/System/Utf.inl index d72931af..4c38530b 100644 --- a/include/SFML/System/Utf.inl +++ b/include/SFML/System/Utf.inl @@ -68,7 +68,7 @@ In Utf<8>::decode(In begin, In end, std::uint32_t& output, std::uint32_t replace // clang-format on // decode the character - int trailingBytes = trailing[static_cast(*begin)]; + const int trailingBytes = trailing[static_cast(*begin)]; if (trailingBytes < std::distance(begin, end)) { output = 0; @@ -177,8 +177,8 @@ Out Utf<8>::fromAnsi(In begin, In end, Out output, const std::locale& locale) { while (begin < end) { - std::uint32_t codepoint = Utf<32>::decodeAnsi(*begin++, locale); - output = encode(codepoint, output); + const std::uint32_t codepoint = Utf<32>::decodeAnsi(*begin++, locale); + output = encode(codepoint, output); } return output; @@ -301,14 +301,14 @@ Out Utf<8>::toUtf32(In begin, In end, Out output) template In Utf<16>::decode(In begin, In end, std::uint32_t& output, std::uint32_t replacement) { - std::uint16_t first = *begin++; + const std::uint16_t first = *begin++; // If it's a surrogate pair, first convert to a single UTF-32 character if ((first >= 0xD800) && (first <= 0xDBFF)) { if (begin < end) { - std::uint32_t second = *begin++; + const std::uint32_t second = *begin++; if ((second >= 0xDC00) && (second <= 0xDFFF)) { // The second element is valid: convert the two elements to a UTF-32 character diff --git a/src/SFML/Audio/ALCheck.cpp b/src/SFML/Audio/ALCheck.cpp index d816ef3a..30790f95 100644 --- a/src/SFML/Audio/ALCheck.cpp +++ b/src/SFML/Audio/ALCheck.cpp @@ -52,7 +52,7 @@ namespace sf::priv void alCheckError(const std::filesystem::path& file, unsigned int line, std::string_view expression) { // Get the last error - ALenum errorCode = alGetError(); + const ALenum errorCode = alGetError(); if (errorCode != AL_NO_ERROR) { diff --git a/src/SFML/Audio/AlResource.cpp b/src/SFML/Audio/AlResource.cpp index 2004265a..3d386314 100644 --- a/src/SFML/Audio/AlResource.cpp +++ b/src/SFML/Audio/AlResource.cpp @@ -51,7 +51,7 @@ namespace sf AlResource::AlResource() { // Protect from concurrent access - std::lock_guard lock(mutex); + const std::lock_guard lock(mutex); // If this is the very first resource, trigger the global device initialization if (count == 0) @@ -66,7 +66,7 @@ AlResource::AlResource() AlResource::~AlResource() { // Protect from concurrent access - std::lock_guard lock(mutex); + const std::lock_guard lock(mutex); // Decrement the resources counter --count; diff --git a/src/SFML/Audio/Music.cpp b/src/SFML/Audio/Music.cpp index 305e41d3..e3bb117f 100644 --- a/src/SFML/Audio/Music.cpp +++ b/src/SFML/Audio/Music.cpp @@ -155,8 +155,8 @@ void Music::setLoopPoints(TimeSpan timePoints) // When we apply this change, we need to "reset" this instance and its buffer // Get old playing status and position - Status oldStatus = getStatus(); - Time oldPos = getPlayingOffset(); + const Status oldStatus = getStatus(); + const Time oldPos = getPlayingOffset(); // Unload stop(); @@ -177,11 +177,11 @@ void Music::setLoopPoints(TimeSpan timePoints) //////////////////////////////////////////////////////////// bool Music::onGetData(SoundStream::Chunk& data) { - std::lock_guard lock(m_mutex); + const std::lock_guard lock(m_mutex); - std::size_t toFill = m_samples.size(); - std::uint64_t currentOffset = m_file.getSampleOffset(); - std::uint64_t loopEnd = m_loopSpan.offset + m_loopSpan.length; + std::size_t toFill = m_samples.size(); + std::uint64_t currentOffset = m_file.getSampleOffset(); + const std::uint64_t 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, @@ -203,7 +203,7 @@ bool Music::onGetData(SoundStream::Chunk& data) //////////////////////////////////////////////////////////// void Music::onSeek(Time timeOffset) { - std::lock_guard lock(m_mutex); + const std::lock_guard lock(m_mutex); m_file.seek(timeOffset); } @@ -212,8 +212,8 @@ void Music::onSeek(Time timeOffset) std::int64_t Music::onLoop() { // Called by underlying SoundStream so we can determine where to loop. - std::lock_guard lock(m_mutex); - std::uint64_t currentOffset = m_file.getSampleOffset(); + const std::lock_guard lock(m_mutex); + const std::uint64_t 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/SoundBuffer.cpp b/src/SFML/Audio/SoundBuffer.cpp index c3accbaa..a2c87ab1 100644 --- a/src/SFML/Audio/SoundBuffer.cpp +++ b/src/SFML/Audio/SoundBuffer.cpp @@ -223,9 +223,9 @@ SoundBuffer& SoundBuffer::operator=(const SoundBuffer& right) bool SoundBuffer::initialize(InputSoundFile& file) { // Retrieve the sound parameters - std::uint64_t sampleCount = file.getSampleCount(); - unsigned int channelCount = file.getChannelCount(); - unsigned int sampleRate = file.getSampleRate(); + const std::uint64_t sampleCount = file.getSampleCount(); + const unsigned int channelCount = file.getChannelCount(); + const unsigned int sampleRate = file.getSampleRate(); // Read the samples from the provided file m_samples.resize(static_cast(sampleCount)); @@ -249,7 +249,7 @@ bool SoundBuffer::update(unsigned int channelCount, unsigned int sampleRate) return false; // Find the good format according to the number of channels - ALenum format = priv::AudioDevice::getFormatFromChannelCount(channelCount); + const ALenum format = priv::AudioDevice::getFormatFromChannelCount(channelCount); // Check if the format is valid if (format == 0) @@ -259,14 +259,14 @@ bool SoundBuffer::update(unsigned int channelCount, unsigned int sampleRate) } // First make a copy of the list of sounds so we can reattach later - SoundList sounds(m_sounds); + const SoundList sounds(m_sounds); // Detach the buffer from the sounds that use it (to avoid OpenAL errors) for (Sound* soundPtr : sounds) soundPtr->resetBuffer(); // Fill the buffer - auto size = static_cast(m_samples.size() * sizeof(std::int16_t)); + const auto size = static_cast(m_samples.size() * sizeof(std::int16_t)); alCheck(alBufferData(m_buffer, format, m_samples.data(), size, static_cast(sampleRate))); // Compute the duration diff --git a/src/SFML/Audio/SoundFileReaderFlac.cpp b/src/SFML/Audio/SoundFileReaderFlac.cpp index 226b6c5c..225bbf99 100644 --- a/src/SFML/Audio/SoundFileReaderFlac.cpp +++ b/src/SFML/Audio/SoundFileReaderFlac.cpp @@ -41,7 +41,7 @@ FLAC__StreamDecoderReadStatus streamRead(const FLAC__StreamDecoder*, FLAC__byte { auto* data = static_cast(clientData); - std::int64_t count = data->stream->read(buffer, static_cast(*bytes)); + const std::int64_t count = data->stream->read(buffer, static_cast(*bytes)); if (count > 0) { *bytes = static_cast(count); @@ -61,7 +61,7 @@ FLAC__StreamDecoderSeekStatus streamSeek(const FLAC__StreamDecoder*, FLAC__uint6 { auto* data = static_cast(clientData); - std::int64_t position = data->stream->seek(static_cast(absoluteByteOffset)); + const std::int64_t position = data->stream->seek(static_cast(absoluteByteOffset)); if (position >= 0) return FLAC__STREAM_DECODER_SEEK_STATUS_OK; else @@ -72,7 +72,7 @@ FLAC__StreamDecoderTellStatus streamTell(const FLAC__StreamDecoder*, FLAC__uint6 { auto* data = static_cast(clientData); - std::int64_t position = data->stream->tell(); + const std::int64_t position = data->stream->tell(); if (position >= 0) { *absoluteByteOffset = static_cast(position); @@ -88,7 +88,7 @@ FLAC__StreamDecoderLengthStatus streamLength(const FLAC__StreamDecoder*, FLAC__u { auto* data = static_cast(clientData); - std::int64_t count = data->stream->getSize(); + const std::int64_t count = data->stream->getSize(); if (count >= 0) { *streamLength = static_cast(count); @@ -115,7 +115,7 @@ FLAC__StreamDecoderWriteStatus streamWrite(const FLAC__StreamDecoder*, 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; + const unsigned int frameSamples = frame->header.blocksize * frame->header.channels; if (data->remaining < frameSamples) data->leftovers.reserve(static_cast(frameSamples - data->remaining)); @@ -208,7 +208,7 @@ bool SoundFileReaderFlac::check(InputStream& stream) &data); // Read the header - bool valid = FLAC__stream_decoder_process_until_end_of_metadata(decoder) != 0; + const bool valid = FLAC__stream_decoder_process_until_end_of_metadata(decoder) != 0; // Destroy the decoder FLAC__stream_decoder_finish(decoder); @@ -303,7 +303,7 @@ std::uint64_t SoundFileReaderFlac::read(std::int16_t* samples, std::uint64_t max assert(m_decoder); // If there are leftovers from previous call, use it first - std::size_t left = m_clientData.leftovers.size(); + const std::size_t left = m_clientData.leftovers.size(); if (left > 0) { if (left > maxCount) diff --git a/src/SFML/Audio/SoundFileReaderMp3.cpp b/src/SFML/Audio/SoundFileReaderMp3.cpp index b7c251ac..3f1c15db 100644 --- a/src/SFML/Audio/SoundFileReaderMp3.cpp +++ b/src/SFML/Audio/SoundFileReaderMp3.cpp @@ -69,8 +69,8 @@ std::size_t readCallback(void* ptr, std::size_t size, void* data) int seekCallback(std::uint64_t offset, void* data) { - auto* stream = static_cast(data); - std::int64_t position = stream->seek(static_cast(offset)); + auto* stream = static_cast(data); + const std::int64_t position = stream->seek(static_cast(offset)); return position < 0 ? -1 : 0; } diff --git a/src/SFML/Audio/SoundFileReaderOgg.cpp b/src/SFML/Audio/SoundFileReaderOgg.cpp index 70e5b63f..4f2bec30 100644 --- a/src/SFML/Audio/SoundFileReaderOgg.cpp +++ b/src/SFML/Audio/SoundFileReaderOgg.cpp @@ -105,7 +105,7 @@ SoundFileReaderOgg::~SoundFileReaderOgg() bool SoundFileReaderOgg::open(InputStream& stream, Info& info) { // Open the Vorbis stream - int status = ov_open_callbacks(&stream, &m_vorbis, nullptr, 0, callbacks); + const int status = ov_open_callbacks(&stream, &m_vorbis, nullptr, 0, callbacks); if (status < 0) { err() << "Failed to open Vorbis file for reading" << std::endl; @@ -143,11 +143,11 @@ std::uint64_t SoundFileReaderOgg::read(std::int16_t* samples, std::uint64_t maxC std::uint64_t count = 0; while (count < maxCount) { - int bytesToRead = static_cast(maxCount - count) * static_cast(sizeof(std::int16_t)); - long bytesRead = ov_read(&m_vorbis, reinterpret_cast(samples), bytesToRead, 0, 2, 1, nullptr); + const int bytesToRead = static_cast(maxCount - count) * static_cast(sizeof(std::int16_t)); + const long bytesRead = ov_read(&m_vorbis, reinterpret_cast(samples), bytesToRead, 0, 2, 1, nullptr); if (bytesRead > 0) { - long samplesRead = bytesRead / static_cast(sizeof(std::int16_t)); + const long samplesRead = bytesRead / static_cast(sizeof(std::int16_t)); count += static_cast(samplesRead); samples += samplesRead; } diff --git a/src/SFML/Audio/SoundFileReaderWav.cpp b/src/SFML/Audio/SoundFileReaderWav.cpp index 5a2704a5..228e40f4 100644 --- a/src/SFML/Audio/SoundFileReaderWav.cpp +++ b/src/SFML/Audio/SoundFileReaderWav.cpp @@ -152,7 +152,7 @@ std::uint64_t SoundFileReaderWav::read(std::int16_t* samples, std::uint64_t maxC assert(m_stream); std::uint64_t count = 0; - auto startPos = static_cast(m_stream->tell()); + const 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. @@ -238,7 +238,7 @@ bool SoundFileReaderWav::parseHeader(Info& info) std::uint32_t subChunkSize = 0; if (!decode(*m_stream, subChunkSize)) return false; - std::int64_t subChunkStart = m_stream->tell(); + const std::int64_t subChunkStart = m_stream->tell(); if (subChunkStart == -1) return false; diff --git a/src/SFML/Audio/SoundFileWriterFlac.cpp b/src/SFML/Audio/SoundFileWriterFlac.cpp index d1bf8c0e..71ad764e 100644 --- a/src/SFML/Audio/SoundFileWriterFlac.cpp +++ b/src/SFML/Audio/SoundFileWriterFlac.cpp @@ -96,7 +96,7 @@ void SoundFileWriterFlac::write(const std::int16_t* samples, std::uint64_t count while (count > 0) { // Make sure that we don't process too many samples at once - unsigned int frames = std::min(static_cast(count / m_channelCount), 10000u); + const unsigned int frames = std::min(static_cast(count / m_channelCount), 10000u); // Convert the samples to 32-bits m_samples32.assign(samples, samples + frames * m_channelCount); diff --git a/src/SFML/Audio/SoundFileWriterWav.cpp b/src/SFML/Audio/SoundFileWriterWav.cpp index ef86b519..183e9a43 100644 --- a/src/SFML/Audio/SoundFileWriterWav.cpp +++ b/src/SFML/Audio/SoundFileWriterWav.cpp @@ -133,27 +133,27 @@ bool SoundFileWriterWav::writeHeader(unsigned int sampleRate, unsigned int chann // Write the sub-chunk 1 ("format") id and size char fmtChunkId[4] = {'f', 'm', 't', ' '}; m_file.write(fmtChunkId, sizeof(fmtChunkId)); - std::uint32_t fmtChunkSize = 16; + const std::uint32_t fmtChunkSize = 16; encode(m_file, fmtChunkSize); // Write the format (PCM) - std::uint16_t format = 1; + const std::uint16_t format = 1; encode(m_file, format); // Write the sound attributes encode(m_file, static_cast(channelCount)); encode(m_file, sampleRate); - std::uint32_t byteRate = sampleRate * channelCount * 2; + const std::uint32_t byteRate = sampleRate * channelCount * 2; encode(m_file, byteRate); - auto blockAlign = static_cast(channelCount * 2); + const auto blockAlign = static_cast(channelCount * 2); encode(m_file, blockAlign); - std::uint16_t bitsPerSample = 16; + const std::uint16_t bitsPerSample = 16; encode(m_file, bitsPerSample); // Write the sub-chunk 2 ("data") id and size char dataChunkId[4] = {'d', 'a', 't', 'a'}; m_file.write(dataChunkId, sizeof(dataChunkId)); - std::uint32_t dataChunkSize = 0; // placeholder, will be written later + const std::uint32_t dataChunkSize = 0; // placeholder, will be written later encode(m_file, dataChunkSize); return true; @@ -169,7 +169,7 @@ void SoundFileWriterWav::close() m_file.flush(); // Update the main chunk size and data sub-chunk size - std::uint32_t fileSize = static_cast(m_file.tellp()); + const std::uint32_t fileSize = static_cast(m_file.tellp()); m_file.seekp(4); encode(m_file, fileSize - 8); // 8 bytes RIFF header m_file.seekp(40); diff --git a/src/SFML/Audio/SoundRecorder.cpp b/src/SFML/Audio/SoundRecorder.cpp index 22c0cc5d..be5425e7 100644 --- a/src/SFML/Audio/SoundRecorder.cpp +++ b/src/SFML/Audio/SoundRecorder.cpp @@ -90,7 +90,7 @@ bool SoundRecorder::start(unsigned int sampleRate) } // Determine the recording format - ALCenum format = (m_channelCount == 1) ? AL_FORMAT_MONO16 : AL_FORMAT_STEREO16; + const ALCenum format = (m_channelCount == 1) ? AL_FORMAT_MONO16 : AL_FORMAT_STEREO16; // Open the capture device for capturing 16 bits samples captureDevice = alcCaptureOpenDevice(m_deviceName.c_str(), sampleRate, format, static_cast(sampleRate)); @@ -184,7 +184,7 @@ bool SoundRecorder::setDevice(const std::string& name) awaitCapturingThread(); // Determine the recording format - ALCenum format = (m_channelCount == 1) ? AL_FORMAT_MONO16 : AL_FORMAT_STEREO16; + const ALCenum format = (m_channelCount == 1) ? AL_FORMAT_MONO16 : AL_FORMAT_STEREO16; // Open the requested capture device for capturing 16 bits samples captureDevice = alcCaptureOpenDevice(m_deviceName.c_str(), m_sampleRate, format, static_cast(m_sampleRate)); diff --git a/src/SFML/Audio/SoundStream.cpp b/src/SFML/Audio/SoundStream.cpp index 03042986..1e08f0ef 100644 --- a/src/SFML/Audio/SoundStream.cpp +++ b/src/SFML/Audio/SoundStream.cpp @@ -69,7 +69,7 @@ void SoundStream::initialize(unsigned int channelCount, unsigned int sampleRate) m_samplesProcessed = 0; { - std::lock_guard lock(m_threadMutex); + const std::lock_guard lock(m_threadMutex); m_isStreaming = false; } @@ -101,7 +101,7 @@ void SoundStream::play() Status threadStartState = Stopped; { - std::lock_guard lock(m_threadMutex); + const std::lock_guard lock(m_threadMutex); isStreaming = m_isStreaming; threadStartState = m_threadStartState; @@ -111,7 +111,7 @@ void SoundStream::play() if (isStreaming && (threadStartState == Paused)) { // If the sound is paused, resume it - std::lock_guard lock(m_threadMutex); + const std::lock_guard lock(m_threadMutex); m_threadStartState = Playing; alCheck(alSourcePlay(m_source)); return; @@ -138,7 +138,7 @@ void SoundStream::pause() { // Handle pause() being called before the thread has started { - std::lock_guard lock(m_threadMutex); + const std::lock_guard lock(m_threadMutex); if (!m_isStreaming) return; @@ -183,7 +183,7 @@ SoundStream::Status SoundStream::getStatus() const // To compensate for the lag between play() and alSourceplay() if (status == Stopped) { - std::lock_guard lock(m_threadMutex); + const std::lock_guard lock(m_threadMutex); if (m_isStreaming) status = m_threadStartState; @@ -197,7 +197,7 @@ SoundStream::Status SoundStream::getStatus() const void SoundStream::setPlayingOffset(Time timeOffset) { // Get old playing status - Status oldStatus = getStatus(); + const Status oldStatus = getStatus(); // Stop the stream stop(); @@ -267,7 +267,7 @@ void SoundStream::streamData() bool requestStop = false; { - std::lock_guard lock(m_threadMutex); + const std::lock_guard lock(m_threadMutex); // Check if the thread was launched Stopped if (m_threadStartState == Stopped) @@ -289,7 +289,7 @@ void SoundStream::streamData() alCheck(alSourcePlay(m_source)); { - std::lock_guard lock(m_threadMutex); + const std::lock_guard lock(m_threadMutex); // Check if the thread was launched Paused if (m_threadStartState == Paused) @@ -299,7 +299,7 @@ void SoundStream::streamData() for (;;) { { - std::lock_guard lock(m_threadMutex); + const std::lock_guard lock(m_threadMutex); if (!m_isStreaming) break; } @@ -315,7 +315,7 @@ void SoundStream::streamData() else { // End streaming - std::lock_guard lock(m_threadMutex); + const std::lock_guard lock(m_threadMutex); m_isStreaming = false; } } @@ -360,7 +360,7 @@ void SoundStream::streamData() << "and initialize() has been called correctly" << std::endl; // Abort streaming (exit main loop) - std::lock_guard lock(m_threadMutex); + const std::lock_guard lock(m_threadMutex); m_isStreaming = false; requestStop = true; break; @@ -383,7 +383,7 @@ void SoundStream::streamData() if (alGetLastError() != AL_NO_ERROR) { // Abort streaming (exit main loop) - std::lock_guard lock(m_threadMutex); + const std::lock_guard lock(m_threadMutex); m_isStreaming = false; break; } @@ -449,10 +449,10 @@ bool SoundStream::fillAndPushBuffer(unsigned int bufferNum, bool immediateLoop) // Fill the buffer if some data was returned if (data.samples && data.sampleCount) { - unsigned int buffer = m_buffers[bufferNum]; + const unsigned int buffer = m_buffers[bufferNum]; // Fill the buffer - auto size = static_cast(data.sampleCount * sizeof(std::int16_t)); + const auto size = static_cast(data.sampleCount * sizeof(std::int16_t)); alCheck(alBufferData(buffer, m_format, data.samples, size, static_cast(m_sampleRate))); // Push it into the sound queue @@ -503,7 +503,7 @@ void SoundStream::clearQueue() void SoundStream::launchStreamingThread(Status threadStartState) { { - std::lock_guard lock(m_threadMutex); + const std::lock_guard lock(m_threadMutex); m_isStreaming = true; m_threadStartState = threadStartState; } @@ -518,7 +518,7 @@ void SoundStream::awaitStreamingThread() { // Request the thread to join { - std::lock_guard lock(m_threadMutex); + const std::lock_guard lock(m_threadMutex); m_isStreaming = false; } diff --git a/src/SFML/Graphics/CircleShape.cpp b/src/SFML/Graphics/CircleShape.cpp index 3661be05..029e65fe 100644 --- a/src/SFML/Graphics/CircleShape.cpp +++ b/src/SFML/Graphics/CircleShape.cpp @@ -71,7 +71,7 @@ std::size_t CircleShape::getPointCount() const //////////////////////////////////////////////////////////// Vector2f CircleShape::getPoint(std::size_t index) const { - Angle angle = static_cast(index) / static_cast(m_pointCount) * sf::degrees(360) - sf::degrees(90); + const Angle angle = static_cast(index) / static_cast(m_pointCount) * sf::degrees(360) - sf::degrees(90); return Vector2f(m_radius, m_radius) + Vector2f(m_radius, angle); } diff --git a/src/SFML/Graphics/Font.cpp b/src/SFML/Graphics/Font.cpp index 77a1e59f..7c8efa9c 100644 --- a/src/SFML/Graphics/Font.cpp +++ b/src/SFML/Graphics/Font.cpp @@ -54,8 +54,8 @@ namespace // 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); + const auto convertedOffset = static_cast(offset); + auto* stream = static_cast(rec->descriptor.pointer); if (stream->seek(convertedOffset) == convertedOffset) { if (count > 0) @@ -350,12 +350,12 @@ const Glyph& Font::getGlyph(std::uint32_t codePoint, unsigned int characterSize, GlyphTable& glyphs = loadPage(characterSize).glyphs; // Build the key by combining the glyph index (based on code point), bold flag, and outline thickness - std::uint64_t key = combine(outlineThickness, - bold, - FT_Get_Char_Index(m_fontHandles ? m_fontHandles->face : nullptr, codePoint)); + const std::uint64_t key = combine(outlineThickness, + bold, + FT_Get_Char_Index(m_fontHandles ? m_fontHandles->face : nullptr, codePoint)); // Search the glyph into the cache - if (auto it = glyphs.find(key); it != glyphs.end()) + if (const auto it = glyphs.find(key); it != glyphs.end()) { // Found: just return it return it->second; @@ -363,7 +363,7 @@ const Glyph& Font::getGlyph(std::uint32_t codePoint, unsigned int characterSize, else { // Not found: we have to load it - Glyph glyph = loadGlyph(codePoint, characterSize, bold, outlineThickness); + const Glyph glyph = loadGlyph(codePoint, characterSize, bold, outlineThickness); return glyphs.emplace(key, glyph).first->second; } } @@ -388,12 +388,12 @@ float Font::getKerning(std::uint32_t first, std::uint32_t second, unsigned int c if (face && setCurrentSize(characterSize)) { // Convert the characters to indices - FT_UInt index1 = FT_Get_Char_Index(face, first); - FT_UInt index2 = FT_Get_Char_Index(face, second); + const FT_UInt index1 = FT_Get_Char_Index(face, first); + const 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 secondLsbDelta = static_cast(getGlyph(second, characterSize, bold).lsbDelta); + const auto firstRsbDelta = static_cast(getGlyph(first, characterSize, bold).rsbDelta); + const auto secondLsbDelta = static_cast(getGlyph(second, characterSize, bold).lsbDelta); // Get the kerning vector if present FT_Vector kerning; @@ -573,8 +573,8 @@ Glyph Font::loadGlyph(std::uint32_t codePoint, unsigned int characterSize, bool 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); + const FT_Pos weight = 1 << 6; + const bool outline = (glyphDesc->format == FT_GLYPH_FORMAT_OUTLINE); if (outline) { if (bold) @@ -676,7 +676,7 @@ Glyph Font::loadGlyph(std::uint32_t codePoint, unsigned int characterSize, bool 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; + const 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; @@ -690,7 +690,7 @@ Glyph Font::loadGlyph(std::uint32_t codePoint, unsigned int characterSize, bool 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; + const std::size_t index = x + y * width; m_pixelBuffer[index * 4 + 3] = pixels[x - padding]; } pixels += bitmap.pitch; @@ -698,10 +698,10 @@ Glyph Font::loadGlyph(std::uint32_t codePoint, unsigned int characterSize, bool } // Write the pixels to the texture - unsigned int x = static_cast(glyph.textureRect.left) - padding; - unsigned int y = static_cast(glyph.textureRect.top) - padding; - unsigned int w = static_cast(glyph.textureRect.width) + 2 * padding; - unsigned int h = static_cast(glyph.textureRect.height) + 2 * padding; + const unsigned int x = static_cast(glyph.textureRect.left) - padding; + const unsigned int y = static_cast(glyph.textureRect.top) - padding; + const unsigned int w = static_cast(glyph.textureRect.width) + 2 * padding; + const unsigned int h = static_cast(glyph.textureRect.height) + 2 * padding; page.texture.update(m_pixelBuffer.data(), {w, h}, {x, y}); } @@ -721,7 +721,7 @@ IntRect Font::findGlyphRect(Page& page, const Vector2u& size) const float bestRatio = 0; for (auto it = page.rows.begin(); it != page.rows.end() && !row; ++it) { - float ratio = static_cast(size.y) / static_cast(it->height); + const float ratio = static_cast(size.y) / static_cast(it->height); // Ignore rows that are either too small or too high if ((ratio < 0.7f) || (ratio > 1.f)) @@ -743,11 +743,11 @@ IntRect Font::findGlyphRect(Page& page, const Vector2u& size) const // If we didn't find a matching row, create a new one (10% taller than the glyph) if (!row) { - unsigned int rowHeight = size.y + size.y / 10; + const unsigned int rowHeight = size.y + size.y / 10; 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(); + const Vector2u textureSize = page.texture.getSize(); if ((textureSize.x * 2 <= Texture::getMaximumSize()) && (textureSize.y * 2 <= Texture::getMaximumSize())) { // Make the texture 2 times bigger @@ -794,12 +794,12 @@ 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 - FT_Face face = m_fontHandles->face; - FT_UShort currentSize = face->size->metrics.x_ppem; + FT_Face face = m_fontHandles->face; + const FT_UShort currentSize = face->size->metrics.x_ppem; if (currentSize != characterSize) { - FT_Error result = FT_Set_Pixel_Sizes(face, 0, characterSize); + const FT_Error result = FT_Set_Pixel_Sizes(face, 0, characterSize); if (result == FT_Err_Invalid_Pixel_Size) { diff --git a/src/SFML/Graphics/GLCheck.cpp b/src/SFML/Graphics/GLCheck.cpp index c6d5dd01..fec6140a 100644 --- a/src/SFML/Graphics/GLCheck.cpp +++ b/src/SFML/Graphics/GLCheck.cpp @@ -39,7 +39,7 @@ namespace sf::priv void glCheckError(const std::filesystem::path& file, unsigned int line, std::string_view expression) { // Get the last error - GLenum errorCode = glGetError(); + const GLenum errorCode = glGetError(); if (errorCode != GL_NO_ERROR) { diff --git a/src/SFML/Graphics/Image.cpp b/src/SFML/Graphics/Image.cpp index 4f84c9de..7757ebef 100644 --- a/src/SFML/Graphics/Image.cpp +++ b/src/SFML/Graphics/Image.cpp @@ -227,9 +227,9 @@ void Image::createMaskFromColor(const Color& color, std::uint8_t alpha) std::uint8_t* dst = dstPixels + j * 4; // Interpolate RGBA components using the alpha values of the destination and source pixels - std::uint8_t srcAlpha = src[3]; - std::uint8_t dstAlpha = dst[3]; - auto outAlpha = static_cast(srcAlpha + dstAlpha - srcAlpha * dstAlpha / 255); + const std::uint8_t srcAlpha = src[3]; + const std::uint8_t dstAlpha = dst[3]; + const auto outAlpha = static_cast(srcAlpha + dstAlpha - srcAlpha * dstAlpha / 255); dst[3] = outAlpha; @@ -299,7 +299,7 @@ void Image::flipHorizontally() { if (!m_pixels.empty()) { - std::size_t rowSize = m_size.x * 4; + const std::size_t rowSize = m_size.x * 4; for (std::size_t y = 0; y < m_size.y; ++y) { @@ -324,7 +324,7 @@ void Image::flipVertically() { if (!m_pixels.empty()) { - auto rowSize = static_cast::iterator::difference_type>(m_size.x * 4); + const auto rowSize = static_cast::iterator::difference_type>(m_size.x * 4); auto top = m_pixels.begin(); auto bottom = m_pixels.end() - rowSize; diff --git a/src/SFML/Graphics/ImageLoader.cpp b/src/SFML/Graphics/ImageLoader.cpp index bdf10825..58a4479f 100644 --- a/src/SFML/Graphics/ImageLoader.cpp +++ b/src/SFML/Graphics/ImageLoader.cpp @@ -286,8 +286,8 @@ bool ImageLoader::saveImageToMemory(const std::string& format, { // Choose function based on format - std::string specified = toLower(format); - const Vector2i convertedSize = Vector2i(size); + const std::string specified = toLower(format); + const Vector2i convertedSize = Vector2i(size); if (specified == "bmp") { diff --git a/src/SFML/Graphics/RenderTarget.cpp b/src/SFML/Graphics/RenderTarget.cpp index 806ff024..35085840 100644 --- a/src/SFML/Graphics/RenderTarget.cpp +++ b/src/SFML/Graphics/RenderTarget.cpp @@ -59,7 +59,7 @@ std::recursive_mutex mutex; // tracking the currently active RenderTarget within a given context std::uint64_t getUniqueId() { - std::lock_guard lock(mutex); + const std::lock_guard lock(mutex); static std::uint64_t id = 1; // start at 1, zero is "no RenderTarget" @@ -74,7 +74,7 @@ ContextRenderTargetMap contextRenderTargetMap; // Check if a RenderTarget with the given ID is active in the current context bool isActive(std::uint64_t id) { - auto it = contextRenderTargetMap.find(sf::Context::getActiveContextId()); + const auto it = contextRenderTargetMap.find(sf::Context::getActiveContextId()); return (it != contextRenderTargetMap.end()) && (it->second == id); } @@ -213,10 +213,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; - 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; + Vector2f normalized; + const 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; // Then transform by the inverse of the view matrix return view.getInverseTransform().transformPoint(normalized); @@ -234,13 +234,13 @@ Vector2i RenderTarget::mapCoordsToPixel(const Vector2f& point) const Vector2i RenderTarget::mapCoordsToPixel(const Vector2f& point, const View& view) const { // First, transform the point by the view matrix - Vector2f normalized = view.getTransform().transformPoint(point); + const Vector2f normalized = view.getTransform().transformPoint(point); // Then convert to viewport coordinates - 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); + Vector2i pixel; + const 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); return pixel; } @@ -263,7 +263,7 @@ void RenderTarget::draw(const Vertex* vertices, std::size_t vertexCount, Primiti if (RenderTargetImpl::isActive(m_id) || setActive(true)) { // Check if the vertex count is low enough so that we can pre-transform them - bool useVertexCache = (vertexCount <= StatesCache::VertexCacheSize); + const bool useVertexCache = (vertexCount <= StatesCache::VertexCacheSize); if (useVertexCache) { @@ -280,7 +280,7 @@ void RenderTarget::draw(const Vertex* vertices, std::size_t vertexCount, Primiti setupDraw(useVertexCache, states); // Check if texture coordinates array is needed, and update client state accordingly - bool enableTexCoordsArray = (states.texture || states.shader); + const bool enableTexCoordsArray = (states.texture || states.shader); if (!m_cache.enable || (enableTexCoordsArray != m_cache.texCoordsArrayEnabled)) { if (enableTexCoordsArray) @@ -392,12 +392,12 @@ bool RenderTarget::setActive(bool active) { // Mark this RenderTarget as active or no longer active in the tracking map { - std::lock_guard lock(RenderTargetImpl::mutex); + const std::lock_guard lock(RenderTargetImpl::mutex); - std::uint64_t contextId = Context::getActiveContextId(); + const std::uint64_t contextId = Context::getActiveContextId(); using RenderTargetImpl::contextRenderTargetMap; - auto it = contextRenderTargetMap.find(contextId); + const auto it = contextRenderTargetMap.find(contextId); if (active) { @@ -435,7 +435,7 @@ void RenderTarget::pushGLStates() { #ifdef SFML_DEBUG // make sure that the user didn't leave an unchecked OpenGL error - GLenum error = glGetError(); + const GLenum error = glGetError(); if (error != GL_NO_ERROR) { err() << "OpenGL error (" << error << ") detected in user code, " @@ -482,8 +482,8 @@ 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 vertexBufferAvailable = VertexBuffer::isAvailable(); + const bool shaderAvailable = Shader::isAvailable(); + const bool vertexBufferAvailable = VertexBuffer::isAvailable(); // Workaround for states not being properly reset on // macOS unless a context switch really takes place @@ -561,8 +561,8 @@ void RenderTarget::initialize() void RenderTarget::applyCurrentView() { // Set the viewport - IntRect viewport = getViewport(m_view); - int top = static_cast(getSize().y) - (viewport.top + viewport.height); + const IntRect viewport = getViewport(m_view); + const int top = static_cast(getSize().y) - (viewport.top + viewport.height); glCheck(glViewport(viewport.left, top, viewport.width, viewport.height)); // Set the projection matrix @@ -706,7 +706,7 @@ void RenderTarget::setupDraw(bool useVertexCache, const RenderStates& states) } else { - std::uint64_t textureId = states.texture ? states.texture->m_cacheId : 0; + const std::uint64_t textureId = states.texture ? states.texture->m_cacheId : 0; if (textureId != m_cache.lastTextureId) applyTexture(states.texture); } @@ -722,7 +722,7 @@ void RenderTarget::drawPrimitives(PrimitiveType type, std::size_t firstVertex, s { // 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[static_cast(type)]; + const GLenum mode = modes[static_cast(type)]; // Draw the primitives glCheck(glDrawArrays(mode, static_cast(firstVertex), static_cast(vertexCount))); diff --git a/src/SFML/Graphics/RenderTextureImplDefault.cpp b/src/SFML/Graphics/RenderTextureImplDefault.cpp index 2cf9f1d8..4c6ac0c7 100644 --- a/src/SFML/Graphics/RenderTextureImplDefault.cpp +++ b/src/SFML/Graphics/RenderTextureImplDefault.cpp @@ -86,7 +86,7 @@ bool RenderTextureImplDefault::isSrgb() const void RenderTextureImplDefault::updateTexture(unsigned int textureId) { // Make sure that the current texture binding will be preserved - priv::TextureSaver save; + const priv::TextureSaver save; // Copy the rendered pixels to the texture glCheck(glBindTexture(GL_TEXTURE_2D, textureId)); diff --git a/src/SFML/Graphics/RenderTextureImplFBO.cpp b/src/SFML/Graphics/RenderTextureImplFBO.cpp index eea18150..f4ceec3c 100644 --- a/src/SFML/Graphics/RenderTextureImplFBO.cpp +++ b/src/SFML/Graphics/RenderTextureImplFBO.cpp @@ -65,13 +65,13 @@ std::recursive_mutex mutex; // might trigger deletion of its contained stale FBOs void destroyStaleFBOs() { - std::uint64_t contextId = sf::Context::getActiveContextId(); + const std::uint64_t contextId = sf::Context::getActiveContextId(); for (auto it = staleFrameBuffers.begin(); it != staleFrameBuffers.end();) { if (it->first == contextId) { - auto frameBuffer = static_cast(it->second); + const auto frameBuffer = static_cast(it->second); glCheck(GLEXT_glDeleteFramebuffers(1, &frameBuffer)); staleFrameBuffers.erase(it++); @@ -86,9 +86,9 @@ void destroyStaleFBOs() // Callback that is called every time a context is destroyed void contextDestroyCallback(void* /*arg*/) { - std::lock_guard lock(mutex); + const std::lock_guard lock(mutex); - std::uint64_t contextId = sf::Context::getActiveContextId(); + const std::uint64_t contextId = sf::Context::getActiveContextId(); // Destroy active frame buffer objects for (auto* frameBuffer : frameBuffers) @@ -97,7 +97,7 @@ void contextDestroyCallback(void* /*arg*/) { if (it->first == contextId) { - GLuint frameBufferId = it->second; + const GLuint frameBufferId = it->second; glCheck(GLEXT_glDeleteFramebuffers(1, &frameBufferId)); // Erase the entry from the RenderTextureImplFBO's map @@ -119,7 +119,7 @@ namespace sf::priv //////////////////////////////////////////////////////////// RenderTextureImplFBO::RenderTextureImplFBO() { - std::lock_guard lock(mutex); + const std::lock_guard lock(mutex); // Register the context destruction callback registerContextDestroyCallback(contextDestroyCallback, nullptr); @@ -133,9 +133,9 @@ RenderTextureImplFBO::RenderTextureImplFBO() //////////////////////////////////////////////////////////// RenderTextureImplFBO::~RenderTextureImplFBO() { - TransientContextLock contextLock; + const TransientContextLock contextLock; - std::lock_guard lock(mutex); + const std::lock_guard lock(mutex); // Remove the frame buffer mapping from the set of all active mappings frameBuffers.erase(&m_frameBuffers); @@ -144,14 +144,14 @@ RenderTextureImplFBO::~RenderTextureImplFBO() // Destroy the color buffer if (m_colorBuffer) { - GLuint colorBuffer = m_colorBuffer; + const GLuint colorBuffer = m_colorBuffer; glCheck(GLEXT_glDeleteRenderbuffers(1, &colorBuffer)); } // Destroy the depth/stencil buffer if (m_depthStencilBuffer) { - GLuint depthStencilBuffer = m_depthStencilBuffer; + const GLuint depthStencilBuffer = m_depthStencilBuffer; glCheck(GLEXT_glDeleteRenderbuffers(1, &depthStencilBuffer)); } @@ -170,7 +170,7 @@ RenderTextureImplFBO::~RenderTextureImplFBO() //////////////////////////////////////////////////////////// bool RenderTextureImplFBO::isAvailable() { - TransientContextLock lock; + const TransientContextLock lock; // Make sure that extensions are initialized priv::ensureExtensionsInit(); @@ -182,7 +182,7 @@ bool RenderTextureImplFBO::isAvailable() //////////////////////////////////////////////////////////// unsigned int RenderTextureImplFBO::getMaximumAntialiasingLevel() { - TransientContextLock lock; + const TransientContextLock lock; GLint samples = 0; @@ -210,7 +210,7 @@ bool RenderTextureImplFBO::create(const Vector2u& size, unsigned int textureId, m_size = size; { - TransientContextLock lock; + const TransientContextLock lock; // Make sure that extensions are initialized priv::ensureExtensionsInit(); @@ -468,7 +468,7 @@ bool RenderTextureImplFBO::createFrameBuffer() } { - std::lock_guard lock(mutex); + const std::lock_guard lock(mutex); // Insert the FBO into our map m_frameBuffers.emplace(Context::getActiveContextId(), frameBuffer); @@ -525,7 +525,7 @@ bool RenderTextureImplFBO::createFrameBuffer() } { - std::lock_guard lock(mutex); + const std::lock_guard lock(mutex); // Insert the FBO into our map m_multisampleFrameBuffers.emplace(Context::getActiveContextId(), multisampleFrameBuffer); @@ -576,7 +576,7 @@ bool RenderTextureImplFBO::activate(bool active) // If none is found, there is no FBO corresponding to the // currently active context so we will have to create a new FBO { - std::lock_guard lock(mutex); + const std::lock_guard lock(mutex); std::unordered_map::iterator it; @@ -628,12 +628,12 @@ void RenderTextureImplFBO::updateTexture(unsigned int) // are already available within the current context if (m_multisample && m_size.x && m_size.y && activate(true)) { - std::uint64_t contextId = Context::getActiveContextId(); + const std::uint64_t contextId = Context::getActiveContextId(); - std::lock_guard lock(mutex); + const std::lock_guard lock(mutex); - auto frameBufferIt = m_frameBuffers.find(contextId); - auto multisampleIt = m_multisampleFrameBuffers.find(contextId); + const auto frameBufferIt = m_frameBuffers.find(contextId); + const auto multisampleIt = m_multisampleFrameBuffers.find(contextId); if ((frameBufferIt != m_frameBuffers.end()) && (multisampleIt != m_multisampleFrameBuffers.end())) { diff --git a/src/SFML/Graphics/Shader.cpp b/src/SFML/Graphics/Shader.cpp index 08b55646..eb442c49 100644 --- a/src/SFML/Graphics/Shader.cpp +++ b/src/SFML/Graphics/Shader.cpp @@ -74,7 +74,7 @@ GLint checkMaxTextureUnits() // Retrieve the maximum number of texture units available std::size_t getMaxTextureUnits() { - static GLint maxUnits = checkMaxTextureUnits(); + static const GLint maxUnits = checkMaxTextureUnits(); return static_cast(maxUnits); } @@ -85,7 +85,7 @@ bool getFileContents(const std::filesystem::path& filename, std::vector& b if (file) { file.seekg(0, std::ios_base::end); - std::ifstream::pos_type size = file.tellg(); + const std::ifstream::pos_type size = file.tellg(); if (size > 0) { file.seekg(0, std::ios_base::beg); @@ -104,8 +104,8 @@ bool getFileContents(const std::filesystem::path& filename, std::vector& b // Read the contents of a stream into an array of char bool getStreamContents(sf::InputStream& stream, std::vector& buffer) { - bool success = true; - std::int64_t size = stream.getSize(); + bool success = true; + const std::int64_t size = stream.getSize(); if (size > 0) { buffer.resize(static_cast(size)); @@ -116,8 +116,8 @@ bool getStreamContents(sf::InputStream& stream, std::vector& buffer) return false; } - std::int64_t read = stream.read(buffer.data(), size); - success = (read == size); + const std::int64_t read = stream.read(buffer.data(), size); + success = (read == size); } buffer.push_back('\0'); return success; @@ -240,7 +240,7 @@ Shader::Shader() = default; //////////////////////////////////////////////////////////// Shader::~Shader() { - TransientContextLock lock; + const TransientContextLock lock; // Destroy effect program if (m_shaderProgram) @@ -267,7 +267,7 @@ Shader& Shader::operator=(Shader&& right) noexcept // Explicit scope for RAII { // Destroy effect program - TransientContextLock lock; + const TransientContextLock lock; if (m_shaderProgram) glCheck(GLEXT_glDeleteObject(castToGlHandle(m_shaderProgram))); } @@ -469,7 +469,7 @@ bool Shader::loadFromStream(InputStream& vertexShaderStream, InputStream& geomet //////////////////////////////////////////////////////////// void Shader::setUniform(const std::string& name, float x) { - UniformBinder binder(*this, name); + const UniformBinder binder(*this, name); if (binder.location != -1) glCheck(GLEXT_glUniform1f(binder.location, x)); } @@ -478,7 +478,7 @@ void Shader::setUniform(const std::string& name, float x) //////////////////////////////////////////////////////////// void Shader::setUniform(const std::string& name, const Glsl::Vec2& v) { - UniformBinder binder(*this, name); + const UniformBinder binder(*this, name); if (binder.location != -1) glCheck(GLEXT_glUniform2f(binder.location, v.x, v.y)); } @@ -487,7 +487,7 @@ void Shader::setUniform(const std::string& name, const Glsl::Vec2& v) //////////////////////////////////////////////////////////// void Shader::setUniform(const std::string& name, const Glsl::Vec3& v) { - UniformBinder binder(*this, name); + const UniformBinder binder(*this, name); if (binder.location != -1) glCheck(GLEXT_glUniform3f(binder.location, v.x, v.y, v.z)); } @@ -496,7 +496,7 @@ void Shader::setUniform(const std::string& name, const Glsl::Vec3& v) //////////////////////////////////////////////////////////// void Shader::setUniform(const std::string& name, const Glsl::Vec4& v) { - UniformBinder binder(*this, name); + const UniformBinder binder(*this, name); if (binder.location != -1) glCheck(GLEXT_glUniform4f(binder.location, v.x, v.y, v.z, v.w)); } @@ -505,7 +505,7 @@ void Shader::setUniform(const std::string& name, const Glsl::Vec4& v) //////////////////////////////////////////////////////////// void Shader::setUniform(const std::string& name, int x) { - UniformBinder binder(*this, name); + const UniformBinder binder(*this, name); if (binder.location != -1) glCheck(GLEXT_glUniform1i(binder.location, x)); } @@ -514,7 +514,7 @@ void Shader::setUniform(const std::string& name, int x) //////////////////////////////////////////////////////////// void Shader::setUniform(const std::string& name, const Glsl::Ivec2& v) { - UniformBinder binder(*this, name); + const UniformBinder binder(*this, name); if (binder.location != -1) glCheck(GLEXT_glUniform2i(binder.location, v.x, v.y)); } @@ -523,7 +523,7 @@ void Shader::setUniform(const std::string& name, const Glsl::Ivec2& v) //////////////////////////////////////////////////////////// void Shader::setUniform(const std::string& name, const Glsl::Ivec3& v) { - UniformBinder binder(*this, name); + const UniformBinder binder(*this, name); if (binder.location != -1) glCheck(GLEXT_glUniform3i(binder.location, v.x, v.y, v.z)); } @@ -532,7 +532,7 @@ void Shader::setUniform(const std::string& name, const Glsl::Ivec3& v) //////////////////////////////////////////////////////////// void Shader::setUniform(const std::string& name, const Glsl::Ivec4& v) { - UniformBinder binder(*this, name); + const UniformBinder binder(*this, name); if (binder.location != -1) glCheck(GLEXT_glUniform4i(binder.location, v.x, v.y, v.z, v.w)); } @@ -569,7 +569,7 @@ void Shader::setUniform(const std::string& name, const Glsl::Bvec4& v) //////////////////////////////////////////////////////////// void Shader::setUniform(const std::string& name, const Glsl::Mat3& matrix) { - UniformBinder binder(*this, name); + const UniformBinder binder(*this, name); if (binder.location != -1) glCheck(GLEXT_glUniformMatrix3fv(binder.location, 1, GL_FALSE, matrix.array)); } @@ -578,7 +578,7 @@ void Shader::setUniform(const std::string& name, const Glsl::Mat3& matrix) //////////////////////////////////////////////////////////// void Shader::setUniform(const std::string& name, const Glsl::Mat4& matrix) { - UniformBinder binder(*this, name); + const UniformBinder binder(*this, name); if (binder.location != -1) glCheck(GLEXT_glUniformMatrix4fv(binder.location, 1, GL_FALSE, matrix.array)); } @@ -589,14 +589,14 @@ void Shader::setUniform(const std::string& name, const Texture& texture) { if (m_shaderProgram) { - TransientContextLock lock; + const TransientContextLock lock; // Find the location of the variable in the shader - int location = getUniformLocation(name); + const int location = getUniformLocation(name); if (location != -1) { // Store the location -> texture mapping - auto it = m_textures.find(location); + const auto it = m_textures.find(location); if (it == m_textures.end()) { // New entry, make sure there are enough texture units @@ -624,7 +624,7 @@ void Shader::setUniform(const std::string& name, CurrentTextureType) { if (m_shaderProgram) { - TransientContextLock lock; + const TransientContextLock lock; // Find the location of the variable in the shader m_currentTexture = getUniformLocation(name); @@ -635,7 +635,7 @@ void Shader::setUniform(const std::string& name, CurrentTextureType) //////////////////////////////////////////////////////////// void Shader::setUniformArray(const std::string& name, const float* scalarArray, std::size_t length) { - UniformBinder binder(*this, name); + const UniformBinder binder(*this, name); if (binder.location != -1) glCheck(GLEXT_glUniform1fv(binder.location, static_cast(length), scalarArray)); } @@ -646,7 +646,7 @@ void Shader::setUniformArray(const std::string& name, const Glsl::Vec2* vectorAr { std::vector contiguous = flatten(vectorArray, length); - UniformBinder binder(*this, name); + const UniformBinder binder(*this, name); if (binder.location != -1) glCheck(GLEXT_glUniform2fv(binder.location, static_cast(length), contiguous.data())); } @@ -657,7 +657,7 @@ void Shader::setUniformArray(const std::string& name, const Glsl::Vec3* vectorAr { std::vector contiguous = flatten(vectorArray, length); - UniformBinder binder(*this, name); + const UniformBinder binder(*this, name); if (binder.location != -1) glCheck(GLEXT_glUniform3fv(binder.location, static_cast(length), contiguous.data())); } @@ -668,7 +668,7 @@ void Shader::setUniformArray(const std::string& name, const Glsl::Vec4* vectorAr { std::vector contiguous = flatten(vectorArray, length); - UniformBinder binder(*this, name); + const UniformBinder binder(*this, name); if (binder.location != -1) glCheck(GLEXT_glUniform4fv(binder.location, static_cast(length), contiguous.data())); } @@ -683,7 +683,7 @@ void Shader::setUniformArray(const std::string& name, const Glsl::Mat3* matrixAr for (std::size_t i = 0; i < length; ++i) priv::copyMatrix(matrixArray[i].array, matrixSize, &contiguous[matrixSize * i]); - UniformBinder binder(*this, name); + const UniformBinder binder(*this, name); if (binder.location != -1) glCheck(GLEXT_glUniformMatrix3fv(binder.location, static_cast(length), GL_FALSE, contiguous.data())); } @@ -698,7 +698,7 @@ void Shader::setUniformArray(const std::string& name, const Glsl::Mat4* matrixAr for (std::size_t i = 0; i < length; ++i) priv::copyMatrix(matrixArray[i].array, matrixSize, &contiguous[matrixSize * i]); - UniformBinder binder(*this, name); + const UniformBinder binder(*this, name); if (binder.location != -1) glCheck(GLEXT_glUniformMatrix4fv(binder.location, static_cast(length), GL_FALSE, contiguous.data())); } @@ -714,7 +714,7 @@ unsigned int Shader::getNativeHandle() const //////////////////////////////////////////////////////////// void Shader::bind(const Shader* shader) { - TransientContextLock lock; + const TransientContextLock lock; // Make sure that we can use shaders if (!isAvailable()) @@ -747,7 +747,7 @@ void Shader::bind(const Shader* shader) //////////////////////////////////////////////////////////// bool Shader::isAvailable() { - std::lock_guard lock(isAvailableMutex); + const std::lock_guard lock(isAvailableMutex); static bool checked = false; static bool available = false; @@ -756,7 +756,7 @@ bool Shader::isAvailable() { checked = true; - TransientContextLock contextLock; + const TransientContextLock contextLock; // Make sure that extensions are initialized sf::priv::ensureExtensionsInit(); @@ -772,7 +772,7 @@ bool Shader::isAvailable() //////////////////////////////////////////////////////////// bool Shader::isGeometryAvailable() { - std::lock_guard lock(isAvailableMutex); + const std::lock_guard lock(isAvailableMutex); static bool checked = false; static bool available = false; @@ -781,7 +781,7 @@ bool Shader::isGeometryAvailable() { checked = true; - TransientContextLock contextLock; + const TransientContextLock contextLock; // Make sure that extensions are initialized sf::priv::ensureExtensionsInit(); @@ -796,7 +796,7 @@ bool Shader::isGeometryAvailable() //////////////////////////////////////////////////////////// bool Shader::compile(const char* vertexShaderCode, const char* geometryShaderCode, const char* fragmentShaderCode) { - TransientContextLock lock; + const TransientContextLock lock; // First make sure that we can use shaders if (!isAvailable()) @@ -861,7 +861,7 @@ bool Shader::compile(const char* vertexShaderCode, const char* geometryShaderCod if (geometryShaderCode) { // Create and compile the shader - GLEXT_GLhandle geometryShader = GLEXT_glCreateShaderObject(GLEXT_GL_GEOMETRY_SHADER); + const GLEXT_GLhandle geometryShader = GLEXT_glCreateShaderObject(GLEXT_GL_GEOMETRY_SHADER); glCheck(GLEXT_glShaderSource(geometryShader, 1, &geometryShaderCode, nullptr)); glCheck(GLEXT_glCompileShader(geometryShader)); @@ -941,7 +941,7 @@ void Shader::bindTextures() const auto it = m_textures.begin(); for (std::size_t i = 0; i < m_textures.size(); ++i) { - auto index = static_cast(i + 1); + const auto index = static_cast(i + 1); glCheck(GLEXT_glUniform1i(it->first, index)); glCheck(GLEXT_glActiveTexture(GLEXT_GL_TEXTURE0 + static_cast(index))); Texture::bind(it->second); @@ -957,7 +957,7 @@ void Shader::bindTextures() const int Shader::getUniformLocation(const std::string& name) { // Check the cache - if (auto it = m_uniforms.find(name); it != m_uniforms.end()) + if (const auto it = m_uniforms.find(name); it != m_uniforms.end()) { // Already in cache, return it return it->second; @@ -965,7 +965,7 @@ int Shader::getUniformLocation(const std::string& name) else { // Not in cache, request the location from OpenGL - int location = GLEXT_glGetUniformLocation(castToGlHandle(m_shaderProgram), name.c_str()); + const int location = GLEXT_glGetUniformLocation(castToGlHandle(m_shaderProgram), name.c_str()); m_uniforms.emplace(name, location); if (location == -1) diff --git a/src/SFML/Graphics/Shape.cpp b/src/SFML/Graphics/Shape.cpp index 749071bc..3bfe5010 100644 --- a/src/SFML/Graphics/Shape.cpp +++ b/src/SFML/Graphics/Shape.cpp @@ -38,7 +38,7 @@ namespace sf::Vector2f computeNormal(const sf::Vector2f& p1, const sf::Vector2f& p2) { sf::Vector2f normal = (p2 - p1).perpendicular(); - float length = normal.length(); + const float length = normal.length(); if (length != 0.f) normal /= length; return normal; @@ -152,7 +152,7 @@ Shape::Shape() = default; void Shape::update() { // Get the total number of points of the shape - std::size_t count = getPointCount(); + const std::size_t count = getPointCount(); if (count < 3) { m_vertices.resize(0); @@ -217,13 +217,16 @@ void Shape::updateFillColors() //////////////////////////////////////////////////////////// void Shape::updateTexCoords() { - FloatRect convertedTextureRect(m_textureRect); + const FloatRect convertedTextureRect(m_textureRect); 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; + const float xratio = m_insideBounds.width > 0 + ? (m_vertices[i].position.x - m_insideBounds.left) / m_insideBounds.width + : 0; + const 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; } @@ -241,17 +244,17 @@ void Shape::updateOutline() return; } - std::size_t count = m_vertices.getVertexCount() - 2; + const std::size_t count = m_vertices.getVertexCount() - 2; m_outlineVertices.resize((count + 1) * 2); for (std::size_t i = 0; i < count; ++i) { - std::size_t index = i + 1; + const std::size_t index = i + 1; // Get the two segments shared by the current point - Vector2f p0 = (i == 0) ? m_vertices[count].position : m_vertices[index - 1].position; - Vector2f p1 = m_vertices[index].position; - Vector2f p2 = m_vertices[index + 1].position; + const Vector2f p0 = (i == 0) ? m_vertices[count].position : m_vertices[index - 1].position; + const Vector2f p1 = m_vertices[index].position; + const Vector2f p2 = m_vertices[index + 1].position; // Compute their normal Vector2f n1 = computeNormal(p0, p1); @@ -265,8 +268,8 @@ void Shape::updateOutline() n2 = -n2; // Combine them to get the extrusion direction - float factor = 1.f + (n1.x * n2.x + n1.y * n2.y); - Vector2f normal = (n1 + n2) / factor; + const float factor = 1.f + (n1.x * n2.x + n1.y * n2.y); + const Vector2f normal = (n1 + n2) / factor; // Update the outline points m_outlineVertices[i * 2 + 0].position = p1; diff --git a/src/SFML/Graphics/Sprite.cpp b/src/SFML/Graphics/Sprite.cpp index a747205e..13e47493 100644 --- a/src/SFML/Graphics/Sprite.cpp +++ b/src/SFML/Graphics/Sprite.cpp @@ -113,8 +113,8 @@ const Color& Sprite::getColor() const //////////////////////////////////////////////////////////// FloatRect Sprite::getLocalBounds() const { - auto width = static_cast(std::abs(m_textureRect.width)); - auto height = static_cast(std::abs(m_textureRect.height)); + const auto width = static_cast(std::abs(m_textureRect.width)); + const auto height = static_cast(std::abs(m_textureRect.height)); return FloatRect({0.f, 0.f}, {width, height}); } @@ -143,7 +143,7 @@ void Sprite::draw(RenderTarget& target, const RenderStates& states) const //////////////////////////////////////////////////////////// void Sprite::updatePositions() { - FloatRect bounds = getLocalBounds(); + const FloatRect bounds = getLocalBounds(); m_vertices[0].position = Vector2f(0, 0); m_vertices[1].position = Vector2f(0, bounds.height); @@ -155,12 +155,12 @@ void Sprite::updatePositions() //////////////////////////////////////////////////////////// void Sprite::updateTexCoords() { - FloatRect convertedTextureRect(m_textureRect); + const FloatRect convertedTextureRect(m_textureRect); - float left = convertedTextureRect.left; - float right = left + convertedTextureRect.width; - float top = convertedTextureRect.top; - float bottom = top + convertedTextureRect.height; + const float left = convertedTextureRect.left; + const float right = left + convertedTextureRect.width; + const float top = convertedTextureRect.top; + const float bottom = top + convertedTextureRect.height; m_vertices[0].texCoords = Vector2f(left, top); m_vertices[1].texCoords = Vector2f(left, bottom); diff --git a/src/SFML/Graphics/Text.cpp b/src/SFML/Graphics/Text.cpp index ca36a92b..aedebddb 100644 --- a/src/SFML/Graphics/Text.cpp +++ b/src/SFML/Graphics/Text.cpp @@ -47,8 +47,8 @@ void addLine(sf::VertexArray& vertices, float thickness, float outlineThickness = 0) { - float top = std::floor(lineTop + offset - (thickness / 2) + 0.5f); - float bottom = top + std::floor(thickness + 0.5f); + const float top = std::floor(lineTop + offset - (thickness / 2) + 0.5f); + const float bottom = top + std::floor(thickness + 0.5f); vertices.append(sf::Vertex(sf::Vector2f(-outlineThickness, top - outlineThickness), color, sf::Vector2f(1, 1))); vertices.append( @@ -64,17 +64,17 @@ void addLine(sf::VertexArray& vertices, // 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; + const 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; + const float left = glyph.bounds.left - padding; + const float top = glyph.bounds.top - padding; + const float right = glyph.bounds.left + glyph.bounds.width + padding; + const 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; + const float u1 = static_cast(glyph.textureRect.left) - padding; + const float v1 = static_cast(glyph.textureRect.top) - padding; + const float u2 = static_cast(glyph.textureRect.left + glyph.textureRect.width) + padding; + const 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))); @@ -304,18 +304,18 @@ Vector2f Text::findCharacterPos(std::size_t index) const index = m_string.getSize(); // 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); + const bool isBold = m_style & Bold; + float whitespaceWidth = m_font->getGlyph(U' ', m_characterSize, isBold).advance; + const float letterSpacing = (whitespaceWidth / 3.f) * (m_letterSpacingFactor - 1.f); whitespaceWidth += letterSpacing; - float lineSpacing = m_font->getLineSpacing(m_characterSize) * m_lineSpacingFactor; + const float lineSpacing = m_font->getLineSpacing(m_characterSize) * m_lineSpacingFactor; // Compute the position Vector2f position; std::uint32_t prevChar = 0; for (std::size_t i = 0; i < index; ++i) { - std::uint32_t curChar = m_string[i]; + const std::uint32_t curChar = m_string[i]; // Apply the kerning offset position.x += m_font->getKerning(prevChar, curChar, m_characterSize, isBold); @@ -404,26 +404,26 @@ void Text::ensureGeometryUpdate() const return; // Compute values related to the text style - bool isBold = m_style & Bold; - bool isUnderlined = m_style & Underlined; - bool isStrikeThrough = m_style & StrikeThrough; - float italicShear = (m_style & Italic) ? sf::degrees(12).asRadians() : 0.f; - float underlineOffset = m_font->getUnderlinePosition(m_characterSize); - float underlineThickness = m_font->getUnderlineThickness(m_characterSize); + const bool isBold = m_style & Bold; + const bool isUnderlined = m_style & Underlined; + const bool isStrikeThrough = m_style & StrikeThrough; + const float italicShear = (m_style & Italic) ? sf::degrees(12).asRadians() : 0.f; + const float underlineOffset = m_font->getUnderlinePosition(m_characterSize); + const float underlineThickness = m_font->getUnderlineThickness(m_characterSize); // 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; + const FloatRect xBounds = m_font->getGlyph(U'x', m_characterSize, isBold).bounds; + const 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); + float whitespaceWidth = m_font->getGlyph(U' ', m_characterSize, isBold).advance; + const 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); + const 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); @@ -433,7 +433,7 @@ void Text::ensureGeometryUpdate() const std::uint32_t prevChar = 0; for (std::size_t i = 0; i < m_string.getSize(); ++i) { - std::uint32_t curChar = m_string[i]; + const std::uint32_t curChar = m_string[i]; // Skip the \r char to avoid weird graphical issues if (curChar == U'\r') @@ -507,10 +507,10 @@ void Text::ensureGeometryUpdate() const addGlyphQuad(m_vertices, Vector2f(x, y), m_fillColor, glyph, italicShear); // Update the current bounds - 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; + const float left = glyph.bounds.left; + const float top = glyph.bounds.top; + const float right = glyph.bounds.left + glyph.bounds.width; + const float bottom = glyph.bounds.top + glyph.bounds.height; minX = std::min(minX, x + left - italicShear * bottom); maxX = std::max(maxX, x + right - italicShear * top); @@ -524,7 +524,7 @@ void Text::ensureGeometryUpdate() const // If we're using outline, update the current bounds if (m_outlineThickness != 0) { - float outline = std::abs(std::ceil(m_outlineThickness)); + const float outline = std::abs(std::ceil(m_outlineThickness)); minX -= outline; maxX += outline; minY -= outline; diff --git a/src/SFML/Graphics/Texture.cpp b/src/SFML/Graphics/Texture.cpp index c7a67e3f..86e95db2 100644 --- a/src/SFML/Graphics/Texture.cpp +++ b/src/SFML/Graphics/Texture.cpp @@ -96,9 +96,9 @@ Texture::~Texture() // Destroy the OpenGL texture if (m_texture) { - TransientContextLock lock; + const TransientContextLock lock; - GLuint texture = m_texture; + const GLuint texture = m_texture; glCheck(glDeleteTextures(1, &texture)); } } @@ -128,9 +128,9 @@ Texture& Texture::operator=(Texture&& right) noexcept // Destroy the OpenGL texture if (m_texture) { - TransientContextLock lock; + const TransientContextLock lock; - GLuint texture = m_texture; + const GLuint texture = m_texture; glCheck(glDeleteTextures(1, &texture)); } @@ -157,16 +157,16 @@ bool Texture::create(const Vector2u& size) return false; } - TransientContextLock lock; + const TransientContextLock lock; // Make sure that extensions are initialized priv::ensureExtensionsInit(); // Compute the internal texture dimensions depending on NPOT textures support - Vector2u actualSize(getValidSize(size.x), getValidSize(size.y)); + const Vector2u actualSize(getValidSize(size.x), getValidSize(size.y)); // Check the maximum texture size - unsigned int maxSize = getMaximumSize(); + const unsigned int maxSize = getMaximumSize(); if ((actualSize.x > maxSize) || (actualSize.y > maxSize)) { err() << "Failed to create texture, its internal size is too high " @@ -190,10 +190,10 @@ bool Texture::create(const Vector2u& size) } // Make sure that the current texture binding will be preserved - priv::TextureSaver save; + const priv::TextureSaver save; - static bool textureEdgeClamp = GLEXT_texture_edge_clamp || GLEXT_GL_VERSION_1_2 || - Context::isExtensionAvailable("GL_EXT_texture_edge_clamp"); + static const bool textureEdgeClamp = GLEXT_texture_edge_clamp || GLEXT_GL_VERSION_1_2 || + Context::isExtensionAvailable("GL_EXT_texture_edge_clamp"); if (!m_isRepeated && !textureEdgeClamp) { @@ -209,7 +209,7 @@ bool Texture::create(const Vector2u& size) } } - static bool textureSrgb = GLEXT_texture_sRGB; + static const bool textureSrgb = GLEXT_texture_sRGB; if (m_sRgb && !textureSrgb) { @@ -321,10 +321,10 @@ bool Texture::loadFromImage(const Image& image, const IntRect& area) // Create the texture and upload the pixels if (create(Vector2u(rectangle.getSize()))) { - TransientContextLock lock; + const TransientContextLock lock; // Make sure that the current texture binding will be preserved - priv::TextureSaver save; + const priv::TextureSaver save; // Copy the pixels to the texture, row by row const std::uint8_t* pixels = image.getPixelsPtr() + 4 * (rectangle.left + (width * rectangle.top)); @@ -366,10 +366,10 @@ Image Texture::copyToImage() const if (!m_texture) return Image(); - TransientContextLock lock; + const TransientContextLock lock; // Make sure that the current texture binding will be preserved - priv::TextureSaver save; + const priv::TextureSaver save; // Create an array of pixels std::vector pixels(m_size.x * m_size.y * 4); @@ -414,7 +414,7 @@ Image Texture::copyToImage() const const std::uint8_t* src = allPixels.data(); std::uint8_t* dst = pixels.data(); int srcPitch = static_cast(m_actualSize.x * 4); - unsigned int dstPitch = m_size.x * 4; + const unsigned int dstPitch = m_size.x * 4; // Handle the case where source pixels are flipped vertically if (m_pixelsFlipped) @@ -457,10 +457,10 @@ void Texture::update(const std::uint8_t* pixels, const Vector2u& size, const Vec if (pixels && m_texture) { - TransientContextLock lock; + const TransientContextLock lock; // Make sure that the current texture binding will be preserved - priv::TextureSaver save; + const priv::TextureSaver save; // Copy pixels from the given array to the texture glCheck(glBindTexture(GL_TEXTURE_2D, m_texture)); @@ -505,7 +505,7 @@ void Texture::update(const Texture& texture, const Vector2u& dest) #ifndef SFML_OPENGL_ES { - TransientContextLock lock; + const TransientContextLock lock; // Make sure that extensions are initialized priv::ensureExtensionsInit(); @@ -513,7 +513,7 @@ void Texture::update(const Texture& texture, const Vector2u& dest) if (GLEXT_framebuffer_object && GLEXT_framebuffer_blit) { - TransientContextLock lock; + const TransientContextLock lock; // Save the current bindings so we can restore them after we are done GLint readFramebuffer = 0; @@ -582,7 +582,7 @@ void Texture::update(const Texture& texture, const Vector2u& dest) glCheck(GLEXT_glDeleteFramebuffers(1, &destFrameBuffer)); // Make sure that the current texture binding will be preserved - priv::TextureSaver save; + const priv::TextureSaver save; // Set the parameters of this texture glCheck(glBindTexture(GL_TEXTURE_2D, m_texture)); @@ -634,10 +634,10 @@ void Texture::update(const Window& window, const Vector2u& dest) if (m_texture && window.setActive(true)) { - TransientContextLock lock; + const TransientContextLock lock; // Make sure that the current texture binding will be preserved - priv::TextureSaver save; + const priv::TextureSaver save; // Copy pixels from the back-buffer to the texture glCheck(glBindTexture(GL_TEXTURE_2D, m_texture)); @@ -670,10 +670,10 @@ void Texture::setSmooth(bool smooth) if (m_texture) { - TransientContextLock lock; + const TransientContextLock lock; // Make sure that the current texture binding will be preserved - priv::TextureSaver save; + const priv::TextureSaver save; glCheck(glBindTexture(GL_TEXTURE_2D, m_texture)); glCheck(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, m_isSmooth ? GL_LINEAR : GL_NEAREST)); @@ -723,12 +723,12 @@ void Texture::setRepeated(bool repeated) if (m_texture) { - TransientContextLock lock; + const TransientContextLock lock; // Make sure that the current texture binding will be preserved - priv::TextureSaver save; + const priv::TextureSaver save; - static bool textureEdgeClamp = GLEXT_texture_edge_clamp; + static const bool textureEdgeClamp = GLEXT_texture_edge_clamp; if (!m_isRepeated && !textureEdgeClamp) { @@ -771,7 +771,7 @@ bool Texture::generateMipmap() if (!m_texture) return false; - TransientContextLock lock; + const TransientContextLock lock; // Make sure that extensions are initialized priv::ensureExtensionsInit(); @@ -780,7 +780,7 @@ bool Texture::generateMipmap() return false; // Make sure that the current texture binding will be preserved - priv::TextureSaver save; + const priv::TextureSaver save; glCheck(glBindTexture(GL_TEXTURE_2D, m_texture)); glCheck(GLEXT_glGenerateMipmap(GL_TEXTURE_2D)); @@ -800,10 +800,10 @@ void Texture::invalidateMipmap() if (!m_hasMipmap) return; - TransientContextLock lock; + const TransientContextLock lock; // Make sure that the current texture binding will be preserved - priv::TextureSaver save; + const priv::TextureSaver save; glCheck(glBindTexture(GL_TEXTURE_2D, m_texture)); glCheck(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, m_isSmooth ? GL_LINEAR : GL_NEAREST)); @@ -815,7 +815,7 @@ void Texture::invalidateMipmap() //////////////////////////////////////////////////////////// void Texture::bind(const Texture* texture, CoordinateType coordinateType) { - TransientContextLock lock; + const TransientContextLock lock; if (texture && texture->m_texture) { @@ -875,7 +875,7 @@ unsigned int Texture::getMaximumSize() { static const unsigned int size = []() { - TransientContextLock transientLock; + const TransientContextLock transientLock; GLint value = 0; diff --git a/src/SFML/Graphics/Transform.cpp b/src/SFML/Graphics/Transform.cpp index 91742c13..50bc3ce0 100644 --- a/src/SFML/Graphics/Transform.cpp +++ b/src/SFML/Graphics/Transform.cpp @@ -37,14 +37,14 @@ namespace sf //////////////////////////////////////////////////////////// Transform& Transform::rotate(Angle angle) { - float rad = angle.asRadians(); - float cos = std::cos(rad); - float sin = std::sin(rad); + const float rad = angle.asRadians(); + const float cos = std::cos(rad); + const float sin = std::sin(rad); // clang-format off - Transform rotation(cos, -sin, 0, - sin, cos, 0, - 0, 0, 1); + const Transform rotation(cos, -sin, 0, + sin, cos, 0, + 0, 0, 1); // clang-format on return combine(rotation); @@ -54,14 +54,14 @@ Transform& Transform::rotate(Angle angle) //////////////////////////////////////////////////////////// Transform& Transform::rotate(Angle angle, const Vector2f& center) { - float rad = angle.asRadians(); - float cos = std::cos(rad); - float sin = std::sin(rad); + const float rad = angle.asRadians(); + const float cos = std::cos(rad); + const float sin = std::sin(rad); // clang-format off - Transform rotation(cos, -sin, center.x * (1 - cos) + center.y * sin, - sin, cos, center.y * (1 - cos) - center.x * sin, - 0, 0, 1); + const Transform rotation(cos, -sin, center.x * (1 - cos) + center.y * sin, + sin, cos, center.y * (1 - cos) - center.x * sin, + 0, 0, 1); // clang-format on return combine(rotation); diff --git a/src/SFML/Graphics/Transformable.cpp b/src/SFML/Graphics/Transformable.cpp index 915ae729..9b1f6441 100644 --- a/src/SFML/Graphics/Transformable.cpp +++ b/src/SFML/Graphics/Transformable.cpp @@ -132,15 +132,15 @@ const Transform& Transformable::getTransform() const // Recompute the combined transform if needed if (m_transformNeedUpdate) { - float angle = -m_rotation.asRadians(); - float cosine = std::cos(angle); - float sine = std::sin(angle); - float sxc = m_scale.x * cosine; - float syc = m_scale.y * cosine; - 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; + const float angle = -m_rotation.asRadians(); + const float cosine = std::cos(angle); + const float sine = std::sin(angle); + const float sxc = m_scale.x * cosine; + const float syc = m_scale.y * cosine; + const float sxs = m_scale.x * sine; + const float sys = m_scale.y * sine; + const float tx = -m_origin.x * sxc - m_origin.y * sys + m_position.x; + const float ty = m_origin.x * sxs - m_origin.y * syc + m_position.y; // clang-format off m_transform = Transform( sxc, sys, tx, diff --git a/src/SFML/Graphics/VertexArray.cpp b/src/SFML/Graphics/VertexArray.cpp index aa3be434..9067ec7a 100644 --- a/src/SFML/Graphics/VertexArray.cpp +++ b/src/SFML/Graphics/VertexArray.cpp @@ -109,7 +109,7 @@ FloatRect VertexArray::getBounds() const for (std::size_t i = 1; i < m_vertices.size(); ++i) { - Vector2f position = m_vertices[i].position; + const Vector2f position = m_vertices[i].position; // Update left and right if (position.x < left) diff --git a/src/SFML/Graphics/VertexBuffer.cpp b/src/SFML/Graphics/VertexBuffer.cpp index 296c9391..4c743e19 100644 --- a/src/SFML/Graphics/VertexBuffer.cpp +++ b/src/SFML/Graphics/VertexBuffer.cpp @@ -105,7 +105,7 @@ VertexBuffer::~VertexBuffer() { if (m_buffer) { - TransientContextLock contextLock; + const TransientContextLock contextLock; glCheck(GLEXT_glDeleteBuffers(1, &m_buffer)); } @@ -118,7 +118,7 @@ bool VertexBuffer::create(std::size_t vertexCount) if (!isAvailable()) return false; - TransientContextLock contextLock; + const TransientContextLock contextLock; if (!m_buffer) glCheck(GLEXT_glGenBuffers(1, &m_buffer)); @@ -169,7 +169,7 @@ bool VertexBuffer::update(const Vertex* vertices, std::size_t vertexCount, unsig if (offset && (offset + vertexCount > m_size)) return false; - TransientContextLock contextLock; + const TransientContextLock contextLock; glCheck(GLEXT_glBindBuffer(GLEXT_GL_ARRAY_BUFFER, m_buffer)); @@ -207,7 +207,7 @@ bool VertexBuffer::update([[maybe_unused]] const VertexBuffer& vertexBuffer) if (!m_buffer || !vertexBuffer.m_buffer) return false; - TransientContextLock contextLock; + const TransientContextLock contextLock; // Make sure that extensions are initialized sf::priv::ensureExtensionsInit(); @@ -295,7 +295,7 @@ void VertexBuffer::bind(const VertexBuffer* vertexBuffer) if (!isAvailable()) return; - TransientContextLock lock; + const TransientContextLock lock; glCheck(GLEXT_glBindBuffer(GLEXT_GL_ARRAY_BUFFER, vertexBuffer ? vertexBuffer->m_buffer : 0)); } @@ -334,7 +334,7 @@ bool VertexBuffer::isAvailable() { static const bool available = []() -> bool { - TransientContextLock contextLock; + const TransientContextLock contextLock; // Make sure that extensions are initialized sf::priv::ensureExtensionsInit(); diff --git a/src/SFML/Graphics/View.cpp b/src/SFML/Graphics/View.cpp index e4b2045d..a3a8ae17 100644 --- a/src/SFML/Graphics/View.cpp +++ b/src/SFML/Graphics/View.cpp @@ -157,17 +157,17 @@ const Transform& View::getTransform() const if (!m_transformUpdated) { // Rotation components - float angle = m_rotation.asRadians(); - 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; + const float angle = m_rotation.asRadians(); + const float cosine = std::cos(angle); + const float sine = std::sin(angle); + const float tx = -m_center.x * cosine - m_center.y * sine + m_center.x; + const float ty = m_center.x * sine - m_center.y * cosine + m_center.y; // Projection components - 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; + const float a = 2.f / m_size.x; + const float b = -2.f / m_size.y; + const float c = -a * m_center.x; + const float d = -b * m_center.y; // Rebuild the projection matrix // clang-format off diff --git a/src/SFML/Network/Ftp.cpp b/src/SFML/Network/Ftp.cpp index ed36b40a..6201453d 100644 --- a/src/SFML/Network/Ftp.cpp +++ b/src/SFML/Network/Ftp.cpp @@ -113,9 +113,9 @@ Ftp::DirectoryResponse::DirectoryResponse(const Ftp::Response& response) : Ftp:: 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); + const std::string::size_type begin = getMessage().find('"', 0); + const std::string::size_type end = getMessage().find('"', begin + 1); + m_directory = getMessage().substr(begin + 1, end - begin - 1); } } @@ -330,8 +330,8 @@ Ftp::Response Ftp::upload(const std::string& localFile, const std::string& remot return Response(Response::Status::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; + const std::string::size_type pos = filename.find_last_of("/\\"); if (pos != std::string::npos) filename = filename.substr(pos + 1); @@ -537,7 +537,7 @@ Ftp::Response Ftp::DataChannel::open(Ftp::TransferMode mode) if (response.isOk()) { // Extract the connection address and port from the response - std::string::size_type begin = response.getMessage().find_first_of("0123456789"); + const std::string::size_type begin = response.getMessage().find_first_of("0123456789"); if (begin != std::string::npos) { std::uint8_t data[6] = {0, 0, 0, 0, 0, 0}; @@ -558,8 +558,8 @@ Ftp::Response Ftp::DataChannel::open(Ftp::TransferMode mode) } // Reconstruct connection port and address - auto port = static_cast(data[4] * 256 + data[5]); - IpAddress address(data[0], data[1], data[2], data[3]); + const auto port = static_cast(data[4] * 256 + data[5]); + const IpAddress address(data[0], data[1], data[2], data[3]); // Connect the data channel to the server if (m_dataSocket.connect(address, port) == Socket::Status::Done) diff --git a/src/SFML/Network/Http.cpp b/src/SFML/Network/Http.cpp index a5599588..f9ee0d54 100644 --- a/src/SFML/Network/Http.cpp +++ b/src/SFML/Network/Http.cpp @@ -144,7 +144,7 @@ bool Http::Request::hasField(const std::string& field) const //////////////////////////////////////////////////////////// const std::string& Http::Response::getField(const std::string& field) const { - if (auto it = m_fields.find(toLower(field)); it != m_fields.end()) + if (const auto it = m_fields.find(toLower(field)); it != m_fields.end()) { return it->second; } @@ -244,8 +244,8 @@ void Http::Response::parse(const std::string& data) in.ignore(std::numeric_limits::max(), '\n'); // Copy the actual content data - std::istreambuf_iterator it(in); - std::istreambuf_iterator itEnd; + std::istreambuf_iterator it(in); + const std::istreambuf_iterator itEnd; for (std::size_t i = 0; ((i < length) && (it != itEnd)); ++i) { m_body.push_back(*it); @@ -268,12 +268,12 @@ void Http::Response::parseFields(std::istream& in) std::string line; while (std::getline(in, line) && (line.size() > 2)) { - std::string::size_type pos = line.find(": "); + const std::string::size_type pos = line.find(": "); if (pos != std::string::npos) { // Extract the field name and its value - std::string field = line.substr(0, pos); - std::string value = line.substr(pos + 2); + const std::string field = line.substr(0, pos); + std::string value = line.substr(pos + 2); // Remove any trailing \r if (!value.empty() && (*value.rbegin() == '\r')) @@ -368,7 +368,7 @@ Http::Response Http::sendRequest(const Http::Request& request, Time timeout) if (m_connection.connect(m_host.value(), m_port, timeout) == Socket::Status::Done) { // Convert the request to string and send it through the connected socket - std::string requestStr = toSend.prepare(); + const std::string requestStr = toSend.prepare(); if (!requestStr.empty()) { diff --git a/src/SFML/Network/IpAddress.cpp b/src/SFML/Network/IpAddress.cpp index be4c3e40..ea092d2c 100644 --- a/src/SFML/Network/IpAddress.cpp +++ b/src/SFML/Network/IpAddress.cpp @@ -124,7 +124,7 @@ std::optional IpAddress::getLocalAddress() // UDP connection will not send anything to the network, so this function won't cause any overhead. // Create the socket - SocketHandle sock = socket(PF_INET, SOCK_DGRAM, 0); + const SocketHandle sock = socket(PF_INET, SOCK_DGRAM, 0); if (sock == priv::SocketImpl::invalidSocket()) return std::nullopt; @@ -161,9 +161,9 @@ 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::Method::Get); - Http::Response page = server.sendRequest(request, timeout); + Http server("www.sfml-dev.org"); + const Http::Request request("/ip-provider.php", Http::Request::Method::Get); + const Http::Response page = server.sendRequest(request, timeout); if (page.getStatus() == Http::Response::Status::Ok) return IpAddress::resolve(page.getBody()); diff --git a/src/SFML/Network/Packet.cpp b/src/SFML/Network/Packet.cpp index e6738468..b20ef7c2 100644 --- a/src/SFML/Network/Packet.cpp +++ b/src/SFML/Network/Packet.cpp @@ -65,7 +65,7 @@ void Packet::append(const void* data, std::size_t sizeInBytes) { if (data && (sizeInBytes > 0)) { - std::size_t start = m_data.size(); + const std::size_t start = m_data.size(); m_data.resize(start + sizeInBytes); std::memcpy(&m_data[start], data, sizeInBytes); } @@ -510,7 +510,7 @@ Packet& Packet::operator<<(double data) Packet& Packet::operator<<(const char* data) { // First insert string length - auto length = static_cast(std::strlen(data)); + const auto length = static_cast(std::strlen(data)); *this << length; // Then insert characters @@ -524,7 +524,7 @@ Packet& Packet::operator<<(const char* data) Packet& Packet::operator<<(const std::string& data) { // First insert string length - auto length = static_cast(data.size()); + const auto length = static_cast(data.size()); *this << length; // Then insert characters @@ -539,7 +539,7 @@ Packet& Packet::operator<<(const std::string& data) Packet& Packet::operator<<(const wchar_t* data) { // First insert string length - auto length = static_cast(std::wcslen(data)); + const auto length = static_cast(std::wcslen(data)); *this << length; // Then insert characters @@ -554,13 +554,13 @@ Packet& Packet::operator<<(const wchar_t* data) Packet& Packet::operator<<(const std::wstring& data) { // First insert string length - auto length = static_cast(data.size()); + const auto length = static_cast(data.size()); *this << length; // Then insert characters if (length > 0) { - for (wchar_t c : data) + for (const wchar_t c : data) *this << static_cast(c); } @@ -572,13 +572,13 @@ Packet& Packet::operator<<(const std::wstring& data) Packet& Packet::operator<<(const String& data) { // First insert the string length - auto length = static_cast(data.getSize()); + const auto length = static_cast(data.getSize()); *this << length; // Then insert characters if (length > 0) { - for (unsigned int datum : data) + for (const unsigned int datum : data) *this << datum; } diff --git a/src/SFML/Network/Socket.cpp b/src/SFML/Network/Socket.cpp index a1e0352a..29de8689 100644 --- a/src/SFML/Network/Socket.cpp +++ b/src/SFML/Network/Socket.cpp @@ -80,7 +80,7 @@ void Socket::create() // Don't create the socket if it already exists if (m_socket == priv::SocketImpl::invalidSocket()) { - SocketHandle handle = socket(PF_INET, m_type == Type::Tcp ? SOCK_STREAM : SOCK_DGRAM, 0); + const SocketHandle handle = socket(PF_INET, m_type == Type::Tcp ? SOCK_STREAM : SOCK_DGRAM, 0); if (handle == priv::SocketImpl::invalidSocket()) { diff --git a/src/SFML/Network/SocketSelector.cpp b/src/SFML/Network/SocketSelector.cpp index bc8bf1c8..6c436d86 100644 --- a/src/SFML/Network/SocketSelector.cpp +++ b/src/SFML/Network/SocketSelector.cpp @@ -73,7 +73,7 @@ SocketSelector::~SocketSelector() = default; //////////////////////////////////////////////////////////// void SocketSelector::add(Socket& socket) { - SocketHandle handle = socket.getHandle(); + const SocketHandle handle = socket.getHandle(); if (handle != priv::SocketImpl::invalidSocket()) { @@ -115,7 +115,7 @@ void SocketSelector::add(Socket& socket) //////////////////////////////////////////////////////////// void SocketSelector::remove(Socket& socket) { - SocketHandle handle = socket.getHandle(); + const SocketHandle handle = socket.getHandle(); if (handle != priv::SocketImpl::invalidSocket()) { @@ -163,7 +163,7 @@ bool SocketSelector::wait(Time timeout) // Wait until one of the sockets is ready for reading, or timeout is reached // The first parameter is ignored on Windows - int count = select(m_impl->maxSocket + 1, &m_impl->socketsReady, nullptr, nullptr, timeout != Time::Zero ? &time : nullptr); + const int count = select(m_impl->maxSocket + 1, &m_impl->socketsReady, nullptr, nullptr, timeout != Time::Zero ? &time : nullptr); return count > 0; } @@ -172,7 +172,7 @@ bool SocketSelector::wait(Time timeout) //////////////////////////////////////////////////////////// bool SocketSelector::isReady(Socket& socket) const { - SocketHandle handle = socket.getHandle(); + const SocketHandle handle = socket.getHandle(); if (handle != priv::SocketImpl::invalidSocket()) { diff --git a/src/SFML/Network/TcpListener.cpp b/src/SFML/Network/TcpListener.cpp index 40bdaa8a..dbf015f7 100644 --- a/src/SFML/Network/TcpListener.cpp +++ b/src/SFML/Network/TcpListener.cpp @@ -116,7 +116,7 @@ Socket::Status TcpListener::accept(TcpSocket& socket) // Accept a new connection sockaddr_in address; priv::SocketImpl::AddrLength length = sizeof(address); - SocketHandle remote = ::accept(getHandle(), reinterpret_cast(&address), &length); + const 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 890a5ef4..76e2b8fa 100644 --- a/src/SFML/Network/TcpSocket.cpp +++ b/src/SFML/Network/TcpSocket.cpp @@ -145,7 +145,7 @@ Socket::Status TcpSocket::connect(const IpAddress& remoteAddress, unsigned short // ----- We're using a timeout: we'll need a few tricks to make it work ----- // Save the previous blocking state - bool blocking = isBlocking(); + const bool blocking = isBlocking(); // Switch to non-blocking to enable our connection timeout if (blocking) @@ -257,7 +257,7 @@ Socket::Status TcpSocket::send(const void* data, std::size_t size, std::size_t& // Check for errors if (result < 0) { - Status status = priv::SocketImpl::getErrorStatus(); + const Status status = priv::SocketImpl::getErrorStatus(); if ((status == Status::NotReady) && sent) return Status::Partial; @@ -286,7 +286,7 @@ Socket::Status TcpSocket::receive(void* data, std::size_t size, std::size_t& rec #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wuseless-cast" // Receive a chunk of bytes - int sizeReceived = static_cast( + const int sizeReceived = static_cast( recv(getHandle(), static_cast(data), static_cast(size), flags)); #pragma GCC diagnostic pop @@ -345,10 +345,10 @@ Socket::Status TcpSocket::send(Packet& packet) #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); + std::size_t sent; + const 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 @@ -381,8 +381,8 @@ Socket::Status TcpSocket::receive(Packet& 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; - Status status = receive(data, sizeof(m_pendingPacket.Size) - m_pendingPacket.SizeReceived, received); + char* data = reinterpret_cast(&m_pendingPacket.Size) + m_pendingPacket.SizeReceived; + const Status status = receive(data, sizeof(m_pendingPacket.Size) - m_pendingPacket.SizeReceived, received); m_pendingPacket.SizeReceived += received; if (status != Status::Done) @@ -403,8 +403,8 @@ Socket::Status TcpSocket::receive(Packet& packet) while (m_pendingPacket.Data.size() < packetSize) { // Receive a chunk of data - std::size_t sizeToGet = std::min(packetSize - m_pendingPacket.Data.size(), sizeof(buffer)); - Status status = receive(buffer, sizeToGet, received); + const std::size_t sizeToGet = std::min(packetSize - m_pendingPacket.Data.size(), sizeof(buffer)); + const Status status = receive(buffer, sizeToGet, received); if (status != Status::Done) return status; diff --git a/src/SFML/Network/UdpSocket.cpp b/src/SFML/Network/UdpSocket.cpp index 5e1ea105..f73d2728 100644 --- a/src/SFML/Network/UdpSocket.cpp +++ b/src/SFML/Network/UdpSocket.cpp @@ -117,7 +117,7 @@ Socket::Status UdpSocket::send(const void* data, std::size_t size, const IpAddre #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( + const int sent = static_cast( sendto(getHandle(), static_cast(data), static_cast(size), @@ -160,7 +160,7 @@ Socket::Status UdpSocket::receive(void* data, #pragma GCC diagnostic ignored "-Wuseless-cast" // Receive a chunk of bytes priv::SocketImpl::AddrLength addressSize = sizeof(address); - int sizeReceived = static_cast( + const int sizeReceived = static_cast( recvfrom(getHandle(), static_cast(data), static_cast(size), @@ -208,8 +208,8 @@ Socket::Status UdpSocket::receive(Packet& packet, std::optional& remo // See the detailed comment in send(Packet) above. // Receive the datagram - std::size_t received = 0; - Status status = receive(m_buffer.data(), m_buffer.size(), received, remoteAddress, remotePort); + std::size_t received = 0; + const 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 1eeb626c..b3514abd 100644 --- a/src/SFML/Network/Unix/SocketImpl.cpp +++ b/src/SFML/Network/Unix/SocketImpl.cpp @@ -71,7 +71,7 @@ void SocketImpl::close(SocketHandle sock) //////////////////////////////////////////////////////////// void SocketImpl::setBlocking(SocketHandle sock, bool block) { - int status = fcntl(sock, F_GETFL); + const int status = fcntl(sock, F_GETFL); if (block) { if (fcntl(sock, F_SETFL, status & ~O_NONBLOCK) == -1) diff --git a/src/SFML/System/Err.cpp b/src/SFML/System/Err.cpp index bd81ae8c..828d022b 100644 --- a/src/SFML/System/Err.cpp +++ b/src/SFML/System/Err.cpp @@ -84,7 +84,7 @@ private: if (pbase() != pptr()) { // Print the contents of the write buffer into the standard error output - auto size = static_cast(pptr() - pbase()); + const auto size = static_cast(pptr() - pbase()); fwrite(pbase(), 1, size, stderr); // Reset the pointer position to the beginning of the write buffer diff --git a/src/SFML/System/FileInputStream.cpp b/src/SFML/System/FileInputStream.cpp index eb85c0d0..cc6958ea 100644 --- a/src/SFML/System/FileInputStream.cpp +++ b/src/SFML/System/FileInputStream.cpp @@ -134,9 +134,9 @@ std::int64_t FileInputStream::getSize() #else if (m_file) { - std::int64_t position = tell(); + const std::int64_t position = tell(); std::fseek(m_file.get(), 0, SEEK_END); - std::int64_t size = tell(); + const std::int64_t size = tell(); if (seek(position) == -1) return -1; diff --git a/src/SFML/System/MemoryInputStream.cpp b/src/SFML/System/MemoryInputStream.cpp index 7208fd96..e24ce5f2 100644 --- a/src/SFML/System/MemoryInputStream.cpp +++ b/src/SFML/System/MemoryInputStream.cpp @@ -51,8 +51,8 @@ std::int64_t MemoryInputStream::read(void* data, std::int64_t size) if (!m_data) return -1; - std::int64_t endPosition = m_offset + size; - std::int64_t count = endPosition <= m_size ? size : m_size - m_offset; + const std::int64_t endPosition = m_offset + size; + const std::int64_t count = endPosition <= m_size ? size : m_size - m_offset; if (count > 0) { diff --git a/src/SFML/System/String.cpp b/src/SFML/System/String.cpp index 4c0e9949..cf2d95ae 100644 --- a/src/SFML/System/String.cpp +++ b/src/SFML/System/String.cpp @@ -70,7 +70,7 @@ String::String(const char* ansiString, const std::locale& locale) { if (ansiString) { - std::size_t length = strlen(ansiString); + const std::size_t length = strlen(ansiString); if (length > 0) { m_string.reserve(length + 1); @@ -93,7 +93,7 @@ String::String(const wchar_t* wideString) { if (wideString) { - std::size_t length = std::wcslen(wideString); + const std::size_t length = std::wcslen(wideString); if (length > 0) { m_string.reserve(length + 1); @@ -276,9 +276,9 @@ 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); + const std::size_t step = replaceWith.getSize(); + const std::size_t len = searchFor.getSize(); + std::size_t pos = find(searchFor); // Replace each occurrence of search while (pos != InvalidPos) diff --git a/src/SFML/Window/Context.cpp b/src/SFML/Window/Context.cpp index a3ee080b..740a6543 100644 --- a/src/SFML/Window/Context.cpp +++ b/src/SFML/Window/Context.cpp @@ -68,7 +68,7 @@ Context::~Context() //////////////////////////////////////////////////////////// bool Context::setActive(bool active) { - bool result = m_context->setActive(active); + const bool result = m_context->setActive(active); if (result) ContextImpl::currentContext = (active ? this : nullptr); diff --git a/src/SFML/Window/GlContext.cpp b/src/SFML/Window/GlContext.cpp index 4c3e3100..e44fa5db 100644 --- a/src/SFML/Window/GlContext.cpp +++ b/src/SFML/Window/GlContext.cpp @@ -334,7 +334,7 @@ void loadExtensions() // 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); + const 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] == '.') && @@ -363,7 +363,7 @@ void GlContext::initResource() using GlContextImpl::sharedContext; // Protect from concurrent access - std::lock_guard lock(mutex); + const std::lock_guard lock(mutex); // If this is the very first resource, trigger the global context initialization if (resourceCount == 0) @@ -400,7 +400,7 @@ void GlContext::cleanupResource() using GlContextImpl::sharedContext; // Protect from concurrent access - std::lock_guard lock(mutex); + const std::lock_guard lock(mutex); // Decrement the resources counter --resourceCount; @@ -481,7 +481,7 @@ std::unique_ptr GlContext::create() // Make sure that there's an active context (context creation may need extensions, and thus a valid context) assert(sharedContext != nullptr); - std::lock_guard lock(mutex); + const std::lock_guard lock(mutex); std::unique_ptr context; @@ -514,7 +514,7 @@ std::unique_ptr GlContext::create(const ContextSettings& settings, co // Make sure that there's an active context (context creation may need extensions, and thus a valid context) assert(sharedContext != nullptr); - std::lock_guard lock(mutex); + const std::lock_guard lock(mutex); // If resourceCount is 1 we know that we are inside sf::Context or sf::Window // Only in this situation we allow the user to indirectly re-create the shared context as a core context @@ -524,7 +524,7 @@ std::unique_ptr GlContext::create(const ContextSettings& settings, co !(sharedContext->m_settings.attributeFlags & ContextSettings::Core)) { // Re-create our shared context as a core context - ContextSettings sharedSettings(0, 0, 0, settings.majorVersion, settings.minorVersion, settings.attributeFlags); + const ContextSettings sharedSettings(0, 0, 0, settings.majorVersion, settings.minorVersion, settings.attributeFlags); sharedContext = std::make_unique(nullptr, sharedSettings, Vector2u(1, 1)); sharedContext->initialize(sharedSettings); @@ -565,7 +565,7 @@ std::unique_ptr GlContext::create(const ContextSettings& settings, co // Make sure that there's an active context (context creation may need extensions, and thus a valid context) assert(sharedContext != nullptr); - std::lock_guard lock(mutex); + const std::lock_guard lock(mutex); // If resourceCount is 1 we know that we are inside sf::Context or sf::Window // Only in this situation we allow the user to indirectly re-create the shared context as a core context @@ -575,7 +575,7 @@ std::unique_ptr GlContext::create(const ContextSettings& settings, co !(sharedContext->m_settings.attributeFlags & ContextSettings::Core)) { // Re-create our shared context as a core context - ContextSettings sharedSettings(0, 0, 0, settings.majorVersion, settings.minorVersion, settings.attributeFlags); + const ContextSettings sharedSettings(0, 0, 0, settings.majorVersion, settings.minorVersion, settings.attributeFlags); sharedContext = std::make_unique(nullptr, sharedSettings, Vector2u(1, 1)); sharedContext->initialize(sharedSettings); @@ -616,7 +616,7 @@ bool GlContext::isExtensionAvailable(const char* name) //////////////////////////////////////////////////////////// GlFunctionPointer GlContext::getFunction(const char* name) { - std::lock_guard lock(GlContextImpl::mutex); + const std::lock_guard lock(GlContextImpl::mutex); return ContextType::getFunction(name); } @@ -670,7 +670,7 @@ bool GlContext::setActive(bool active) { if (m_id != currentContext.id) { - std::lock_guard lock(mutex); + const std::lock_guard lock(mutex); // Activate the context if (makeCurrent(true)) @@ -695,7 +695,7 @@ bool GlContext::setActive(bool active) { if (m_id == currentContext.id) { - std::lock_guard lock(mutex); + const std::lock_guard lock(mutex); // Deactivate the context if (makeCurrent(false)) @@ -947,8 +947,8 @@ void GlContext::initialize(const ContextSettings& requestedSettings) void GlContext::checkSettings(const ContextSettings& requestedSettings) const { // Perform checks to inform the user if they are getting a context they might not have expected - int version = static_cast(m_settings.majorVersion * 10u + m_settings.minorVersion); - int requestedVersion = static_cast(requestedSettings.majorVersion * 10u + requestedSettings.minorVersion); + const int version = static_cast(m_settings.majorVersion * 10u + m_settings.minorVersion); + const int requestedVersion = static_cast(requestedSettings.majorVersion * 10u + requestedSettings.minorVersion); if ((m_settings.attributeFlags != requestedSettings.attributeFlags) || (version < requestedVersion) || (m_settings.stencilBits < requestedSettings.stencilBits) || diff --git a/src/SFML/Window/OSX/ClipboardImpl.mm b/src/SFML/Window/OSX/ClipboardImpl.mm index 55d7ddef..a1d1c2ab 100644 --- a/src/SFML/Window/OSX/ClipboardImpl.mm +++ b/src/SFML/Window/OSX/ClipboardImpl.mm @@ -38,12 +38,12 @@ namespace sf::priv //////////////////////////////////////////////////////////// String ClipboardImpl::getString() { - AutoreleasePool pool; - NSPasteboard* pboard = [NSPasteboard generalPasteboard]; - NSString* data = [pboard stringForType:NSPasteboardTypeString]; + const AutoreleasePool pool; + NSPasteboard* const pboard = [NSPasteboard generalPasteboard]; + NSString* const data = [pboard stringForType:NSPasteboardTypeString]; - char const* utf8 = [data cStringUsingEncoding:NSUTF8StringEncoding]; - NSUInteger length = [data lengthOfBytesUsingEncoding:NSUTF8StringEncoding]; + char const* utf8 = [data cStringUsingEncoding:NSUTF8StringEncoding]; + const NSUInteger length = [data lengthOfBytesUsingEncoding:NSUTF8StringEncoding]; return String::fromUtf8(utf8, utf8 + length); } @@ -52,11 +52,14 @@ String ClipboardImpl::getString() //////////////////////////////////////////////////////////// void ClipboardImpl::setString(const String& text) { - AutoreleasePool pool; + const AutoreleasePool pool; std::basic_string utf8 = text.toUtf8(); - NSString* data = [[NSString alloc] initWithBytes:utf8.data() length:utf8.length() encoding:NSUTF8StringEncoding]; + NSString* const data = [[NSString alloc] + initWithBytes:utf8.data() + length:utf8.length() + encoding:NSUTF8StringEncoding]; - NSPasteboard* pboard = [NSPasteboard generalPasteboard]; + NSPasteboard* const pboard = [NSPasteboard generalPasteboard]; [pboard declareTypes:@[NSPasteboardTypeString] owner:nil]; [pboard setString:data forType:NSPasteboardTypeString]; diff --git a/src/SFML/Window/OSX/CursorImpl.mm b/src/SFML/Window/OSX/CursorImpl.mm index afd43f33..e21c9a9a 100644 --- a/src/SFML/Window/OSX/CursorImpl.mm +++ b/src/SFML/Window/OSX/CursorImpl.mm @@ -57,7 +57,7 @@ CursorImpl::CursorImpl() = default; //////////////////////////////////////////////////////////// CursorImpl::~CursorImpl() { - AutoreleasePool pool; + const AutoreleasePool pool; [m_cursor release]; } @@ -65,16 +65,16 @@ CursorImpl::~CursorImpl() //////////////////////////////////////////////////////////// bool CursorImpl::loadFromPixels(const std::uint8_t* pixels, Vector2u size, Vector2u hotspot) { - AutoreleasePool pool; + const AutoreleasePool pool; if (m_cursor) { [m_cursor release]; m_cursor = nil; } - NSSize nssize = NSMakeSize(size.x, size.y); - NSImage* image = [NSImage imageWithRawData:pixels andSize:nssize]; - NSPoint nshotspot = NSMakePoint(hotspot.x, hotspot.y); + const NSSize nssize = NSMakeSize(size.x, size.y); + NSImage* const image = [NSImage imageWithRawData:pixels andSize:nssize]; + const NSPoint nshotspot = NSMakePoint(hotspot.x, hotspot.y); m_cursor = [[NSCursor alloc] initWithImage:image hotSpot:nshotspot]; @@ -84,8 +84,8 @@ bool CursorImpl::loadFromPixels(const std::uint8_t* pixels, Vector2u size, Vecto //////////////////////////////////////////////////////////// bool CursorImpl::loadFromSystem(Cursor::Type type) { - AutoreleasePool pool; - NSCursor* newCursor = nil; + const AutoreleasePool pool; + NSCursor* newCursor = nil; // clang-format off switch (type) diff --git a/src/SFML/Window/OSX/HIDInputManager.mm b/src/SFML/Window/OSX/HIDInputManager.mm index 758cce97..d31c7fe4 100644 --- a/src/SFML/Window/OSX/HIDInputManager.mm +++ b/src/SFML/Window/OSX/HIDInputManager.mm @@ -689,7 +689,7 @@ String HIDInputManager::getDescription(Keyboard::Scancode code) default: { // Phase 2: Try to convert the key to unicode - UniChar unicode = toUnicode(localize(code)); + const UniChar unicode = toUnicode(localize(code)); if (unicode != 0x00) return String(static_cast(unicode)); } @@ -705,8 +705,8 @@ String HIDInputManager::getDescription(Keyboard::Scancode code) HIDInputManager::HIDInputManager() { // Create an HID Manager reference - m_manager = IOHIDManagerCreate(kCFAllocatorDefault, kIOHIDOptionsTypeNone); - IOReturn openStatus = IOHIDManagerOpen(m_manager, kIOHIDOptionsTypeNone); + m_manager = IOHIDManagerCreate(kCFAllocatorDefault, kIOHIDOptionsTypeNone); + const IOReturn openStatus = IOHIDManagerOpen(m_manager, kIOHIDOptionsTypeNone); if (openStatus != kIOReturnSuccess) { @@ -754,7 +754,7 @@ void HIDInputManager::initializeKeyboard() return; } - auto* keyboards = static_cast(underlying); // Toll-Free Bridge + auto* const keyboards = static_cast(underlying); // Toll-Free Bridge for (id keyboard in keyboards) loadKeyboard(static_cast(keyboard)); @@ -775,7 +775,7 @@ void HIDInputManager::loadKeyboard(IOHIDDeviceRef keyboard) return; } - auto* keys = static_cast(underlying); // Toll-Free Bridge + auto* const keys = static_cast(underlying); // Toll-Free Bridge for (id key in keys) { auto* elem = static_cast(key); @@ -790,8 +790,8 @@ void HIDInputManager::loadKeyboard(IOHIDDeviceRef keyboard) //////////////////////////////////////////////////////////// void HIDInputManager::loadKey(IOHIDElementRef key) { - std::uint32_t usage = IOHIDElementGetUsage(key); - Keyboard::Scancode code = usageToScancode(usage); + const std::uint32_t usage = IOHIDElementGetUsage(key); + const Keyboard::Scancode code = usageToScancode(usage); if (code != Keyboard::Scan::Unknown) { CFRetain(key); @@ -826,8 +826,8 @@ void HIDInputManager::buildMappings() // virtual code to a localized Key. for (int i = 0; i < static_cast(Keyboard::Scan::ScancodeCount); ++i) { - auto scan = static_cast(i); - std::uint8_t virtualCode = scanToVirtualCode(scan); + const auto scan = static_cast(i); + const std::uint8_t virtualCode = scanToVirtualCode(scan); if (virtualCode == unknownVirtualCode) continue; @@ -871,16 +871,16 @@ void HIDInputManager::buildMappings() std::uint32_t const modifiers = 0x100; // no modifiers // Use current layout for translation - OSStatus error = UCKeyTranslate(layout, - virtualCode, - kUCKeyActionDown, - modifiers, - LMGetKbdType(), - kUCKeyTranslateNoDeadKeysMask, - &deadKeyState, - maxLength, - &length, - string); + const OSStatus error = UCKeyTranslate(layout, + virtualCode, + kUCKeyActionDown, + modifiers, + LMGetKbdType(), + kUCKeyTranslateNoDeadKeysMask, + &deadKeyState, + maxLength, + &length, + string); if (error != noErr) { diff --git a/src/SFML/Window/OSX/InputImpl.mm b/src/SFML/Window/OSX/InputImpl.mm index 4749c309..41ae814d 100644 --- a/src/SFML/Window/OSX/InputImpl.mm +++ b/src/SFML/Window/OSX/InputImpl.mm @@ -55,7 +55,7 @@ namespace sf::priv //////////////////////////////////////////////////////////// SFOpenGLView* getSFOpenGLViewFromSFMLWindow(const WindowBase& window) { - id nsHandle = static_cast(window.getSystemHandle()); + const id nsHandle = static_cast(window.getSystemHandle()); // Get our SFOpenGLView from ... SFOpenGLView* view = nil; @@ -70,7 +70,7 @@ SFOpenGLView* getSFOpenGLViewFromSFMLWindow(const WindowBase& window) { if ([view isKindOfClass:[NSView class]]) { - NSArray* subviews = [view subviews]; + NSArray* const subviews = [view subviews]; for (NSView* subview in subviews) { if ([subview isKindOfClass:[SFOpenGLView class]]) @@ -91,7 +91,7 @@ SFOpenGLView* getSFOpenGLViewFromSFMLWindow(const WindowBase& window) else if ([nsHandle isKindOfClass:[NSView class]]) { // If system handle is a view then from a subview of kind SFOpenGLView. - NSArray* subviews = [nsHandle subviews]; + NSArray* const subviews = [nsHandle subviews]; for (NSView* subview in subviews) { if ([subview isKindOfClass:[SFOpenGLView class]]) @@ -120,7 +120,7 @@ SFOpenGLView* getSFOpenGLViewFromSFMLWindow(const WindowBase& window) //////////////////////////////////////////////////////////// bool InputImpl::isKeyPressed(Keyboard::Key key) { - AutoreleasePool pool; + const AutoreleasePool pool; return HIDInputManager::getInstance().isKeyPressed(key); } @@ -163,9 +163,9 @@ void InputImpl::setVirtualKeyboardVisible(bool /*visible*/) //////////////////////////////////////////////////////////// bool InputImpl::isMouseButtonPressed(Mouse::Button button) { - AutoreleasePool pool; - NSUInteger state = [NSEvent pressedMouseButtons]; - NSUInteger flag = 1 << button; + const AutoreleasePool pool; + const NSUInteger state = [NSEvent pressedMouseButtons]; + const NSUInteger flag = 1 << button; return (state & flag) != 0; } @@ -173,12 +173,12 @@ bool InputImpl::isMouseButtonPressed(Mouse::Button button) //////////////////////////////////////////////////////////// Vector2i InputImpl::getMousePosition() { - AutoreleasePool pool; + const AutoreleasePool pool; // Reverse Y axis to match SFML coord. NSPoint pos = [NSEvent mouseLocation]; pos.y = sf::VideoMode::getDesktopMode().size.y - pos.y; - int scale = static_cast([[NSScreen mainScreen] backingScaleFactor]); + const int scale = static_cast([[NSScreen mainScreen] backingScaleFactor]); return Vector2i(static_cast(pos.x), static_cast(pos.y)) * scale; } @@ -186,17 +186,17 @@ Vector2i InputImpl::getMousePosition() //////////////////////////////////////////////////////////// Vector2i InputImpl::getMousePosition(const WindowBase& relativeTo) { - AutoreleasePool pool; - SFOpenGLView* view = getSFOpenGLViewFromSFMLWindow(relativeTo); + const AutoreleasePool pool; + SFOpenGLView* const view = getSFOpenGLViewFromSFMLWindow(relativeTo); // No view ? if (view == nil) return Vector2i(); // Use -cursorPositionFromEvent: with nil. - NSPoint pos = [view cursorPositionFromEvent:nil]; + const NSPoint pos = [view cursorPositionFromEvent:nil]; - int scale = static_cast([view displayScaleFactor]); + const int scale = static_cast([view displayScaleFactor]); return Vector2i(static_cast(pos.x), static_cast(pos.y)) * scale; } @@ -204,10 +204,10 @@ Vector2i InputImpl::getMousePosition(const WindowBase& relativeTo) //////////////////////////////////////////////////////////// void InputImpl::setMousePosition(const Vector2i& position) { - AutoreleasePool pool; + const 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); + const int scale = static_cast([[NSScreen mainScreen] backingScaleFactor]); + const CGPoint pos = CGPointMake(position.x / scale, position.y / scale); // Place the cursor. CGEventRef event = CGEventCreateMouseEvent(nullptr, @@ -223,17 +223,17 @@ void InputImpl::setMousePosition(const Vector2i& position) //////////////////////////////////////////////////////////// void InputImpl::setMousePosition(const Vector2i& position, const WindowBase& relativeTo) { - AutoreleasePool pool; - SFOpenGLView* view = getSFOpenGLViewFromSFMLWindow(relativeTo); + const AutoreleasePool pool; + SFOpenGLView* const 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]; + const 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 9f73ab65..d9821202 100644 --- a/src/SFML/Window/OSX/JoystickImpl.cpp +++ b/src/SFML/Window/OSX/JoystickImpl.cpp @@ -46,9 +46,9 @@ bool joystickButtonSortPredicate(IOHIDElementRef b1, IOHIDElementRef b2) // Convert a CFStringRef to std::string std::string stringFromCFString(CFStringRef cfString) { - CFIndex length = CFStringGetLength(cfString); + const CFIndex length = CFStringGetLength(cfString); std::vector str(static_cast(length)); - CFIndex maxSize = CFStringGetMaximumSizeForEncoding(length, kCFStringEncodingUTF8); + const CFIndex maxSize = CFStringGetMaximumSizeForEncoding(length, kCFStringEncodingUTF8); CFStringGetCString(cfString, str.data(), maxSize, kCFStringEncodingUTF8); return str.data(); } @@ -110,8 +110,8 @@ void JoystickImpl::cleanup() //////////////////////////////////////////////////////////// bool JoystickImpl::isConnected(unsigned int index) { - AutoreleasePool pool; - bool state = false; // Is the index-th joystick connected? + const AutoreleasePool pool; + bool state = false; // Is the index-th joystick connected? // First, let's check if the device was previously detected: if (m_locationIDs[index] != 0) @@ -134,7 +134,7 @@ bool JoystickImpl::isConnected(unsigned int index) } - unsigned int connectedCount = HIDJoystickManager::getInstance().getJoystickCount(); + const unsigned int connectedCount = HIDJoystickManager::getInstance().getJoystickCount(); if (connectedCount > openedCount) { @@ -143,7 +143,7 @@ bool JoystickImpl::isConnected(unsigned int index) if (devices != nullptr) { - CFIndex size = CFSetGetCount(devices); + const CFIndex size = CFSetGetCount(devices); if (size > 0) { std::vector array(static_cast(size)); // array of IOHIDDeviceRef @@ -155,7 +155,7 @@ bool JoystickImpl::isConnected(unsigned int index) for (CFIndex didx(0); !state && didx < size; ++didx) { auto* d = static_cast(const_cast(array[static_cast(didx)])); - Location dloc = HIDInputManager::getLocationID(d); + const Location dloc = HIDInputManager::getLocationID(d); bool foundJ = false; for (unsigned int j(0); !foundJ && j < Joystick::Count; ++j) @@ -186,10 +186,10 @@ bool JoystickImpl::isConnected(unsigned int index) //////////////////////////////////////////////////////////// bool JoystickImpl::open(unsigned int index) { - AutoreleasePool pool; - m_index = index; - m_hat = nullptr; - Location deviceLoc = m_locationIDs[index]; // The device we need to load + const AutoreleasePool pool; + m_index = index; + m_hat = nullptr; + const Location deviceLoc = m_locationIDs[index]; // The device we need to load // Get all devices CFSetRef devices = HIDJoystickManager::getInstance().copyJoysticks(); @@ -197,7 +197,7 @@ bool JoystickImpl::open(unsigned int index) return false; // Get a usable copy of the joysticks devices. - CFIndex joysticksCount = CFSetGetCount(devices); + const CFIndex joysticksCount = CFSetGetCount(devices); std::vector devicesArray(static_cast(joysticksCount)); CFSetGetValues(devices, devicesArray.data()); @@ -230,7 +230,7 @@ bool JoystickImpl::open(unsigned int index) } // Go through all connected elements. - CFIndex elementsCount = CFArrayGetCount(elements); + const CFIndex elementsCount = CFArrayGetCount(elements); for (int i = 0; i < elementsCount; ++i) { auto* element = static_cast(const_cast(CFArrayGetValueAtIndex(elements, i))); @@ -270,8 +270,8 @@ bool JoystickImpl::open(unsigned int index) // We assume this model here as well. Hence, with 4 switches and intermediate // positions we have 8 values (0-7) plus the "null" state (8). { - CFIndex min = IOHIDElementGetLogicalMin(element); - CFIndex max = IOHIDElementGetLogicalMax(element); + const CFIndex min = IOHIDElementGetLogicalMin(element); + const CFIndex max = IOHIDElementGetLogicalMax(element); if (min != 0 || max != 7) { @@ -346,7 +346,7 @@ bool JoystickImpl::open(unsigned int index) //////////////////////////////////////////////////////////// void JoystickImpl::close() { - AutoreleasePool pool; + const AutoreleasePool pool; for (IOHIDElementRef iohidElementRef : m_buttons) CFRelease(iohidElementRef); @@ -371,8 +371,8 @@ void JoystickImpl::close() //////////////////////////////////////////////////////////// JoystickCaps JoystickImpl::getCapabilities() const { - AutoreleasePool pool; - JoystickCaps caps; + const AutoreleasePool pool; + JoystickCaps caps; // Buttons: caps.buttonCount = static_cast(m_buttons.size()); @@ -391,7 +391,7 @@ JoystickCaps JoystickImpl::getCapabilities() const //////////////////////////////////////////////////////////// Joystick::Identification JoystickImpl::getIdentification() const { - AutoreleasePool pool; + const AutoreleasePool pool; return m_identification; } @@ -399,7 +399,7 @@ Joystick::Identification JoystickImpl::getIdentification() const //////////////////////////////////////////////////////////// JoystickState JoystickImpl::update() { - AutoreleasePool pool; + const AutoreleasePool pool; static constexpr JoystickState disconnectedState; // return this if joystick was disconnected JoystickState state; // otherwise return that state.connected = true; @@ -408,7 +408,7 @@ JoystickState JoystickImpl::update() // by the joystick manager. So we don't release buttons nor axes here. // First, let's determine if the joystick is still connected - Location selfLoc = m_locationIDs[m_index]; + const Location selfLoc = m_locationIDs[m_index]; // Get all devices CFSetRef devices = HIDJoystickManager::getInstance().copyJoysticks(); @@ -416,7 +416,7 @@ JoystickState JoystickImpl::update() return disconnectedState; // Get a usable copy of the joysticks devices. - CFIndex joysticksCount = CFSetGetCount(devices); + const CFIndex joysticksCount = CFSetGetCount(devices); std::vector devicesArray(static_cast(joysticksCount)); CFSetGetValues(devices, devicesArray.data()); @@ -475,12 +475,12 @@ 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. - auto physicalMax = static_cast(IOHIDElementGetPhysicalMax(iohidElementRef)); - auto physicalMin = static_cast(IOHIDElementGetPhysicalMin(iohidElementRef)); - double scaledMin = -100; - double scaledMax = 100; - double physicalValue = IOHIDValueGetScaledValue(value, kIOHIDValueScaleTypePhysical); - auto scaledValue = static_cast( + const auto physicalMax = static_cast(IOHIDElementGetPhysicalMax(iohidElementRef)); + const auto physicalMin = static_cast(IOHIDElementGetPhysicalMin(iohidElementRef)); + const double scaledMin = -100; + const double scaledMax = 100; + const double physicalValue = IOHIDValueGetScaledValue(value, kIOHIDValueScaleTypePhysical); + const auto scaledValue = static_cast( (((physicalValue - physicalMin) * (scaledMax - scaledMin)) / (physicalMax - physicalMin)) + scaledMin); state.axes[axis] = scaledValue; } @@ -502,7 +502,7 @@ JoystickState JoystickImpl::update() return disconnectedState; } - CFIndex raw = IOHIDValueGetIntegerValue(value); + const CFIndex raw = IOHIDValueGetIntegerValue(value); // Load PovX switch (raw) diff --git a/src/SFML/Window/OSX/SFContext.mm b/src/SFML/Window/OSX/SFContext.mm index e5535aa4..2b56b6de 100644 --- a/src/SFML/Window/OSX/SFContext.mm +++ b/src/SFML/Window/OSX/SFContext.mm @@ -43,7 +43,7 @@ namespace sf::priv //////////////////////////////////////////////////////////// SFContext::SFContext(SFContext* shared) { - AutoreleasePool pool; + const AutoreleasePool pool; // Create the context createContext(shared, VideoMode::getDesktopMode().bitsPerPixel, ContextSettings(0, 0, 0)); } @@ -52,7 +52,7 @@ SFContext::SFContext(SFContext* shared) //////////////////////////////////////////////////////////// SFContext::SFContext(SFContext* shared, const ContextSettings& settings, const WindowImpl& owner, unsigned int bitsPerPixel) { - AutoreleasePool pool; + const AutoreleasePool pool; // Create the context. createContext(shared, bitsPerPixel, settings); @@ -65,7 +65,7 @@ SFContext::SFContext(SFContext* shared, const ContextSettings& settings, const W //////////////////////////////////////////////////////////// SFContext::SFContext(SFContext* shared, const ContextSettings& settings, const Vector2u& size) { - AutoreleasePool pool; + const AutoreleasePool pool; // Ensure the process is setup in order to create a valid window. WindowImplCocoa::setUpProcess(); @@ -88,7 +88,7 @@ SFContext::SFContext(SFContext* shared, const ContextSettings& settings, const V //////////////////////////////////////////////////////////// SFContext::~SFContext() { - AutoreleasePool pool; + const AutoreleasePool pool; // Notify unshared OpenGL resources of context destruction cleanupUnsharedResources(); @@ -107,8 +107,8 @@ SFContext::~SFContext() //////////////////////////////////////////////////////////// GlFunctionPointer SFContext::getFunction(const char* name) { - AutoreleasePool pool; - static void* image = nullptr; + const AutoreleasePool pool; + static void* image = nullptr; if (!image) image = dlopen("/System/Library/Frameworks/OpenGL.framework/Versions/Current/OpenGL", RTLD_LAZY); @@ -120,7 +120,7 @@ GlFunctionPointer SFContext::getFunction(const char* name) //////////////////////////////////////////////////////////// bool SFContext::makeCurrent(bool current) { - AutoreleasePool pool; + const AutoreleasePool pool; if (current) { [m_context makeCurrentContext]; @@ -137,7 +137,7 @@ bool SFContext::makeCurrent(bool current) //////////////////////////////////////////////////////////// void SFContext::display() { - AutoreleasePool pool; + const AutoreleasePool pool; [m_context flushBuffer]; } @@ -145,8 +145,8 @@ void SFContext::display() //////////////////////////////////////////////////////////// void SFContext::setVerticalSyncEnabled(bool enabled) { - AutoreleasePool pool; - GLint swapInterval = enabled ? 1 : 0; + const AutoreleasePool pool; + const GLint swapInterval = enabled ? 1 : 0; [m_context setValues:&swapInterval forParameter:NSOpenGLCPSwapInterval]; } @@ -155,7 +155,7 @@ void SFContext::setVerticalSyncEnabled(bool enabled) //////////////////////////////////////////////////////////// void SFContext::createContext(SFContext* shared, unsigned int bitsPerPixel, const ContextSettings& settings) { - AutoreleasePool pool; + const AutoreleasePool pool; // Save the settings. (OpenGL version is updated elsewhere.) m_settings = settings; @@ -215,7 +215,7 @@ void SFContext::createContext(SFContext* shared, unsigned int bitsPerPixel, cons // 1.x/2.x are mapped to 2.1 since Apple only support that legacy version. // >=3.0 are mapped to a 3.2 core profile. - bool legacy = m_settings.majorVersion < 3; + const bool legacy = m_settings.majorVersion < 3; if (legacy) { @@ -250,7 +250,7 @@ void SFContext::createContext(SFContext* shared, unsigned int bitsPerPixel, cons m_settings.sRgbCapable = true; // Create the pixel format. - NSOpenGLPixelFormat* pixFmt = [[NSOpenGLPixelFormat alloc] initWithAttributes:attrs.data()]; + NSOpenGLPixelFormat* const pixFmt = [[NSOpenGLPixelFormat alloc] initWithAttributes:attrs.data()]; if (pixFmt == nil) { @@ -259,7 +259,7 @@ void SFContext::createContext(SFContext* shared, unsigned int bitsPerPixel, cons } // Use the shared context if one is given. - NSOpenGLContext* sharedContext = shared != nullptr ? shared->m_context : nil; + NSOpenGLContext* const sharedContext = shared != nullptr ? shared->m_context : nil; if (sharedContext != nil) { diff --git a/src/SFML/Window/OSX/SFKeyboardModifiersHelper.mm b/src/SFML/Window/OSX/SFKeyboardModifiersHelper.mm index 90dd5204..bd1aa7f7 100644 --- a/src/SFML/Window/OSX/SFKeyboardModifiersHelper.mm +++ b/src/SFML/Window/OSX/SFKeyboardModifiersHelper.mm @@ -133,7 +133,7 @@ void initialiseKeyboardHelper() if (isStateInitialized) return; - NSUInteger modifiers = [[NSApp currentEvent] modifierFlags]; + const NSUInteger modifiers = [[NSApp currentEvent] modifierFlags]; // Load current keyboard state state.leftShiftWasDown = isKeyMaskActive(modifiers, NSLeftShiftKeyMask); @@ -245,10 +245,10 @@ void processOneModifier(NSUInteger modifiers, sf::priv::WindowImplCocoa& requester) { // Setup a potential event key. - sf::Event::KeyEvent event = keyEventWithModifiers(modifiers, key, code); + const sf::Event::KeyEvent event = keyEventWithModifiers(modifiers, key, code); // State - BOOL isDown = isKeyMaskActive(modifiers, mask); + const BOOL isDown = isKeyMaskActive(modifiers, mask); // Check for key pressed event if (isDown && !wasDown) diff --git a/src/SFML/Window/OSX/VideoModeImpl.cpp b/src/SFML/Window/OSX/VideoModeImpl.cpp index b8f40ebb..2dae1f1f 100644 --- a/src/SFML/Window/OSX/VideoModeImpl.cpp +++ b/src/SFML/Window/OSX/VideoModeImpl.cpp @@ -51,7 +51,7 @@ std::vector VideoModeImpl::getFullscreenModes() return modes; } - VideoMode desktop = getDesktopMode(); + const VideoMode desktop = getDesktopMode(); // Loop on each mode and convert it into a sf::VideoMode object. const CFIndex modesCount = CFArrayGetCount(cgmodes); @@ -59,7 +59,7 @@ std::vector VideoModeImpl::getFullscreenModes() { auto* cgmode = static_cast(const_cast(CFArrayGetValueAtIndex(cgmodes, i))); - VideoMode mode = convertCGModeToSFMode(cgmode); + const VideoMode mode = convertCGModeToSFMode(cgmode); // Skip if bigger than desktop as we currently don't perform hard resolution switch if ((mode.size.x > desktop.size.x) || (mode.size.y > desktop.size.y)) @@ -85,8 +85,8 @@ VideoMode VideoModeImpl::getDesktopMode() // Rely exclusively on mode and convertCGModeToSFMode // instead of display id and CGDisplayPixelsHigh/Wide. - CGDirectDisplayID display = CGMainDisplayID(); - CGDisplayModeRef cgmode = CGDisplayCopyDisplayMode(display); + const CGDirectDisplayID display = CGMainDisplayID(); + CGDisplayModeRef cgmode = CGDisplayCopyDisplayMode(display); mode = convertCGModeToSFMode(cgmode); diff --git a/src/SFML/Window/OSX/WindowImplCocoa.mm b/src/SFML/Window/OSX/WindowImplCocoa.mm index 57fc3c74..dae93d98 100644 --- a/src/SFML/Window/OSX/WindowImplCocoa.mm +++ b/src/SFML/Window/OSX/WindowImplCocoa.mm @@ -60,7 +60,7 @@ bool isCursorHidden = false; // initially, the cursor is visible //////////////////////////////////////////////////////// void hideMouseCursor() { - AutoreleasePool pool; + const AutoreleasePool pool; if (!isCursorHidden) { [NSCursor hide]; @@ -72,7 +72,7 @@ void hideMouseCursor() //////////////////////////////////////////////////////// void showMouseCursor() { - AutoreleasePool pool; + const AutoreleasePool pool; if (isCursorHidden) { [NSCursor unhide]; @@ -86,9 +86,9 @@ void showMouseCursor() //////////////////////////////////////////////////////////// WindowImplCocoa::WindowImplCocoa(WindowHandle handle) { - AutoreleasePool pool; + const AutoreleasePool pool; // Treat the handle as it real type - id nsHandle = static_cast(handle); + const id nsHandle = static_cast(handle); if ([nsHandle isKindOfClass:[NSWindow class]]) { // We have a window. @@ -119,7 +119,7 @@ WindowImplCocoa::WindowImplCocoa(WindowHandle handle) //////////////////////////////////////////////////////////// WindowImplCocoa::WindowImplCocoa(VideoMode mode, const String& title, unsigned long style, const ContextSettings& /*settings*/) { - AutoreleasePool pool; + const AutoreleasePool pool; // Transform the app process. setUpProcess(); @@ -135,7 +135,7 @@ WindowImplCocoa::WindowImplCocoa(VideoMode mode, const String& title, unsigned l //////////////////////////////////////////////////////////// WindowImplCocoa::~WindowImplCocoa() { - AutoreleasePool pool; + const AutoreleasePool pool; [m_delegate closeWindow]; // Tell the window/view controller (and the OpenGL view) that the delegate // (this object) no longer exists to prevent events being sent to the window @@ -144,10 +144,10 @@ WindowImplCocoa::~WindowImplCocoa() [m_delegate release]; // Put the next window in front, if any. - NSArray* windows = [NSApp orderedWindows]; + NSArray* const windows = [NSApp orderedWindows]; if ([windows count] > 0) { - NSWindow* nextWindow = [windows objectAtIndex:0]; + NSWindow* const nextWindow = [windows objectAtIndex:0]; if ([nextWindow isVisible]) [nextWindow makeKeyAndOrderFront:nil]; } @@ -157,7 +157,7 @@ WindowImplCocoa::~WindowImplCocoa() //////////////////////////////////////////////////////////// void WindowImplCocoa::applyContext(NSOpenGLContextRef context) const { - AutoreleasePool pool; + const AutoreleasePool pool; [m_delegate applyContext:context]; } @@ -165,8 +165,8 @@ void WindowImplCocoa::applyContext(NSOpenGLContextRef context) const //////////////////////////////////////////////////////////// void WindowImplCocoa::setUpProcess() { - AutoreleasePool pool; - static bool isTheProcessSetAsApplication = false; + const AutoreleasePool pool; + static bool isTheProcessSetAsApplication = false; if (!isTheProcessSetAsApplication) { @@ -381,7 +381,7 @@ void WindowImplCocoa::textEntered(unichar charcode) //////////////////////////////////////////////////////////// void WindowImplCocoa::processEvents() { - AutoreleasePool pool; + const AutoreleasePool pool; [m_delegate processEvent]; } @@ -391,7 +391,7 @@ void WindowImplCocoa::processEvents() //////////////////////////////////////////////////////////// WindowHandle WindowImplCocoa::getSystemHandle() const { - AutoreleasePool pool; + const AutoreleasePool pool; return [m_delegate getSystemHandle]; } @@ -399,9 +399,9 @@ 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)); + const AutoreleasePool pool; + const NSPoint pos = [m_delegate position]; + sf::Vector2i ret(static_cast(pos.x), static_cast(pos.y)); scaleOutXY(ret, m_delegate); return ret; } @@ -410,8 +410,8 @@ Vector2i WindowImplCocoa::getPosition() const //////////////////////////////////////////////////////////// void WindowImplCocoa::setPosition(const Vector2i& position) { - AutoreleasePool pool; - sf::Vector2i backingPosition = position; + const AutoreleasePool pool; + sf::Vector2i backingPosition = position; scaleInXY(backingPosition, m_delegate); [m_delegate setWindowPositionToX:backingPosition.x Y:backingPosition.y]; } @@ -420,9 +420,9 @@ 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)); + const AutoreleasePool pool; + const NSSize size = [m_delegate size]; + Vector2u ret(static_cast(size.width), static_cast(size.height)); scaleOutXY(ret, m_delegate); return ret; } @@ -440,7 +440,7 @@ void WindowImplCocoa::setSize(const Vector2u& size) //////////////////////////////////////////////////////////// void WindowImplCocoa::setTitle(const String& title) { - AutoreleasePool pool; + const AutoreleasePool pool; [m_delegate changeTitle:sfStringToNSString(title)]; } @@ -448,7 +448,7 @@ void WindowImplCocoa::setTitle(const String& title) //////////////////////////////////////////////////////////// void WindowImplCocoa::setIcon(const Vector2u& size, const std::uint8_t* pixels) { - AutoreleasePool pool; + const AutoreleasePool pool; [m_delegate setIconTo:size.x by:size.y with:pixels]; } @@ -456,7 +456,7 @@ void WindowImplCocoa::setIcon(const Vector2u& size, const std::uint8_t* pixels) //////////////////////////////////////////////////////////// void WindowImplCocoa::setVisible(bool visible) { - AutoreleasePool pool; + const AutoreleasePool pool; if (visible) [m_delegate showWindow]; else @@ -467,7 +467,7 @@ void WindowImplCocoa::setVisible(bool visible) //////////////////////////////////////////////////////////// void WindowImplCocoa::setMouseCursorVisible(bool visible) { - AutoreleasePool pool; + const AutoreleasePool pool; m_showCursor = visible; // If the mouse is over the window, we apply the new setting @@ -484,7 +484,7 @@ void WindowImplCocoa::setMouseCursorVisible(bool visible) //////////////////////////////////////////////////////////// void WindowImplCocoa::setMouseCursorGrabbed(bool grabbed) { - AutoreleasePool pool; + const AutoreleasePool pool; [m_delegate setCursorGrabbed:grabbed]; } @@ -492,7 +492,7 @@ void WindowImplCocoa::setMouseCursorGrabbed(bool grabbed) //////////////////////////////////////////////////////////// void WindowImplCocoa::setMouseCursor(const CursorImpl& cursor) { - AutoreleasePool pool; + const AutoreleasePool pool; [m_delegate setCursor:cursor.m_cursor]; } @@ -500,7 +500,7 @@ void WindowImplCocoa::setMouseCursor(const CursorImpl& cursor) //////////////////////////////////////////////////////////// void WindowImplCocoa::setKeyRepeatEnabled(bool enabled) { - AutoreleasePool pool; + const AutoreleasePool pool; if (enabled) [m_delegate enableKeyRepeat]; else @@ -511,7 +511,7 @@ void WindowImplCocoa::setKeyRepeatEnabled(bool enabled) //////////////////////////////////////////////////////////// void WindowImplCocoa::requestFocus() { - AutoreleasePool pool; + const AutoreleasePool pool; [m_delegate requestFocus]; } @@ -519,7 +519,7 @@ void WindowImplCocoa::requestFocus() //////////////////////////////////////////////////////////// bool WindowImplCocoa::hasFocus() const { - AutoreleasePool pool; + const AutoreleasePool pool; return [m_delegate hasFocus]; } diff --git a/src/SFML/Window/OSX/cpp_objc_conversion.mm b/src/SFML/Window/OSX/cpp_objc_conversion.mm index 33b62b94..dfd4e613 100644 --- a/src/SFML/Window/OSX/cpp_objc_conversion.mm +++ b/src/SFML/Window/OSX/cpp_objc_conversion.mm @@ -38,7 +38,7 @@ NSString* stringToNSString(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* const str = [NSString stringWithCString:utf8.c_str() encoding:NSUTF8StringEncoding]; return str; } @@ -46,7 +46,7 @@ NSString* stringToNSString(const std::string& string) //////////////////////////////////////////////////////////// NSString* sfStringToNSString(const sf::String& string) { - auto length = static_cast(string.getSize() * sizeof(std::uint32_t)); + const auto length = static_cast(string.getSize() * sizeof(std::uint32_t)); const void* data = reinterpret_cast(string.getData()); NSStringEncoding encoding; @@ -55,6 +55,6 @@ NSString* sfStringToNSString(const sf::String& string) else encoding = NSUTF32BigEndianStringEncoding; - NSString* str = [[NSString alloc] initWithBytes:data length:length encoding:encoding]; + NSString* const str = [[NSString alloc] initWithBytes:data length:length encoding:encoding]; return [str autorelease]; } diff --git a/src/SFML/Window/Win32/ClipboardImpl.cpp b/src/SFML/Window/Win32/ClipboardImpl.cpp index 4faac36b..a6199688 100644 --- a/src/SFML/Window/Win32/ClipboardImpl.cpp +++ b/src/SFML/Window/Win32/ClipboardImpl.cpp @@ -86,8 +86,8 @@ void ClipboardImpl::setString(const String& text) } // Create a Win32-compatible string - std::size_t stringSize = (text.getSize() + 1) * sizeof(WCHAR); - HANDLE stringHandle = GlobalAlloc(GMEM_MOVEABLE, stringSize); + const std::size_t stringSize = (text.getSize() + 1) * sizeof(WCHAR); + HANDLE stringHandle = GlobalAlloc(GMEM_MOVEABLE, stringSize); if (stringHandle) { diff --git a/src/SFML/Window/Win32/InputImpl.cpp b/src/SFML/Window/Win32/InputImpl.cpp index 32a9a21f..eadda836 100644 --- a/src/SFML/Window/Win32/InputImpl.cpp +++ b/src/SFML/Window/Win32/InputImpl.cpp @@ -489,7 +489,7 @@ WORD sfScanToWinScanExtended(Keyboard::Scancode code) UINT sfScanToVirtualKey(Keyboard::Scancode code) { - WORD winScancode = sfScanToWinScan(code); + const WORD winScancode = sfScanToWinScan(code); // Manually map non-extended key codes // clang-format off @@ -544,9 +544,9 @@ void InputImpl::ensureMappings() // Phase 2: Translate scancode to virtual code to key names for (int i = 0; i < static_cast(Keyboard::Scan::ScancodeCount); ++i) { - auto scan = static_cast(i); - UINT virtualKey = sfScanToVirtualKey(scan); - Keyboard::Key key = virtualKeyToSfKey(virtualKey); + const auto scan = static_cast(i); + const UINT virtualKey = sfScanToVirtualKey(scan); + const Keyboard::Key key = virtualKeyToSfKey(virtualKey); if (key != Keyboard::Unknown && m_keyToScancodeMapping[key] == Keyboard::Scan::Unknown) m_keyToScancodeMapping[key] = scan; m_scancodeToKeyMapping[static_cast(scan)] = key; @@ -558,14 +558,14 @@ void InputImpl::ensureMappings() //////////////////////////////////////////////////////////// bool InputImpl::isKeyPressed(Keyboard::Key key) { - int virtualKey = sfKeyToVirtualKey(key); + const int virtualKey = sfKeyToVirtualKey(key); return (GetAsyncKeyState(virtualKey) & 0x8000) != 0; } //////////////////////////////////////////////////////////// bool InputImpl::isKeyPressed(Keyboard::Scancode code) { - UINT virtualKey = sfScanToVirtualKey(code); + const UINT virtualKey = sfScanToVirtualKey(code); return (GetAsyncKeyState(static_cast(virtualKey)) & KF_UP) != 0; } @@ -594,10 +594,10 @@ Keyboard::Scancode InputImpl::delocalize(Keyboard::Key key) //////////////////////////////////////////////////////////// String InputImpl::getDescription(Keyboard::Scancode code) { - WORD winCode = sfScanToWinScanExtended(code); - const int bufSize = 1024; - WCHAR name[bufSize]; - int result = GetKeyNameText(winCode << 16, name, bufSize); + const WORD winCode = sfScanToWinScanExtended(code); + const int bufSize = 1024; + WCHAR name[bufSize]; + const int result = GetKeyNameText(winCode << 16, name, bufSize); if (result > 0) { return name; diff --git a/src/SFML/Window/Win32/JoystickImpl.cpp b/src/SFML/Window/Win32/JoystickImpl.cpp index 704565d2..cb9e3b81 100644 --- a/src/SFML/Window/Win32/JoystickImpl.cpp +++ b/src/SFML/Window/Win32/JoystickImpl.cpp @@ -132,7 +132,7 @@ std::string getErrorString(DWORD error) nullptr) == 0) return "Unknown error."; - sf::String message = buffer; + const sf::String message = buffer; LocalFree(buffer); return message.toAnsiString(); } @@ -299,7 +299,7 @@ bool JoystickImpl::open(unsigned int index) m_index = JOYSTICKID1 + index; // Store the joystick capabilities - bool success = joyGetDevCaps(m_index, &m_caps, sizeof(m_caps)) == JOYERR_NOERROR; + const bool success = joyGetDevCaps(m_index, &m_caps, sizeof(m_caps)) == JOYERR_NOERROR; if (success) { @@ -395,7 +395,7 @@ JoystickState JoystickImpl::update() // Special case for POV, it is given as an angle if (pos.dwPOV != 0xFFFF) { - float angle = static_cast(pos.dwPOV) / 18000.f * 3.141592654f; + const 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; } @@ -430,11 +430,11 @@ void JoystickImpl::initializeDInput() if (directInput8Create) { // Try to acquire a DirectInput 8.x interface - HRESULT result = directInput8Create(GetModuleHandleW(nullptr), - 0x0800, - guids::IID_IDirectInput8W, - reinterpret_cast(&directInput), - nullptr); + const HRESULT result = directInput8Create(GetModuleHandleW(nullptr), + 0x0800, + guids::IID_IDirectInput8W, + reinterpret_cast(&directInput), + nullptr); if (FAILED(result)) { @@ -490,10 +490,10 @@ void JoystickImpl::updateConnectionsDInput() record.plugged = false; // Enumerate devices - HRESULT result = directInput->EnumDevices(DI8DEVCLASS_GAMECTRL, - &JoystickImpl::deviceEnumerationCallback, - nullptr, - DIEDFL_ATTACHEDONLY); + const 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();) @@ -730,7 +730,7 @@ bool JoystickImpl::openDInput(unsigned int index) } // Set device's axis mode to absolute if the device reports having at least one axis - for (int axis : m_axes) + for (const int axis : m_axes) { if (axis != -1) { @@ -867,7 +867,7 @@ JoystickCaps JoystickImpl::getCapabilitiesDInput() const // Count how many buttons have valid offsets caps.buttonCount = 0; - for (int button : m_buttons) + for (const int button : m_buttons) { if (button != -1) ++caps.buttonCount; @@ -931,11 +931,11 @@ JoystickState JoystickImpl::updateDInputBuffered() { if ((j == Joystick::PovX) || (j == Joystick::PovY)) { - unsigned short value = LOWORD(events[i].dwData); + const unsigned short value = LOWORD(events[i].dwData); if (value != 0xFFFF) { - float angle = (static_cast(value)) * 3.141592654f / DI_DEGREES / 180.f; + const float angle = (static_cast(value)) * 3.141592654f / DI_DEGREES / 180.f; m_state.axes[Joystick::PovX] = std::sin(angle) * 100.f; m_state.axes[Joystick::PovY] = std::cos(angle) * 100.f; @@ -1020,12 +1020,12 @@ JoystickState JoystickImpl::updateDInputPolled() { if ((i == Joystick::PovX) || (i == Joystick::PovY)) { - unsigned short value = LOWORD( + const unsigned short value = LOWORD( *reinterpret_cast(reinterpret_cast(&joystate) + m_axes[i])); if (value != 0xFFFF) { - float angle = (static_cast(value)) * 3.141592654f / DI_DEGREES / 180.f; + const float angle = (static_cast(value)) * 3.141592654f / DI_DEGREES / 180.f; state.axes[Joystick::PovX] = std::sin(angle) * 100.f; state.axes[Joystick::PovY] = std::cos(angle) * 100.f; @@ -1055,7 +1055,7 @@ JoystickState JoystickImpl::updateDInputPolled() { if (m_buttons[i] != -1) { - BYTE value = *reinterpret_cast(reinterpret_cast(&joystate) + m_buttons[i]); + const BYTE value = *reinterpret_cast(reinterpret_cast(&joystate) + m_buttons[i]); state.buttons[i] = ((value & 0x80) != 0); } @@ -1085,7 +1085,7 @@ BOOL CALLBACK JoystickImpl::deviceEnumerationCallback(const DIDEVICEINSTANCE* de } } - JoystickRecord record = {deviceInstance->guidInstance, sf::Joystick::Count, true}; + const JoystickRecord record = {deviceInstance->guidInstance, sf::Joystick::Count, true}; joystickList.push_back(record); return DIENUM_CONTINUE; @@ -1131,7 +1131,7 @@ BOOL CALLBACK JoystickImpl::deviceObjectEnumerationCallback(const DIDEVICEOBJECT propertyRange.lMin = -32768; propertyRange.lMax = 32767; - HRESULT result = joystick.m_device->SetProperty(DIPROP_RANGE, &propertyRange.diph); + const HRESULT result = joystick.m_device->SetProperty(DIPROP_RANGE, &propertyRange.diph); if (result != DI_OK) err() << "Failed to set DirectInput device axis property range: " << result << std::endl; diff --git a/src/SFML/Window/Win32/VideoModeImpl.cpp b/src/SFML/Window/Win32/VideoModeImpl.cpp index 318f2cf8..51400a59 100644 --- a/src/SFML/Window/Win32/VideoModeImpl.cpp +++ b/src/SFML/Window/Win32/VideoModeImpl.cpp @@ -46,7 +46,7 @@ std::vector VideoModeImpl::getFullscreenModes() for (int count = 0; EnumDisplaySettings(nullptr, static_cast(count), &win32Mode); ++count) { // Convert to sf::VideoMode - VideoMode mode({win32Mode.dmPelsWidth, win32Mode.dmPelsHeight}, win32Mode.dmBitsPerPel); + const VideoMode mode({win32Mode.dmPelsWidth, win32Mode.dmPelsHeight}, win32Mode.dmBitsPerPel); // Add it only if it is not already in the array if (std::find(modes.begin(), modes.end(), mode) == modes.end()) diff --git a/src/SFML/Window/Win32/WglContext.cpp b/src/SFML/Window/Win32/WglContext.cpp index da0a7edf..6f5a2837 100644 --- a/src/SFML/Window/Win32/WglContext.cpp +++ b/src/SFML/Window/Win32/WglContext.cpp @@ -297,7 +297,7 @@ int WglContext::selectBestPixelFormat(HDC deviceContext, unsigned int bitsPerPix // Let's check how many formats are supporting our requirements 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; + const bool isValid = wglChoosePixelFormatARB(deviceContext, intAttributes, nullptr, 512, formats, &nbFormats) != FALSE; if (!isValid) err() << "Failed to enumerate pixel formats: " << getErrorString(GetLastError()).toAnsiString() << std::endl; @@ -372,15 +372,15 @@ 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); + const int color = values[0] + values[1] + values[2] + values[3]; + const 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) @@ -423,7 +423,7 @@ int WglContext::selectBestPixelFormat(HDC deviceContext, unsigned int bitsPerPix //////////////////////////////////////////////////////////// void WglContext::setDevicePixelFormat(unsigned int bitsPerPixel) { - int bestFormat = selectBestPixelFormat(m_deviceContext, bitsPerPixel, m_settings); + const int bestFormat = selectBestPixelFormat(m_deviceContext, bitsPerPixel, m_settings); if (bestFormat == 0) { @@ -452,7 +452,7 @@ void WglContext::setDevicePixelFormat(unsigned int bitsPerPixel) //////////////////////////////////////////////////////////// void WglContext::updateSettingsFromPixelFormat() { - int format = GetPixelFormat(m_deviceContext); + const int format = GetPixelFormat(m_deviceContext); if (format == 0) { @@ -562,7 +562,7 @@ void WglContext::createSurface(WglContext* shared, const Vector2u& size, unsigne // Check if the shared context already exists and pbuffers are supported if (shared && shared->m_deviceContext && SF_GLAD_WGL_ARB_pbuffer) { - int bestFormat = selectBestPixelFormat(shared->m_deviceContext, bitsPerPixel, m_settings, true); + const int bestFormat = selectBestPixelFormat(shared->m_deviceContext, bitsPerPixel, m_settings, true); if (bestFormat > 0) { @@ -649,7 +649,7 @@ void WglContext::createContext(WglContext* shared) return; // Get a working copy of the context settings - ContextSettings settings = m_settings; + const ContextSettings settings = m_settings; // Get the context to share display lists with HGLRC sharedContext = shared ? shared->m_context : nullptr; @@ -673,10 +673,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; + const int profile = (m_settings.attributeFlags & ContextSettings::Core) + ? WGL_CONTEXT_CORE_PROFILE_BIT_ARB + : WGL_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB; + const 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); @@ -700,7 +700,7 @@ void WglContext::createContext(WglContext* shared) if (sharedContext) { static std::recursive_mutex mutex; - std::lock_guard lock(mutex); + const std::lock_guard lock(mutex); if (WglContextImpl::currentContext == shared) { @@ -772,7 +772,7 @@ void WglContext::createContext(WglContext* shared) { // wglShareLists doesn't seem to be thread-safe static std::recursive_mutex mutex; - std::lock_guard lock(mutex); + const std::lock_guard lock(mutex); if (WglContextImpl::currentContext == shared) { diff --git a/src/SFML/Window/Win32/WindowImplWin32.cpp b/src/SFML/Window/Win32/WindowImplWin32.cpp index f077c15d..58d7293f 100644 --- a/src/SFML/Window/Win32/WindowImplWin32.cpp +++ b/src/SFML/Window/Win32/WindowImplWin32.cpp @@ -163,9 +163,9 @@ m_cursorGrabbed(m_fullscreen) registerWindowClass(); // 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; + HDC screenDC = GetDC(nullptr); + const int left = (GetDeviceCaps(screenDC, HORZRES) - static_cast(mode.size.x)) / 2; + const int top = (GetDeviceCaps(screenDC, VERTRES) - static_cast(mode.size.y)) / 2; auto [width, height] = Vector2i(mode.size); ReleaseDC(nullptr, screenDC); @@ -333,8 +333,8 @@ void WindowImplWin32::setSize(const Vector2u& size) // so we have to compute it RECT rectangle = {0, 0, static_cast(size.x), static_cast(size.y)}; AdjustWindowRect(&rectangle, static_cast(GetWindowLongPtr(m_handle, GWL_STYLE)), false); - int width = rectangle.right - rectangle.left; - int height = rectangle.bottom - rectangle.top; + const int width = rectangle.right - rectangle.left; + const int height = rectangle.bottom - rectangle.top; SetWindowPos(m_handle, nullptr, 0, 0, width, height, SWP_NOMOVE | SWP_NOZORDER); } @@ -1044,8 +1044,8 @@ void WindowImplWin32::processEvent(UINT message, WPARAM wParam, LPARAM lParam) case WM_MOUSEMOVE: { // Extract the mouse local coordinates - int x = static_cast(LOWORD(lParam)); - int y = static_cast(HIWORD(lParam)); + const int x = static_cast(LOWORD(lParam)); + const int y = static_cast(HIWORD(lParam)); // Get the client area of the window RECT area; @@ -1135,8 +1135,8 @@ Keyboard::Key WindowImplWin32::virtualKeyCodeToSF(WPARAM key, LPARAM flags) // Check the scancode to distinguish between left and right shift case VK_SHIFT: { - static UINT lShift = MapVirtualKeyW(VK_LSHIFT, MAPVK_VK_TO_VSC); - UINT scancode = static_cast((flags & (0xFF << 16)) >> 16); + static const UINT lShift = MapVirtualKeyW(VK_LSHIFT, MAPVK_VK_TO_VSC); + const UINT scancode = static_cast((flags & (0xFF << 16)) >> 16); return scancode == lShift ? Keyboard::LShift : Keyboard::RShift; } diff --git a/src/SFML/Window/WindowImpl.cpp b/src/SFML/Window/WindowImpl.cpp index 7c9a17fd..3d8b3700 100644 --- a/src/SFML/Window/WindowImpl.cpp +++ b/src/SFML/Window/WindowImpl.cpp @@ -198,11 +198,11 @@ 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]; + const JoystickState previousState = m_joystickStatesImpl->m_states[i]; m_joystickStatesImpl->m_states[i] = JoystickManager::getInstance().getState(i); // Connection state - bool connected = m_joystickStatesImpl->m_states[i].connected; + const bool connected = m_joystickStatesImpl->m_states[i].connected; if (previousState.connected ^ connected) { Event event; @@ -217,16 +217,16 @@ void WindowImpl::processJoystickEvents() if (connected) { - JoystickCaps caps = JoystickManager::getInstance().getCapabilities(i); + const JoystickCaps caps = JoystickManager::getInstance().getCapabilities(i); // Axes for (unsigned int j = 0; j < Joystick::AxisCount; ++j) { if (caps.axes[j]) { - auto axis = static_cast(j); - float prevPos = m_previousAxes[i][axis]; - float currPos = m_joystickStatesImpl->m_states[i].axes[axis]; + const auto axis = static_cast(j); + const float prevPos = m_previousAxes[i][axis]; + const float currPos = m_joystickStatesImpl->m_states[i].axes[axis]; if (std::abs(currPos - prevPos) >= m_joystickThreshold) { Event event; @@ -244,8 +244,8 @@ void WindowImpl::processJoystickEvents() // Buttons for (unsigned int j = 0; j < caps.buttonCount; ++j) { - bool prevPressed = previousState.buttons[j]; - bool currPressed = m_joystickStatesImpl->m_states[i].buttons[j]; + const bool prevPressed = previousState.buttons[j]; + const bool currPressed = m_joystickStatesImpl->m_states[i].buttons[j]; if (prevPressed ^ currPressed) { @@ -269,14 +269,14 @@ void WindowImpl::processSensorEvents() for (unsigned int i = 0; i < Sensor::Count; ++i) { - auto sensor = static_cast(i); + const auto sensor = static_cast(i); // Only process enabled sensors if (SensorManager::getInstance().isEnabled(sensor)) { // Copy the previous value of the sensor and get the new one - Vector3f previousValue = m_sensorValue[i]; - m_sensorValue[i] = SensorManager::getInstance().getValue(sensor); + const Vector3f previousValue = m_sensorValue[i]; + m_sensorValue[i] = SensorManager::getInstance().getValue(sensor); // If the value has changed, trigger an event if (m_sensorValue[i] != previousValue) // @todo use a threshold? diff --git a/test/Graphics/Image.test.cpp b/test/Graphics/Image.test.cpp index 107959eb..b1245143 100644 --- a/test/Graphics/Image.test.cpp +++ b/test/Graphics/Image.test.cpp @@ -168,8 +168,8 @@ TEST_CASE("[Graphics] sf::Image") SUBCASE("Copy (Empty image)") { - sf::Image image1; - sf::Image image2; + const sf::Image image1; + sf::Image image2; image2.create(sf::Vector2u(10, 10), sf::Color::Red); CHECK(!image2.copy(image1, sf::Vector2u(0, 0), sf::IntRect(sf::Vector2i(0, 0), sf::Vector2i(9, 9)))); diff --git a/test/Graphics/Rect.test.cpp b/test/Graphics/Rect.test.cpp index b2cfaacd..58e3bfaf 100644 --- a/test/Graphics/Rect.test.cpp +++ b/test/Graphics/Rect.test.cpp @@ -18,7 +18,7 @@ TEST_CASE("[Graphics] sf::Rect") { SUBCASE("Default constructor") { - sf::IntRect rectangle; + const sf::IntRect rectangle; CHECK(rectangle.left == 0); CHECK(rectangle.top == 0); CHECK(rectangle.width == 0); @@ -27,7 +27,7 @@ TEST_CASE("[Graphics] sf::Rect") SUBCASE("(left, top, width, height) constructor") { - sf::IntRect rectangle({1, 2}, {3, 4}); + const sf::IntRect rectangle({1, 2}, {3, 4}); CHECK(rectangle.left == 1); CHECK(rectangle.top == 2); CHECK(rectangle.width == 3); @@ -36,9 +36,9 @@ TEST_CASE("[Graphics] sf::Rect") SUBCASE("(Vector2, Vector2) constructor") { - sf::Vector2i position(1, 2); - sf::Vector2i dimension(3, 4); - sf::IntRect rectangle(position, dimension); + const sf::Vector2i position(1, 2); + const sf::Vector2i dimension(3, 4); + const sf::IntRect rectangle(position, dimension); CHECK(rectangle.left == 1); CHECK(rectangle.top == 2); @@ -48,8 +48,8 @@ TEST_CASE("[Graphics] sf::Rect") SUBCASE("Conversion constructor") { - sf::FloatRect sourceRectangle({1.0f, 2.0f}, {3.0f, 4.0f}); - sf::IntRect rectangle(sourceRectangle); + const sf::FloatRect sourceRectangle({1.0f, 2.0f}, {3.0f, 4.0f}); + const sf::IntRect rectangle(sourceRectangle); CHECK(rectangle.left == static_cast(sourceRectangle.left)); CHECK(rectangle.top == static_cast(sourceRectangle.top)); @@ -60,7 +60,7 @@ TEST_CASE("[Graphics] sf::Rect") SUBCASE("contains(Vector2)") { - sf::IntRect rectangle({0, 0}, {10, 10}); + const sf::IntRect rectangle({0, 0}, {10, 10}); CHECK(rectangle.contains(sf::Vector2i(0, 0)) == true); CHECK(rectangle.contains(sf::Vector2i(9, 0)) == true); diff --git a/test/Graphics/Texture.test.cpp b/test/Graphics/Texture.test.cpp index 998ac1a5..e1e11629 100644 --- a/test/Graphics/Texture.test.cpp +++ b/test/Graphics/Texture.test.cpp @@ -18,7 +18,7 @@ TEST_CASE("[Graphics] sf::Texture" * doctest::skip(skipDisplayTests)) { SUBCASE("Construction") { - sf::Texture texture; + const sf::Texture texture; CHECK(texture.getSize() == sf::Vector2u()); CHECK(!texture.isSmooth()); CHECK(!texture.isSrgb()); @@ -204,8 +204,8 @@ TEST_CASE("[Graphics] sf::Texture" * doctest::skip(skipDisplayTests)) CHECK_FALSE(texture2.isSmooth()); CHECK(texture2.isRepeated()); - sf::Image image1 = texture1.copyToImage(); - sf::Image image2 = texture2.copyToImage(); + const sf::Image image1 = texture1.copyToImage(); + const sf::Image image2 = texture2.copyToImage(); REQUIRE(image1.getSize() == sf::Vector2u(2, 1)); REQUIRE(image2.getSize() == sf::Vector2u(1, 1)); CHECK(image1.getPixel(sf::Vector2u(1, 0)) == sf::Color::Green); diff --git a/test/System/Err.test.cpp b/test/System/Err.test.cpp index 99d0e6c6..3494cdd7 100644 --- a/test/System/Err.test.cpp +++ b/test/System/Err.test.cpp @@ -21,7 +21,7 @@ TEST_CASE("[System] sf::err") auto* const defaultStreamBuffer = sf::err().rdbuf(); CHECK(defaultStreamBuffer != nullptr); - std::stringstream stream; + const std::stringstream stream; sf::err().rdbuf(stream.rdbuf()); sf::err() << "Something went wrong!\n"; CHECK(stream.str() == "Something went wrong!\n"); diff --git a/test/System/FileInputStream.test.cpp b/test/System/FileInputStream.test.cpp index d7ff9a15..43d2f2a1 100644 --- a/test/System/FileInputStream.test.cpp +++ b/test/System/FileInputStream.test.cpp @@ -83,7 +83,7 @@ TEST_CASE("[System] sf::FileInputStream") { const std::string fileContents = "hello world"; - TemporaryFile tmpFile(fileContents); + const TemporaryFile tmpFile(fileContents); sf::FileInputStream fis; REQUIRE(fis.open(tmpFile.getPath())); diff --git a/test/Window/Window.test.cpp b/test/Window/Window.test.cpp index 24fa215d..fdc86767 100644 --- a/test/Window/Window.test.cpp +++ b/test/Window/Window.test.cpp @@ -19,7 +19,10 @@ TEST_CASE("[Window] sf::Window" * doctest::skip(skipDisplayTests)) { SUBCASE("Construction") { - sf::Window window(sf::VideoMode(sf::Vector2u(256, 256), 32), "Window Title", sf::Style::Default, sf::ContextSettings()); + const sf::Window window(sf::VideoMode(sf::Vector2u(256, 256), 32), + "Window Title", + sf::Style::Default, + sf::ContextSettings()); CHECK(window.getSize() == sf::Vector2u(256, 256)); } } diff --git a/test/install/Install.cpp b/test/install/Install.cpp index 77349197..7de4e249 100644 --- a/test/install/Install.cpp +++ b/test/install/Install.cpp @@ -8,32 +8,32 @@ int main() { // Audio - [[maybe_unused]] sf::InputSoundFile inputSoundFile; - [[maybe_unused]] sf::SoundBufferRecorder soundBufferRecorder; - [[maybe_unused]] sf::Music music; - [[maybe_unused]] sf::Sound sound; + [[maybe_unused]] const sf::InputSoundFile inputSoundFile; + [[maybe_unused]] const sf::SoundBufferRecorder soundBufferRecorder; + [[maybe_unused]] const sf::Music music; + [[maybe_unused]] const sf::Sound sound; // Graphics - [[maybe_unused]] sf::Color color; - [[maybe_unused]] sf::Font font; - [[maybe_unused]] sf::RenderWindow renderWindow; - [[maybe_unused]] sf::RectangleShape rectangleShape; - [[maybe_unused]] sf::Vertex vertex; + [[maybe_unused]] const sf::Color color; + [[maybe_unused]] const sf::Font font; + [[maybe_unused]] const sf::RenderWindow renderWindow; + [[maybe_unused]] const sf::RectangleShape rectangleShape; + [[maybe_unused]] const sf::Vertex vertex; // Network - [[maybe_unused]] sf::Ftp ftp; - [[maybe_unused]] sf::Http http; - [[maybe_unused]] sf::Packet packet; - [[maybe_unused]] sf::UdpSocket udpSocket; + [[maybe_unused]] const sf::Ftp ftp; + [[maybe_unused]] const sf::Http http; + [[maybe_unused]] const sf::Packet packet; + [[maybe_unused]] const sf::UdpSocket udpSocket; // System - [[maybe_unused]] sf::Angle angle; - [[maybe_unused]] sf::FileInputStream fileInputStream; - [[maybe_unused]] sf::String string; - [[maybe_unused]] sf::Time time; + [[maybe_unused]] const sf::Angle angle; + [[maybe_unused]] const sf::FileInputStream fileInputStream; + [[maybe_unused]] const sf::String string; + [[maybe_unused]] const sf::Time time; // Window - [[maybe_unused]] sf::Context context; - [[maybe_unused]] sf::VideoMode videoMode; - [[maybe_unused]] sf::Window window; + [[maybe_unused]] const sf::Context context; + [[maybe_unused]] const sf::VideoMode videoMode; + [[maybe_unused]] const sf::Window window; }