diff options
author | heavydemon21 <nielsstunnebrink1@gmail.com> | 2024-11-18 15:08:31 +0100 |
---|---|---|
committer | heavydemon21 <nielsstunnebrink1@gmail.com> | 2024-11-18 15:08:31 +0100 |
commit | fee42c67918a9370f7f4e074dba9a677afccf90b (patch) | |
tree | c5ed200e3c584fafc4c6bd3df48adeed3cfbd31d | |
parent | ed1403aea4412bd479244eae8e2940190e71cd28 (diff) | |
parent | 121b64b1cb6cfead5814070c8b0185d3d7308095 (diff) |
Merge remote-tracking branch 'origin/master' into niels/RenderingParticle
156 files changed, 2110 insertions, 2372 deletions
diff --git a/.clang-format b/.clang-format index 8ce4033..1ee37ec 100644 --- a/.clang-format +++ b/.clang-format @@ -4,7 +4,7 @@ AllowShortIfStatementsOnASingleLine: AllIfsAndElse AllowShortLoopsOnASingleLine: true BasedOnStyle: LLVM BreakBeforeBraces: Attach -ColumnLimit: 80 +ColumnLimit: 95 EmptyLineBeforeAccessModifier: Always IndentAccessModifiers: false IndentCaseLabels: true diff --git a/.editorconfig b/.editorconfig index df2cf5e..191871f 100644 --- a/.editorconfig +++ b/.editorconfig @@ -4,8 +4,11 @@ root = true indent_style = tab end_of_line = lf insert_final_newline = true +max_line_length = 95 [{*.{md,yml},.clang-*}] indent_style = space indent_size = 2 +[*.md] +max_line_length = 80 diff --git a/contributing.md b/contributing.md index 3090727..5b0c79d 100644 --- a/contributing.md +++ b/contributing.md @@ -678,6 +678,118 @@ that you can click on to open them. uint64_t foo(); ``` </td></tr></table></details> +- <details><summary> + Utilize standard exceptions where appropriate (those found in <code><stdexcept></code>) + </summary><table><tr><th>Good</th><th>Bad</th></tr><tr><td> + + ```cpp + #include <stdexcept> + + // ... + + if (foo == nullptr) { + throw std::runtime_error("What is wrong"); + } + ``` + </td><td> + + ```cpp + if (foo == nullptr) { + std::cout << "What is wrong" << std::endl; + exit(1); + } + ``` + </td></tr></table></details> +- <details><summary> + Mention the name of the class when throwing an exception + </summary><table><tr><th>Good</th><th>Bad</th></tr><tr><td> + + ```cpp + Foo::bar() { + if (...) + throw std::runtime_error("Foo: big error!"); + } + ``` + </td><td> + + ```cpp + Foo::bar() { + if (...) + throw std::runtime_error("big error!"); + } + ``` + </td></tr></table></details> +- <details><summary> + Constructors of classes derived from <code>Component</code> should be + protected and <code>ComponentManager</code> should be declared as a friend + class. + </summary><table><tr><th>Good</th><th>Bad</th></tr><tr><td> + + ```cpp + class MyComponent : public Component { + protected: + MyComponent(...); + //! Only ComponentManager is allowed to create components + friend class ComponentManager; + }; + ``` + </td><td> + + ```cpp + class MyComponent : public Component { + public: + MyComponent(...); + }; + ``` + </td></tr></table></details> +- <details><summary> + C++ <code>std::format</code> should be used instead of C-style format specifiers + </summary><table><tr><th>Good</th><th>Bad</th></tr><tr><td> + + ```cpp + std::string message = std::format("Hello, {}", name); + + dbg_logf("Here too: {}", 3); + + throw std::runtime_error(std::format("Or here: {}", 5)); + ``` + </td><td> + + ```cpp + char message[50]; + sprintf(message, "Hello, %s", name); + ``` + </td></tr></table></details> +- <details><summary> + Argument names should be added in <code>.h</code> files (not only in + <code>.cpp</code> and <code>.hpp</code> files) + </summary><table><tr><th>Good</th><th>Bad</th></tr><tr><td> + + Foo.h: + ```cpp + void foo(int bar); + ``` + + Foo.cpp: + ```cpp + void foo(int bar) { + // ... + } + ``` + </td><td> + + Foo.h: + ```cpp + void foo(int); + ``` + + Foo.cpp: + ```cpp + void foo(int bar) { + // ... + } + ``` + </td></tr></table></details> ## CMakeLists-specific diff --git a/mwe/ecs-homemade/inc/ComponentManager.h b/mwe/ecs-homemade/inc/ComponentManager.h index 0ba358e..99c108f 100644 --- a/mwe/ecs-homemade/inc/ComponentManager.h +++ b/mwe/ecs-homemade/inc/ComponentManager.h @@ -33,8 +33,7 @@ public: //Get a vector<> of all components at specific type and id template <typename T> - std::vector<std::reference_wrapper<T>> - GetComponentsByID(std::uint32_t id) const; + std::vector<std::reference_wrapper<T>> GetComponentsByID(std::uint32_t id) const; //Get a vector<> of all components of a specific type template <typename T> std::vector<std::reference_wrapper<T>> GetComponentsByType() const; @@ -50,8 +49,7 @@ private: * The first std::vector<> stores another vector<>. This first vector<> is to bind the entity's id to a component. * The second std::vector<> stores unique_ptrs. Each component can be gathered via an unique_ptr. This second vector<> allows multiple components of the same std::type_index for one entity (id). */ - std::unordered_map<std::type_index, - std::vector<std::vector<std::unique_ptr<Component>>>> + std::unordered_map<std::type_index, std::vector<std::vector<std::unique_ptr<Component>>>> mComponents; }; diff --git a/mwe/ecs-homemade/inc/ComponentManager.hpp b/mwe/ecs-homemade/inc/ComponentManager.hpp index 92db1d4..af9c3a1 100644 --- a/mwe/ecs-homemade/inc/ComponentManager.hpp +++ b/mwe/ecs-homemade/inc/ComponentManager.hpp @@ -7,8 +7,7 @@ T & ComponentManager::AddComponent(std::uint32_t id, Args &&... args) { //Check if this component type is already in the unordered_map<> if (mComponents.find(type) == mComponents.end()) { //If not, create a new (empty) vector<> of vector<unique_ptr<Component>> - mComponents[type] - = std::vector<std::vector<std::unique_ptr<Component>>>(); + mComponents[type] = std::vector<std::vector<std::unique_ptr<Component>>>(); } //Resize the vector<> if the id is greater than the current size @@ -18,8 +17,7 @@ T & ComponentManager::AddComponent(std::uint32_t id, Args &&... args) { } //Create a new component of type T using perfect forwarding and store its unique_ptr in the vector<> - mComponents[type][id].push_back( - std::make_unique<T>(std::forward<Args>(args)...)); + mComponents[type][id].push_back(std::make_unique<T>(std::forward<Args>(args)...)); return static_cast<T &>(*mComponents[type][id].back().get()); } @@ -68,15 +66,13 @@ ComponentManager::GetComponentsByID(std::uint32_t id) const { if (mComponents.find(type) != mComponents.end()) { //Get the correct vector<> - const std::vector<std::vector<std::unique_ptr<Component>>> & - componentArray + const std::vector<std::vector<std::unique_ptr<Component>>> & componentArray = mComponents.at(type); //Make sure that the id (that we are looking for) is within the boundaries of the vector<> if (id < componentArray.size()) { //Loop trough the whole vector<> - for (const std::unique_ptr<Component> & componentPtr : - componentArray[id]) { + for (const std::unique_ptr<Component> & componentPtr : componentArray[id]) { //Cast the unique_ptr to a raw pointer T * castedComponent = static_cast<T *>(componentPtr.get()); @@ -94,8 +90,7 @@ ComponentManager::GetComponentsByID(std::uint32_t id) const { } template <typename T> -std::vector<std::reference_wrapper<T>> -ComponentManager::GetComponentsByType() const { +std::vector<std::reference_wrapper<T>> ComponentManager::GetComponentsByType() const { //Determine the type of T (this is used as the key of the unordered_map<>) std::type_index type = typeid(T); @@ -107,13 +102,11 @@ ComponentManager::GetComponentsByType() const { if (mComponents.find(type) != mComponents.end()) { //Get the correct vector<> - const std::vector<std::vector<std::unique_ptr<Component>>> & - componentArray + const std::vector<std::vector<std::unique_ptr<Component>>> & componentArray = mComponents.at(type); //Loop through the whole vector<> - for (const std::vector<std::unique_ptr<Component>> & component : - componentArray) { + for (const std::vector<std::unique_ptr<Component>> & component : componentArray) { //Loop trough the whole vector<> for (const std::unique_ptr<Component> & componentPtr : component) { //Cast the unique_ptr to a raw pointer diff --git a/mwe/ecs-homemade/inc/GameObjectMax.hpp b/mwe/ecs-homemade/inc/GameObjectMax.hpp index 2f433bb..92375bb 100644 --- a/mwe/ecs-homemade/inc/GameObjectMax.hpp +++ b/mwe/ecs-homemade/inc/GameObjectMax.hpp @@ -2,6 +2,5 @@ template <typename T, typename... Args> T & GameObject::AddComponent(Args &&... args) { - return ComponentManager::GetInstance().AddComponent<T>( - mId, std::forward<Args>(args)...); + return ComponentManager::GetInstance().AddComponent<T>(mId, std::forward<Args>(args)...); } diff --git a/mwe/ecs-homemade/src/ComponentManager.cpp b/mwe/ecs-homemade/src/ComponentManager.cpp index 536c152..33ba12e 100644 --- a/mwe/ecs-homemade/src/ComponentManager.cpp +++ b/mwe/ecs-homemade/src/ComponentManager.cpp @@ -12,8 +12,7 @@ void ComponentManager::DeleteAllComponentsOfId(std::uint32_t id) { if (id < componentArray .size()) { //Make sure that the id (that we are looking for) is within the boundaries of the vector<> - componentArray[id] - .clear(); //Clear the components at this specific id + componentArray[id].clear(); //Clear the components at this specific id } } } diff --git a/mwe/ecs-homemade/src/GameObjectMax.cpp b/mwe/ecs-homemade/src/GameObjectMax.cpp index 753c8e2..0516f68 100644 --- a/mwe/ecs-homemade/src/GameObjectMax.cpp +++ b/mwe/ecs-homemade/src/GameObjectMax.cpp @@ -2,8 +2,7 @@ #include "ComponentManager.h" -GameObject::GameObject(std::uint32_t id, std::string name, std::string tag, - int layer) +GameObject::GameObject(std::uint32_t id, std::string name, std::string tag, int layer) : mId(id), mName(name), mTag(tag), diff --git a/mwe/ecs-homemade/src/main.cpp b/mwe/ecs-homemade/src/main.cpp index 70c5d2c..85ab1f1 100644 --- a/mwe/ecs-homemade/src/main.cpp +++ b/mwe/ecs-homemade/src/main.cpp @@ -53,8 +53,7 @@ int main() { } std::vector<std::reference_wrapper<BehaviourScript>> scripts - = ComponentManager::GetInstance() - .GetComponentsByType<BehaviourScript>(); + = ComponentManager::GetInstance().GetComponentsByType<BehaviourScript>(); for (BehaviourScript & script : scripts) { //script.onStart(); //script.onUpdate(); @@ -66,10 +65,10 @@ int main() { delete gameObject[i]; } - auto Addtime = std::chrono::duration_cast<std::chrono::microseconds>( - stopAdding - startAdding); - auto LoopTime = std::chrono::duration_cast<std::chrono::microseconds>( - stopLooping - stopAdding); + auto Addtime + = std::chrono::duration_cast<std::chrono::microseconds>(stopAdding - startAdding); + auto LoopTime + = std::chrono::duration_cast<std::chrono::microseconds>(stopLooping - stopAdding); std::cout << "AddTime: " << Addtime.count() << " us" << std::endl; std::cout << "LoopTime: " << LoopTime.count() << " us" << std::endl; } diff --git a/mwe/ecs-memory-efficient/inc/ContiguousContainer.hpp b/mwe/ecs-memory-efficient/inc/ContiguousContainer.hpp index ff8fde4..fa95952 100644 --- a/mwe/ecs-memory-efficient/inc/ContiguousContainer.hpp +++ b/mwe/ecs-memory-efficient/inc/ContiguousContainer.hpp @@ -54,8 +54,7 @@ size_t ContiguousContainer<T>::getSize() const { // Function that returns a vector of references to all stored objects template <typename T> -std::vector<std::reference_wrapper<T>> -ContiguousContainer<T>::getAllReferences() { +std::vector<std::reference_wrapper<T>> ContiguousContainer<T>::getAllReferences() { std::vector<std::reference_wrapper<T>> references; references.reserve(mSize); // Reserve space to avoid reallocation for (size_t i = 0; i < mSize; ++i) { diff --git a/mwe/ecs-memory-efficient/inc/GameObjectMax.hpp b/mwe/ecs-memory-efficient/inc/GameObjectMax.hpp index be3ffa2..909b4be 100644 --- a/mwe/ecs-memory-efficient/inc/GameObjectMax.hpp +++ b/mwe/ecs-memory-efficient/inc/GameObjectMax.hpp @@ -2,18 +2,15 @@ template <typename... Args> void GameObject::addSpriteComponent(Args &&... args) { - ComponentManager::GetInstance().addSpriteComponent( - std::forward<Args>(args)...); + ComponentManager::GetInstance().addSpriteComponent(std::forward<Args>(args)...); } template <typename... Args> void GameObject::addRigidbodyComponent(Args &&... args) { - ComponentManager::GetInstance().addRigidbodyComponent( - std::forward<Args>(args)...); + ComponentManager::GetInstance().addRigidbodyComponent(std::forward<Args>(args)...); } template <typename... Args> void GameObject::addColiderComponent(Args &&... args) { - ComponentManager::GetInstance().addColiderComponent( - std::forward<Args>(args)...); + ComponentManager::GetInstance().addColiderComponent(std::forward<Args>(args)...); } diff --git a/mwe/ecs-memory-efficient/src/ComponentManager.cpp b/mwe/ecs-memory-efficient/src/ComponentManager.cpp index 8c1fd23..e7a8866 100644 --- a/mwe/ecs-memory-efficient/src/ComponentManager.cpp +++ b/mwe/ecs-memory-efficient/src/ComponentManager.cpp @@ -6,17 +6,14 @@ ComponentManager & ComponentManager::GetInstance() { return mInstance; } ComponentManager::ComponentManager() {} -std::vector<std::reference_wrapper<Sprite>> -ComponentManager::getAllSpriteReferences() { +std::vector<std::reference_wrapper<Sprite>> ComponentManager::getAllSpriteReferences() { return mSpriteContainer.getAllReferences(); } -std::vector<std::reference_wrapper<Rigidbody>> -ComponentManager::getAllRigidbodyReferences() { +std::vector<std::reference_wrapper<Rigidbody>> ComponentManager::getAllRigidbodyReferences() { return mRigidbodyContainer.getAllReferences(); } -std::vector<std::reference_wrapper<Colider>> -ComponentManager::getAllColiderReferences() { +std::vector<std::reference_wrapper<Colider>> ComponentManager::getAllColiderReferences() { return mColiderContainer.getAllReferences(); } diff --git a/mwe/ecs-memory-efficient/src/GameObjectMax.cpp b/mwe/ecs-memory-efficient/src/GameObjectMax.cpp index 753c8e2..0516f68 100644 --- a/mwe/ecs-memory-efficient/src/GameObjectMax.cpp +++ b/mwe/ecs-memory-efficient/src/GameObjectMax.cpp @@ -2,8 +2,7 @@ #include "ComponentManager.h" -GameObject::GameObject(std::uint32_t id, std::string name, std::string tag, - int layer) +GameObject::GameObject(std::uint32_t id, std::string name, std::string tag, int layer) : mId(id), mName(name), mTag(tag), diff --git a/mwe/ecs-memory-efficient/src/main.cpp b/mwe/ecs-memory-efficient/src/main.cpp index 9c6f2aa..b564b8c 100644 --- a/mwe/ecs-memory-efficient/src/main.cpp +++ b/mwe/ecs-memory-efficient/src/main.cpp @@ -50,10 +50,10 @@ int main() { delete gameObject[i]; } - auto Addtime = std::chrono::duration_cast<std::chrono::microseconds>( - stopAdding - startAdding); - auto LoopTime = std::chrono::duration_cast<std::chrono::microseconds>( - stopLooping - stopAdding); + auto Addtime + = std::chrono::duration_cast<std::chrono::microseconds>(stopAdding - startAdding); + auto LoopTime + = std::chrono::duration_cast<std::chrono::microseconds>(stopLooping - stopAdding); std::cout << "AddTime: " << Addtime.count() << " us" << std::endl; std::cout << "LoopTime: " << LoopTime.count() << " us" << std::endl; } diff --git a/mwe/events/include/customTypes.h b/mwe/events/include/customTypes.h index 415b989..5a7851b 100644 --- a/mwe/events/include/customTypes.h +++ b/mwe/events/include/customTypes.h @@ -5,14 +5,10 @@ struct Vector2 { float y; // Y component of the vector // Vector subtraction - Vector2 operator-(const Vector2 & other) const { - return {x - other.x, y - other.y}; - } + Vector2 operator-(const Vector2 & other) const { return {x - other.x, y - other.y}; } // Vector addition - Vector2 operator+(const Vector2 & other) const { - return {x + other.x, y + other.y}; - } + Vector2 operator+(const Vector2 & other) const { return {x + other.x, y + other.y}; } // Scalar multiplication Vector2 operator*(float scalar) const { return {x * scalar, y * scalar}; } @@ -31,8 +27,7 @@ struct Collision { Vector2 contactNormal; // Normal vector at the contact point // Constructor to initialize a Collision - Collision(int idA, int idB, const Vector2 & point, const Vector2 & normal, - float depth) + Collision(int idA, int idB, const Vector2 & point, const Vector2 & normal, float depth) : objectIdA(idA), objectIdB(idB), contactPoint(point), diff --git a/mwe/events/include/event.h b/mwe/events/include/event.h index 16c75bf..ee1bf52 100644 --- a/mwe/events/include/event.h +++ b/mwe/events/include/event.h @@ -20,9 +20,7 @@ public: \ static std::uint32_t typeID = UUIDGenerator::getUniqueID(); \ return typeID; \ } \ - virtual std::uint32_t getEventType() const override { \ - return getStaticEventType(); \ - } + virtual std::uint32_t getEventType() const override { return getStaticEventType(); } class Event { public: Event(std::string eventType); @@ -32,16 +30,14 @@ public: void addArgument(const std::string & key, const std::variant<int, std::string, float> & value); - std::variant<int, std::string, float> - getArgument(const std::string & key) const; + std::variant<int, std::string, float> getArgument(const std::string & key) const; std::string getType() const; bool getHandled() const; void markHandled(); private: - std::unordered_map<std::string, std::variant<int, std::string, float>> - eventData; + std::unordered_map<std::string, std::variant<int, std::string, float>> eventData; bool isHandled = false; }; diff --git a/mwe/events/include/eventManager.h b/mwe/events/include/eventManager.h index 508a5e2..30e927f 100644 --- a/mwe/events/include/eventManager.h +++ b/mwe/events/include/eventManager.h @@ -18,11 +18,9 @@ public: } void shutdown(); - void subscribe(int eventType, - std::unique_ptr<IEventHandlerWrapper> && handler, + void subscribe(int eventType, std::unique_ptr<IEventHandlerWrapper> && handler, int eventId); - void unsubscribe(int eventType, const std::string & handlerName, - int eventId); + void unsubscribe(int eventType, const std::string & handlerName, int eventId); void triggerEvent(const Event & event_, int eventId); void queueEvent(std::unique_ptr<Event> && event_, int eventId); void dispatchEvents(); @@ -30,11 +28,9 @@ public: private: EventManager() = default; std::vector<std::pair<std::unique_ptr<Event>, int>> eventsQueue; - std::unordered_map<int, std::vector<std::unique_ptr<IEventHandlerWrapper>>> - subscribers; + std::unordered_map<int, std::vector<std::unique_ptr<IEventHandlerWrapper>>> subscribers; std::unordered_map< - int, std::unordered_map< - int, std::vector<std::unique_ptr<IEventHandlerWrapper>>>> + int, std::unordered_map<int, std::vector<std::unique_ptr<IEventHandlerWrapper>>>> subscribersByEventId; }; @@ -42,18 +38,16 @@ template <typename EventType> inline void subscribe(const EventHandler<EventType> & callback, int eventId = 0, const bool unsubscribeOnSuccess = false) { std::unique_ptr<IEventHandlerWrapper> handler - = std::make_unique<EventHandlerWrapper<EventType>>( - callback, unsubscribeOnSuccess); - EventManager::getInstance().subscribe(EventType::getStaticEventType(), - std::move(handler), eventId); + = std::make_unique<EventHandlerWrapper<EventType>>(callback, unsubscribeOnSuccess); + EventManager::getInstance().subscribe(EventType::getStaticEventType(), std::move(handler), + eventId); } template <typename EventType> -inline void unsubscribe(const EventHandler<EventType> & callback, - int eventId = 0) { +inline void unsubscribe(const EventHandler<EventType> & callback, int eventId = 0) { const std::string handlerName = callback.target_type().name(); - EventManager::getInstance().unsubscribe(EventType::getStaticEventType(), - handlerName, eventId); + EventManager::getInstance().unsubscribe(EventType::getStaticEventType(), handlerName, + eventId); } inline void triggerEvent(const Event & triggeredEvent, int eventId = 0) { @@ -61,6 +55,6 @@ inline void triggerEvent(const Event & triggeredEvent, int eventId = 0) { } inline void queueEvent(std::unique_ptr<Event> && queuedEvent, int eventId = 0) { - EventManager::getInstance().queueEvent( - std::forward<std::unique_ptr<Event>>(queuedEvent), eventId); + EventManager::getInstance().queueEvent(std::forward<std::unique_ptr<Event>>(queuedEvent), + eventId); } diff --git a/mwe/events/src/event.cpp b/mwe/events/src/event.cpp index 8ffa0b1..0040c73 100644 --- a/mwe/events/src/event.cpp +++ b/mwe/events/src/event.cpp @@ -8,14 +8,11 @@ void Event::addArgument(const std::string & key, eventData[key] = value; } -std::variant<int, std::string, float> -Event::getArgument(const std::string & key) const { +std::variant<int, std::string, float> Event::getArgument(const std::string & key) const { return eventData.at(key); } -std::string Event::getType() const { - return std::get<std::string>(eventData.at("eventType")); -} +std::string Event::getType() const { return std::get<std::string>(eventData.at("eventType")); } std::string Event::toString() const { return std::to_string(getEventType()); } bool Event::getHandled() const { return isHandled; } @@ -32,9 +29,7 @@ Keycode KeyPressedEvent::getKeyCode() const { return key; } int KeyPressedEvent::getRepeatCount() const { return repeatCount; } // KeyReleasedEvent class methods -KeyReleasedEvent::KeyReleasedEvent(int keycode) - : Event("KeyReleasedEvent"), - key(keycode) {} +KeyReleasedEvent::KeyReleasedEvent(int keycode) : Event("KeyReleasedEvent"), key(keycode) {} Keycode KeyReleasedEvent::getKeyCode() const { return key; } @@ -44,22 +39,16 @@ MousePressedEvent::MousePressedEvent(int mouseX, int mouseY) mouseX(mouseX), mouseY(mouseY) {} -std::pair<int, int> MousePressedEvent::getMousePosition() const { - return {mouseX, mouseY}; -} +std::pair<int, int> MousePressedEvent::getMousePosition() const { return {mouseX, mouseY}; } //Collision event CollisionEvent::CollisionEvent(Collision collision) : collisionData(collision), Event("CollisionEvent") {} -Collision CollisionEvent::getCollisionData() const { - return this->collisionData; -} +Collision CollisionEvent::getCollisionData() const { return this->collisionData; } -TextSubmitEvent::TextSubmitEvent(std::string text) - : text(text), - Event("TextSubmitEvent") {} +TextSubmitEvent::TextSubmitEvent(std::string text) : text(text), Event("TextSubmitEvent") {} std::string TextSubmitEvent::getText() const { return this->text; } @@ -68,9 +57,7 @@ MouseReleasedEvent::MouseReleasedEvent(int x, int y, MouseButton button) mouseY(y), button(button), Event("MouseReleased") {} -std::pair<int, int> MouseReleasedEvent::getMousePosition() const { - return {mouseX, mouseY}; -} +std::pair<int, int> MouseReleasedEvent::getMousePosition() const { return {mouseX, mouseY}; } MouseClickEvent::MouseClickEvent(int x, int y, MouseButton button) : mouseX(x), mouseY(y), @@ -80,9 +67,5 @@ MouseMovedEvent::MouseMovedEvent(int x, int y) : mouseX(x), mouseY(y), Event("MouseMovedEvent") {} -std::pair<int, int> MouseClickEvent::getMousePosition() const { - return {mouseX, mouseY}; -} -std::pair<int, int> MouseMovedEvent::getMousePosition() const { - return {mouseX, mouseY}; -} +std::pair<int, int> MouseClickEvent::getMousePosition() const { return {mouseX, mouseY}; } +std::pair<int, int> MouseMovedEvent::getMousePosition() const { return {mouseX, mouseY}; } diff --git a/mwe/events/src/eventManager.cpp b/mwe/events/src/eventManager.cpp index 34a093d..9e7d880 100644 --- a/mwe/events/src/eventManager.cpp +++ b/mwe/events/src/eventManager.cpp @@ -2,33 +2,27 @@ void EventManager::shutdown() { subscribers.clear(); } -void EventManager::subscribe(int eventType, - std::unique_ptr<IEventHandlerWrapper> && handler, +void EventManager::subscribe(int eventType, std::unique_ptr<IEventHandlerWrapper> && handler, int eventId) { if (eventId) { std::unordered_map< - int, std::unordered_map< - int, std::vector<std::unique_ptr<IEventHandlerWrapper>>>>:: + int, std::unordered_map<int, std::vector<std::unique_ptr<IEventHandlerWrapper>>>>:: iterator subscribers = subscribersByEventId.find(eventType); if (subscribers != subscribersByEventId.end()) { - std::unordered_map< - int, std::vector<std::unique_ptr<IEventHandlerWrapper>>> & + std::unordered_map<int, std::vector<std::unique_ptr<IEventHandlerWrapper>>> & handlersMap = subscribers->second; std::unordered_map< - int, - std::vector<std::unique_ptr<IEventHandlerWrapper>>>::iterator - handlers + int, std::vector<std::unique_ptr<IEventHandlerWrapper>>>::iterator handlers = handlersMap.find(eventId); if (handlers != handlersMap.end()) { handlers->second.emplace_back(std::move(handler)); return; } } - subscribersByEventId[eventType][eventId].emplace_back( - std::move(handler)); + subscribersByEventId[eventType][eventId].emplace_back(std::move(handler)); } else { auto & handlers = subscribers[eventType]; @@ -36,29 +30,23 @@ void EventManager::subscribe(int eventType, } } -void EventManager::unsubscribe(int eventType, const std::string & handlerName, - int eventId) { +void EventManager::unsubscribe(int eventType, const std::string & handlerName, int eventId) { if (eventId) { std::unordered_map< - int, std::unordered_map< - int, std::vector<std::unique_ptr<IEventHandlerWrapper>>>>:: + int, std::unordered_map<int, std::vector<std::unique_ptr<IEventHandlerWrapper>>>>:: iterator subscriberList = subscribersByEventId.find(eventType); if (subscriberList != subscribersByEventId.end()) { - std::unordered_map< - int, std::vector<std::unique_ptr<IEventHandlerWrapper>>> & + std::unordered_map<int, std::vector<std::unique_ptr<IEventHandlerWrapper>>> & handlersMap = subscriberList->second; std::unordered_map< - int, - std::vector<std::unique_ptr<IEventHandlerWrapper>>>::iterator - handlers + int, std::vector<std::unique_ptr<IEventHandlerWrapper>>>::iterator handlers = handlersMap.find(eventId); if (handlers != handlersMap.end()) { std::vector<std::unique_ptr<IEventHandlerWrapper>> & callbacks = handlers->second; - for (std::vector< - std::unique_ptr<IEventHandlerWrapper>>::iterator it + for (std::vector<std::unique_ptr<IEventHandlerWrapper>>::iterator it = callbacks.begin(); it != callbacks.end(); ++it) { if (it->get()->getType() == handlerName) { @@ -69,13 +57,11 @@ void EventManager::unsubscribe(int eventType, const std::string & handlerName, } } } else { - std::unordered_map< - int, std::vector<std::unique_ptr<IEventHandlerWrapper>>>::iterator + std::unordered_map<int, std::vector<std::unique_ptr<IEventHandlerWrapper>>>::iterator handlersIt = subscribers.find(eventType); if (handlersIt != subscribers.end()) { - std::vector<std::unique_ptr<IEventHandlerWrapper>> & handlers - = handlersIt->second; + std::vector<std::unique_ptr<IEventHandlerWrapper>> & handlers = handlersIt->second; for (std::vector<std::unique_ptr<IEventHandlerWrapper>>::iterator it = handlers.begin(); it != handlers.end(); ++it) { @@ -90,8 +76,7 @@ void EventManager::unsubscribe(int eventType, const std::string & handlerName, void EventManager::triggerEvent(const Event & event_, int eventId) { if (eventId > 0) { - auto handlersIt - = subscribersByEventId[event_.getEventType()].find(eventId); + auto handlersIt = subscribersByEventId[event_.getEventType()].find(eventId); if (handlersIt != subscribersByEventId[event_.getEventType()].end()) { std::vector<std::unique_ptr<IEventHandlerWrapper>> & callbacks = handlersIt->second; diff --git a/mwe/events/src/iKeyListener.cpp b/mwe/events/src/iKeyListener.cpp index 0235fab..d5d1d90 100644 --- a/mwe/events/src/iKeyListener.cpp +++ b/mwe/events/src/iKeyListener.cpp @@ -3,11 +3,9 @@ IKeyListener::~IKeyListener() { unsubscribeEvents(); } void IKeyListener::subscribeEvents(int listenerId) { - keyPressedHandler - = [this](const KeyPressedEvent & event) { this->onKeyPressed(event); }; - keyReleasedHandler = [this](const KeyReleasedEvent & event) { - this->onKeyReleased(event); - }; + keyPressedHandler = [this](const KeyPressedEvent & event) { this->onKeyPressed(event); }; + keyReleasedHandler + = [this](const KeyReleasedEvent & event) { this->onKeyReleased(event); }; subscribe<KeyPressedEvent>(keyPressedHandler, listenerId); subscribe<KeyReleasedEvent>(keyReleasedHandler, listenerId); diff --git a/mwe/events/src/iMouseListener.cpp b/mwe/events/src/iMouseListener.cpp index 69d8c9f..53e6f80 100644 --- a/mwe/events/src/iMouseListener.cpp +++ b/mwe/events/src/iMouseListener.cpp @@ -2,17 +2,12 @@ IMouseListener::~IMouseListener() { unsubscribeEvents(); } void IMouseListener::subscribeEvents(int listenerId) { - mouseClickHandler = [this](const MouseClickEvent & event) { - this->onMouseClicked(event); - }; - mousePressHandler = [this](const MousePressedEvent & event) { - this->onMousePressed(event); - }; - mouseReleaseHandler = [this](const MouseReleasedEvent & event) { - this->onMouseReleased(event); - }; - mouseMoveHandler - = [this](const MouseMovedEvent & event) { this->onMouseMoved(event); }; + mouseClickHandler = [this](const MouseClickEvent & event) { this->onMouseClicked(event); }; + mousePressHandler + = [this](const MousePressedEvent & event) { this->onMousePressed(event); }; + mouseReleaseHandler + = [this](const MouseReleasedEvent & event) { this->onMouseReleased(event); }; + mouseMoveHandler = [this](const MouseMovedEvent & event) { this->onMouseMoved(event); }; subscribe<MouseClickEvent>(mouseClickHandler, listenerId); subscribe<MousePressedEvent>(mousePressHandler, listenerId); diff --git a/mwe/events/src/inputSystem.cpp b/mwe/events/src/inputSystem.cpp index b87b12e..d740c9e 100644 --- a/mwe/events/src/inputSystem.cpp +++ b/mwe/events/src/inputSystem.cpp @@ -3,9 +3,7 @@ InputSystem::InputSystem() {} void InputSystem::registerButton(Button * button) { buttons.push_back(button); } -void InputSystem::registerTextInput(TextInput * input) { - textInputs.push_back(input); -} +void InputSystem::registerTextInput(TextInput * input) { textInputs.push_back(input); } void InputSystem::registerText(Text * label) { texts.push_back(label); } void InputSystem::processInput() { @@ -16,8 +14,7 @@ void InputSystem::processInput() { triggerEvent(ShutDownEvent()); break; case SDL_KEYDOWN: - triggerEvent( - KeyPressedEvent(getCustomKey(event.key.keysym.sym))); + triggerEvent(KeyPressedEvent(getCustomKey(event.key.keysym.sym))); processKeyPress(event.key.keysym.sym); break; case SDL_TEXTINPUT: @@ -37,15 +34,14 @@ void InputSystem::processInput() { void InputSystem::processMouseClick(int mouseX, int mouseY) { for (auto * button : buttons) { - if (mouseX >= button->x && mouseX <= (button->x + button->width) - && mouseY >= button->y && mouseY <= (button->y + button->height)) { + if (mouseX >= button->x && mouseX <= (button->x + button->width) && mouseY >= button->y + && mouseY <= (button->y + button->height)) { button->onClick(); } } for (auto * textInput : textInputs) { if (mouseX >= textInput->x && mouseX <= textInput->x + textInput->width - && mouseY >= textInput->y - && mouseY <= textInput->y + textInput->height) { + && mouseY >= textInput->y && mouseY <= textInput->y + textInput->height) { textInput->isActive = true; } else { textInput->isActive = false; diff --git a/mwe/events/src/keyListenerTest.cpp b/mwe/events/src/keyListenerTest.cpp index 8446dfa..f45dffd 100644 --- a/mwe/events/src/keyListenerTest.cpp +++ b/mwe/events/src/keyListenerTest.cpp @@ -1,8 +1,6 @@ #include "keyListenerTest.h" -KeyListenerTest::KeyListenerTest(int listenerId) { - subscribeEvents(listenerId); -} +KeyListenerTest::KeyListenerTest(int listenerId) { subscribeEvents(listenerId); } KeyListenerTest::~KeyListenerTest() { unsubscribeEvents(); } diff --git a/mwe/events/src/loopManager.cpp b/mwe/events/src/loopManager.cpp index 0b7d888..c58a5e7 100644 --- a/mwe/events/src/loopManager.cpp +++ b/mwe/events/src/loopManager.cpp @@ -1,8 +1,7 @@ #include "loopManager.h" LoopManager::LoopManager() : inputSystem(std::make_unique<InputSystem>()) { - shutdownHandler - = [this](const ShutDownEvent & event) { this->onShutdown(event); }; + shutdownHandler = [this](const ShutDownEvent & event) { this->onShutdown(event); }; subscribe(shutdownHandler); } void LoopManager::processInput() { @@ -63,17 +62,15 @@ void LoopManager::setup() { subscribe<KeyPressedEvent>(callback, false); EventHandler<MousePressedEvent> mouseCallback = onMouse; subscribe<MousePressedEvent>(mouseCallback, false); - EventHandler<KeyPressedEvent> closeWindowCallback - = [this](const KeyPressedEvent & e) { - if (e.getKeyCode() == Escape) { - this->setRunning(false); - } - }; + EventHandler<KeyPressedEvent> closeWindowCallback = [this](const KeyPressedEvent & e) { + if (e.getKeyCode() == Escape) { + this->setRunning(false); + } + }; subscribe<KeyPressedEvent>(closeWindowCallback, false); Button * testButton = new Button(200, 200); testButton->color = {100, 0, 100}; - testButton->onClick - = []() { std::cout << "Button was clicked" << std::endl; }; + testButton->onClick = []() { std::cout << "Button was clicked" << std::endl; }; testButton->x = 200; testButton->y = 200; inputSystem->registerButton(testButton); @@ -93,9 +90,7 @@ void LoopManager::render() { window.renderUIObjects(); } } -void LoopManager::onShutdown(const ShutDownEvent & e) { - this->gameRunning = false; -} +void LoopManager::onShutdown(const ShutDownEvent & e) { this->gameRunning = false; } void LoopManager::update() { //fprintf(stderr, "**********normal update********** \n"); LoopTimer & timer = LoopTimer::getInstance(); diff --git a/mwe/events/src/main.cpp b/mwe/events/src/main.cpp index f4e7390..ad0fd69 100644 --- a/mwe/events/src/main.cpp +++ b/mwe/events/src/main.cpp @@ -25,8 +25,8 @@ private: int playerID; }; void onPlayerDamaged(const PlayerDamagedEvent & e) { - std::cout << "Player " << e.getPlayerID() << " took " << e.getDamage() - << " damage." << std::endl; + std::cout << "Player " << e.getPlayerID() << " took " << e.getDamage() << " damage." + << std::endl; } void onKeyPressed1(const KeyPressedEvent & e) { @@ -38,8 +38,7 @@ void onKeyPressed(const KeyPressedEvent & e) { fprintf(stderr, "second function KeyCode %d\n", keyCode); } void CollisionHandler(const CollisionEvent & e) { - std::cout << "collision betwee object id: " - << e.getCollisionData().objectIdA + std::cout << "collision betwee object id: " << e.getCollisionData().objectIdA << " and id: " << e.getCollisionData().objectIdB << std::endl; } void testCollisionEvent() { diff --git a/mwe/events/src/mouseListenerTest.cpp b/mwe/events/src/mouseListenerTest.cpp index a2a7e6d..7b35f4e 100644 --- a/mwe/events/src/mouseListenerTest.cpp +++ b/mwe/events/src/mouseListenerTest.cpp @@ -1,8 +1,6 @@ #include "mouseListenerTest.h" -MouseListenerTest::MouseListenerTest(int listenerId) { - subscribeEvents(listenerId); -} +MouseListenerTest::MouseListenerTest(int listenerId) { subscribeEvents(listenerId); } MouseListenerTest::~MouseListenerTest() { unsubscribeEvents(); } @@ -12,13 +10,13 @@ void MouseListenerTest::onMouseClicked(const MouseClickEvent & event) { } void MouseListenerTest::onMousePressed(const MousePressedEvent & event) { - std::cout << "Mouse button pressed at: (" << event.getMousePosition().first - << ", " << event.getMousePosition().second << ")" << std::endl; + std::cout << "Mouse button pressed at: (" << event.getMousePosition().first << ", " + << event.getMousePosition().second << ")" << std::endl; } void MouseListenerTest::onMouseReleased(const MouseReleasedEvent & event) { - std::cout << "Mouse button released at: (" << event.getMousePosition().first - << ", " << event.getMousePosition().second << ")" << std::endl; + std::cout << "Mouse button released at: (" << event.getMousePosition().first << ", " + << event.getMousePosition().second << ")" << std::endl; } void MouseListenerTest::onMouseMoved(const MouseMovedEvent & event) { diff --git a/mwe/events/src/timer.cpp b/mwe/events/src/timer.cpp index 0b89bf5..0f8339f 100644 --- a/mwe/events/src/timer.cpp +++ b/mwe/events/src/timer.cpp @@ -45,8 +45,7 @@ void LoopTimer::enforceFrameRate() { double frameDuration = (currentFrameTime - lastFrameTime) / 1000.0; if (frameDuration < frameTargetTime) { - uint32_t delayTime - = (uint32_t) ((frameTargetTime - frameDuration) * 1000.0); + uint32_t delayTime = (uint32_t) ((frameTargetTime - frameDuration) * 1000.0); SDL_Delay(delayTime); } } diff --git a/mwe/events/src/uiRenderer.cpp b/mwe/events/src/uiRenderer.cpp index 9fec272..ca8d284 100644 --- a/mwe/events/src/uiRenderer.cpp +++ b/mwe/events/src/uiRenderer.cpp @@ -24,21 +24,18 @@ void UIRenderer::renderButton(Button * button) { // Private helper function to render a Text void UIRenderer::renderText(Text * text) { if (text->font != nullptr) { - SDL_Color sdlColor - = {text->color.red, text->color.green, text->color.blue, 255}; + SDL_Color sdlColor = {text->color.red, text->color.green, text->color.blue, 255}; SDL_Surface * textSurface = TTF_RenderText_Blended(text->font, text->text.c_str(), sdlColor); if (!textSurface) { - std::cerr << "Error creating text surface: " << TTF_GetError() - << std::endl; + std::cerr << "Error creating text surface: " << TTF_GetError() << std::endl; return; } - SDL_Texture * textTexture - = SDL_CreateTextureFromSurface(renderer, textSurface); + SDL_Texture * textTexture = SDL_CreateTextureFromSurface(renderer, textSurface); if (!textTexture) { - std::cerr << "Error creating texture from surface: " - << SDL_GetError() << std::endl; + std::cerr << "Error creating texture from surface: " << SDL_GetError() + << std::endl; SDL_FreeSurface(textSurface); return; } diff --git a/mwe/events/src/window.cpp b/mwe/events/src/window.cpp index f482b7f..af2b627 100644 --- a/mwe/events/src/window.cpp +++ b/mwe/events/src/window.cpp @@ -11,9 +11,8 @@ bool WindowManager::initWindow() { return false; } - window = SDL_CreateWindow("SDL Tutorial", SDL_WINDOWPOS_UNDEFINED, - SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, - SCREEN_HEIGHT, SDL_WINDOW_SHOWN); + window = SDL_CreateWindow("SDL Tutorial", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, + SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN); if (!window) { std::cerr << "Error creating SDL Window.\n"; return false; @@ -36,9 +35,7 @@ void WindowManager::destroyWindow() { } SDL_Renderer * WindowManager::getRenderer() { return renderer; } -void WindowManager::addUIObject(UIObject * uiObject) { - uiObjects.push_back(uiObject); -} +void WindowManager::addUIObject(UIObject * uiObject) { uiObjects.push_back(uiObject); } void WindowManager::renderUIObjects() { for (UIObject * obj : uiObjects) { diff --git a/mwe/events/versions/delayBased.cpp b/mwe/events/versions/delayBased.cpp index 253a03a..634de9c 100644 --- a/mwe/events/versions/delayBased.cpp +++ b/mwe/events/versions/delayBased.cpp @@ -32,8 +32,7 @@ void LoopManager::setup() { LoopTimer::getInstance().setFPS(210); for (int i = 0; i < 2; i++) { - GameObject * square2 - = new GameObject("square2", i * 40, i * 40, 20, 20, 0, 0); + GameObject * square2 = new GameObject("square2", i * 40, i * 40, 20, 20, 0, 0); objectList.push_back(square2); } } diff --git a/mwe/gameloop/include/gameObject.h b/mwe/gameloop/include/gameObject.h index abdc9b0..2764215 100644 --- a/mwe/gameloop/include/gameObject.h +++ b/mwe/gameloop/include/gameObject.h @@ -3,8 +3,8 @@ class GameObject { public: GameObject(); - GameObject(std::string name, float x, float y, float width, float height, - float velX, float velY); + GameObject(std::string name, float x, float y, float width, float height, float velX, + float velY); std::string getName() const; float getX() const; float getY() const; diff --git a/mwe/gameloop/src/gameObject.cpp b/mwe/gameloop/src/gameObject.cpp index b33dc78..809e25f 100644 --- a/mwe/gameloop/src/gameObject.cpp +++ b/mwe/gameloop/src/gameObject.cpp @@ -24,8 +24,8 @@ void GameObject::setVelX(float value) { velX = value; } void GameObject::setVelY(float value) { velY = value; } -GameObject::GameObject(std::string name, float x, float y, float width, - float height, float velX, float velY) +GameObject::GameObject(std::string name, float x, float y, float width, float height, + float velX, float velY) : name(name), x(x), y(y), diff --git a/mwe/gameloop/src/loopManager.cpp b/mwe/gameloop/src/loopManager.cpp index 49d65fb..fb06995 100644 --- a/mwe/gameloop/src/loopManager.cpp +++ b/mwe/gameloop/src/loopManager.cpp @@ -18,11 +18,11 @@ void LoopManager::processInput() { if (event.key.keysym.sym == SDLK_ESCAPE) { gameRunning = false; } else if (event.key.keysym.sym == SDLK_i) { - LoopTimer::getInstance().setGameScale( - LoopTimer::getInstance().getGameScale() + 0.1); + LoopTimer::getInstance().setGameScale(LoopTimer::getInstance().getGameScale() + + 0.1); } else if (event.key.keysym.sym == SDLK_k) { - LoopTimer::getInstance().setGameScale( - LoopTimer::getInstance().getGameScale() - 0.1); + LoopTimer::getInstance().setGameScale(LoopTimer::getInstance().getGameScale() + - 0.1); } break; @@ -57,8 +57,7 @@ void LoopManager::setup() { LoopTimer::getInstance().setFPS(10); this->gameRunning = true; for (int i = 1; i < 3; i++) { - GameObject * square - = new GameObject("square2", i * 60, i * 60, 20, 20, 0, 0); + GameObject * square = new GameObject("square2", i * 60, i * 60, 20, 20, 0, 0); objectList.push_back(square); } } diff --git a/mwe/gameloop/src/timer.cpp b/mwe/gameloop/src/timer.cpp index 97baef6..5ae1564 100644 --- a/mwe/gameloop/src/timer.cpp +++ b/mwe/gameloop/src/timer.cpp @@ -45,8 +45,7 @@ void LoopTimer::enforceFrameRate() { double frameDuration = (currentFrameTime - lastFrameTime) / 1000.0; if (frameDuration < frameTargetTime) { - uint32_t delayTime - = (uint32_t) ((frameTargetTime - frameDuration) * 1000.0); + uint32_t delayTime = (uint32_t) ((frameTargetTime - frameDuration) * 1000.0); SDL_Delay(delayTime); } } diff --git a/mwe/gameloop/src/window.cpp b/mwe/gameloop/src/window.cpp index dd1d98f..8f802e1 100644 --- a/mwe/gameloop/src/window.cpp +++ b/mwe/gameloop/src/window.cpp @@ -36,9 +36,8 @@ bool WindowManager::initWindow() { fprintf(stderr, "Error inititalising SDL.\n"); return false; } - window = SDL_CreateWindow("SDL Tutorial", SDL_WINDOWPOS_UNDEFINED, - SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, - SCREEN_HEIGHT, SDL_WINDOW_SHOWN); + window = SDL_CreateWindow("SDL Tutorial", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, + SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN); if (!window) { fprintf(stderr, "Error creating SDL Window. \n"); return false; diff --git a/mwe/gameloop/versions/delayBased.cpp b/mwe/gameloop/versions/delayBased.cpp index 253a03a..634de9c 100644 --- a/mwe/gameloop/versions/delayBased.cpp +++ b/mwe/gameloop/versions/delayBased.cpp @@ -32,8 +32,7 @@ void LoopManager::setup() { LoopTimer::getInstance().setFPS(210); for (int i = 0; i < 2; i++) { - GameObject * square2 - = new GameObject("square2", i * 40, i * 40, 20, 20, 0, 0); + GameObject * square2 = new GameObject("square2", i * 40, i * 40, 20, 20, 0, 0); objectList.push_back(square2); } } diff --git a/mwe/resource-manager/TextureMap.cpp b/mwe/resource-manager/TextureMap.cpp index d82975c..284f8a8 100644 --- a/mwe/resource-manager/TextureMap.cpp +++ b/mwe/resource-manager/TextureMap.cpp @@ -15,8 +15,7 @@ TextureMap::~TextureMap() { } //public -bool TextureMap::loadFromFile(const std::string & path, - SDL_Renderer * renderer) { +bool TextureMap::loadFromFile(const std::string & path, SDL_Renderer * renderer) { assert(renderer != nullptr); assert(!path.empty()); @@ -34,12 +33,11 @@ bool TextureMap::loadFromFile(const std::string & path, constexpr std::int32_t bmask = 0x00ff0000; const std::int32_t amask = c == 4 ? 0xff000000 : 0; - auto * surface = SDL_CreateRGBSurfaceFrom(data, x, y, c * 8, pitch, - rmask, gmask, bmask, amask); + auto * surface + = SDL_CreateRGBSurfaceFrom(data, x, y, c * 8, pitch, rmask, gmask, bmask, amask); if (!surface) { - std::cerr << "Unable to create texture surface: " << SDL_GetError() - << "\n"; + std::cerr << "Unable to create texture surface: " << SDL_GetError() << "\n"; stbi_image_free(data); return false; } diff --git a/mwe/resource-manager/main.cpp b/mwe/resource-manager/main.cpp index b6416f6..1910af8 100644 --- a/mwe/resource-manager/main.cpp +++ b/mwe/resource-manager/main.cpp @@ -23,9 +23,8 @@ int main() { SDL_Event event; - SDL_Window * window - = SDL_CreateWindow("Tessting resources", SDL_WINDOWPOS_UNDEFINED, - SDL_WINDOWPOS_UNDEFINED, 640, 480, 0); + SDL_Window * window = SDL_CreateWindow("Tessting resources", SDL_WINDOWPOS_UNDEFINED, + SDL_WINDOWPOS_UNDEFINED, 640, 480, 0); SDL_Renderer * renderer = SDL_CreateRenderer(window, -1, 0); diff --git a/mwe/resource-manager/map_layer.cpp b/mwe/resource-manager/map_layer.cpp index 6339707..17792a6 100644 --- a/mwe/resource-manager/map_layer.cpp +++ b/mwe/resource-manager/map_layer.cpp @@ -20,8 +20,7 @@ bool MapLayer::create(const tmx::Map & map, std::uint32_t layerIndex, const auto & tileSets = map.getTilesets(); const auto tintColour = layer.getTintColour(); - const SDL_Colour vertColour - = {tintColour.r, tintColour.g, tintColour.b, tintColour.a}; + const SDL_Colour vertColour = {tintColour.r, tintColour.g, tintColour.b, tintColour.a}; for (auto i = 0u; i < tileSets.size(); ++i) { //check tile ID to see if it falls within the current tile set @@ -40,8 +39,7 @@ bool MapLayer::create(const tmx::Map & map, std::uint32_t layerIndex, for (auto x = 0u; x < mapSize.x; ++x) { const auto idx = y * mapSize.x + x; if (idx < tileIDs.size() && tileIDs[idx].ID >= ts.getFirstGID() - && tileIDs[idx].ID - < (ts.getFirstGID() + ts.getTileCount())) { + && tileIDs[idx].ID < (ts.getFirstGID() + ts.getTileCount())) { //tex coords auto idIndex = (tileIDs[idx].ID - ts.getFirstGID()); float u = static_cast<float>(idIndex % tileCountX); @@ -55,36 +53,24 @@ bool MapLayer::create(const tmx::Map & map, std::uint32_t layerIndex, v /= textures[i]->getSize().y; //vert pos - const float tilePosX - = static_cast<float>(x) * mapTileSize.x; - const float tilePosY - = (static_cast<float>(y) * mapTileSize.y); + const float tilePosX = static_cast<float>(x) * mapTileSize.x; + const float tilePosY = (static_cast<float>(y) * mapTileSize.y); //push back to vert array - SDL_Vertex vert - = {{tilePosX, tilePosY}, vertColour, {u, v}}; + SDL_Vertex vert = {{tilePosX, tilePosY}, vertColour, {u, v}}; verts.emplace_back(vert); - vert = {{tilePosX + mapTileSize.x, tilePosY}, - vertColour, - {u + uNorm, v}}; + vert = {{tilePosX + mapTileSize.x, tilePosY}, vertColour, {u + uNorm, v}}; verts.emplace_back(vert); - vert = {{tilePosX, tilePosY + mapTileSize.y}, - vertColour, - {u, v + vNorm}}; + vert = {{tilePosX, tilePosY + mapTileSize.y}, vertColour, {u, v + vNorm}}; verts.emplace_back(vert); - vert = {{tilePosX, tilePosY + mapTileSize.y}, - vertColour, - {u, v + vNorm}}; + vert = {{tilePosX, tilePosY + mapTileSize.y}, vertColour, {u, v + vNorm}}; verts.emplace_back(vert); - vert = {{tilePosX + mapTileSize.x, tilePosY}, - vertColour, - {u + uNorm, v}}; + vert = {{tilePosX + mapTileSize.x, tilePosY}, vertColour, {u + uNorm, v}}; verts.emplace_back(vert); - vert - = {{tilePosX + mapTileSize.x, tilePosY + mapTileSize.y}, - vertColour, - {u + uNorm, v + vNorm}}; + vert = {{tilePosX + mapTileSize.x, tilePosY + mapTileSize.y}, + vertColour, + {u + uNorm, v + vNorm}}; verts.emplace_back(vert); } } @@ -104,7 +90,6 @@ void MapLayer::draw(SDL_Renderer * renderer) const { assert(renderer); for (const auto & s : m_subsets) { SDL_RenderGeometry(renderer, s.texture, s.vertexData.data(), - static_cast<std::int32_t>(s.vertexData.size()), - nullptr, 0); + static_cast<std::int32_t>(s.vertexData.size()), nullptr, 0); } } diff --git a/mwe/resource-manager/resource_converter.cpp b/mwe/resource-manager/resource_converter.cpp index 0477dc2..632f630 100644 --- a/mwe/resource-manager/resource_converter.cpp +++ b/mwe/resource-manager/resource_converter.cpp @@ -17,8 +17,7 @@ SDL_Surface * ResourceConverter::FromStringToImage(const Texture & resource) { const std::string & content = resource.getContent(); SDL_RWops * rw = SDL_RWFromConstMem(content.data(), content.size()); if (!rw) { - std::cerr << "Failed to create SDL_RWops: " << SDL_GetError() - << std::endl; + std::cerr << "Failed to create SDL_RWops: " << SDL_GetError() << std::endl; return nullptr; } diff --git a/mwe/resource-manager/spritesheet.cpp b/mwe/resource-manager/spritesheet.cpp index a5881e5..9739e01 100644 --- a/mwe/resource-manager/spritesheet.cpp +++ b/mwe/resource-manager/spritesheet.cpp @@ -4,8 +4,6 @@ #include <string> -SpriteSheet::SpriteSheet(const std::string & content) { - this->m_content = content; -} +SpriteSheet::SpriteSheet(const std::string & content) { this->m_content = content; } SpriteSheet::~SpriteSheet() {} diff --git a/mwe/resource-manager/stb_image.h b/mwe/resource-manager/stb_image.h index ce0cc10..3462f3a 100644 --- a/mwe/resource-manager/stb_image.h +++ b/mwe/resource-manager/stb_image.h @@ -410,9 +410,8 @@ typedef struct { int (*read)( void * user, char * data, int size); // fill 'data' with 'size' bytes. return number of bytes actually read - void (*skip)( - void * user, - int n); // skip the next 'n' bytes, or 'unget' the last -n bytes if negative + void (*skip)(void * user, + int n); // skip the next 'n' bytes, or 'unget' the last -n bytes if negative int (*eof)(void * user); // returns nonzero if we are at end of file/data } stbi_io_callbacks; @@ -421,33 +420,28 @@ typedef struct { // 8-bits-per-channel interface // -STBIDEF stbi_uc * stbi_load_from_memory(stbi_uc const * buffer, int len, - int * x, int * y, - int * channels_in_file, - int desired_channels); -STBIDEF stbi_uc * stbi_load_from_callbacks(stbi_io_callbacks const * clbk, - void * user, int * x, int * y, - int * channels_in_file, +STBIDEF stbi_uc * stbi_load_from_memory(stbi_uc const * buffer, int len, int * x, int * y, + int * channels_in_file, int desired_channels); +STBIDEF stbi_uc * stbi_load_from_callbacks(stbi_io_callbacks const * clbk, void * user, + int * x, int * y, int * channels_in_file, int desired_channels); #ifndef STBI_NO_STDIO -STBIDEF stbi_uc * stbi_load(char const * filename, int * x, int * y, - int * channels_in_file, int desired_channels); -STBIDEF stbi_uc * stbi_load_from_file(FILE * f, int * x, int * y, - int * channels_in_file, +STBIDEF stbi_uc * stbi_load(char const * filename, int * x, int * y, int * channels_in_file, + int desired_channels); +STBIDEF stbi_uc * stbi_load_from_file(FILE * f, int * x, int * y, int * channels_in_file, int desired_channels); // for stbi_load_from_file, file pointer is left pointing immediately after image #endif #ifndef STBI_NO_GIF -STBIDEF stbi_uc * stbi_load_gif_from_memory(stbi_uc const * buffer, int len, - int ** delays, int * x, int * y, - int * z, int * comp, int req_comp); +STBIDEF stbi_uc * stbi_load_gif_from_memory(stbi_uc const * buffer, int len, int ** delays, + int * x, int * y, int * z, int * comp, + int req_comp); #endif #ifdef STBI_WINDOWS_UTF8 -STBIDEF int stbi_convert_wchar_to_utf8(char * buffer, size_t bufferlen, - const wchar_t * input); +STBIDEF int stbi_convert_wchar_to_utf8(char * buffer, size_t bufferlen, const wchar_t * input); #endif //////////////////////////////////// @@ -455,20 +449,16 @@ STBIDEF int stbi_convert_wchar_to_utf8(char * buffer, size_t bufferlen, // 16-bits-per-channel interface // -STBIDEF stbi_us * stbi_load_16_from_memory(stbi_uc const * buffer, int len, - int * x, int * y, - int * channels_in_file, - int desired_channels); -STBIDEF stbi_us * stbi_load_16_from_callbacks(stbi_io_callbacks const * clbk, - void * user, int * x, int * y, - int * channels_in_file, +STBIDEF stbi_us * stbi_load_16_from_memory(stbi_uc const * buffer, int len, int * x, int * y, + int * channels_in_file, int desired_channels); +STBIDEF stbi_us * stbi_load_16_from_callbacks(stbi_io_callbacks const * clbk, void * user, + int * x, int * y, int * channels_in_file, int desired_channels); #ifndef STBI_NO_STDIO -STBIDEF stbi_us * stbi_load_16(char const * filename, int * x, int * y, - int * channels_in_file, int desired_channels); -STBIDEF stbi_us * stbi_load_from_file_16(FILE * f, int * x, int * y, - int * channels_in_file, +STBIDEF stbi_us * stbi_load_16(char const * filename, int * x, int * y, int * channels_in_file, + int desired_channels); +STBIDEF stbi_us * stbi_load_from_file_16(FILE * f, int * x, int * y, int * channels_in_file, int desired_channels); #endif @@ -477,19 +467,16 @@ STBIDEF stbi_us * stbi_load_from_file_16(FILE * f, int * x, int * y, // float-per-channel interface // #ifndef STBI_NO_LINEAR -STBIDEF float * stbi_loadf_from_memory(stbi_uc const * buffer, int len, int * x, - int * y, int * channels_in_file, - int desired_channels); -STBIDEF float * stbi_loadf_from_callbacks(stbi_io_callbacks const * clbk, - void * user, int * x, int * y, - int * channels_in_file, +STBIDEF float * stbi_loadf_from_memory(stbi_uc const * buffer, int len, int * x, int * y, + int * channels_in_file, int desired_channels); +STBIDEF float * stbi_loadf_from_callbacks(stbi_io_callbacks const * clbk, void * user, int * x, + int * y, int * channels_in_file, int desired_channels); #ifndef STBI_NO_STDIO -STBIDEF float * stbi_loadf(char const * filename, int * x, int * y, - int * channels_in_file, int desired_channels); -STBIDEF float * stbi_loadf_from_file(FILE * f, int * x, int * y, - int * channels_in_file, +STBIDEF float * stbi_loadf(char const * filename, int * x, int * y, int * channels_in_file, + int desired_channels); +STBIDEF float * stbi_loadf_from_file(FILE * f, int * x, int * y, int * channels_in_file, int desired_channels); #endif #endif @@ -505,8 +492,7 @@ STBIDEF void stbi_ldr_to_hdr_scale(float scale); #endif // STBI_NO_LINEAR // stbi_is_hdr is always defined, but always returns false if STBI_NO_HDR -STBIDEF int stbi_is_hdr_from_callbacks(stbi_io_callbacks const * clbk, - void * user); +STBIDEF int stbi_is_hdr_from_callbacks(stbi_io_callbacks const * clbk, void * user); STBIDEF int stbi_is_hdr_from_memory(stbi_uc const * buffer, int len); #ifndef STBI_NO_STDIO STBIDEF int stbi_is_hdr(char const * filename); @@ -521,13 +507,12 @@ STBIDEF const char * stbi_failure_reason(void); STBIDEF void stbi_image_free(void * retval_from_stbi_load); // get image dimensions & components without fully decoding -STBIDEF int stbi_info_from_memory(stbi_uc const * buffer, int len, int * x, - int * y, int * comp); -STBIDEF int stbi_info_from_callbacks(stbi_io_callbacks const * clbk, - void * user, int * x, int * y, int * comp); +STBIDEF int stbi_info_from_memory(stbi_uc const * buffer, int len, int * x, int * y, + int * comp); +STBIDEF int stbi_info_from_callbacks(stbi_io_callbacks const * clbk, void * user, int * x, + int * y, int * comp); STBIDEF int stbi_is_16_bit_from_memory(stbi_uc const * buffer, int len); -STBIDEF int stbi_is_16_bit_from_callbacks(stbi_io_callbacks const * clbk, - void * user); +STBIDEF int stbi_is_16_bit_from_callbacks(stbi_io_callbacks const * clbk, void * user); #ifndef STBI_NO_STDIO STBIDEF int stbi_info(char const * filename, int * x, int * y, int * comp); @@ -539,8 +524,7 @@ STBIDEF int stbi_is_16_bit_from_file(FILE * f); // for image formats that explicitly notate that they have premultiplied alpha, // we just return the colors as stored in the file. set this flag to force // unpremultiplication. results are undefined if the unpremultiply overflow. -STBIDEF void -stbi_set_unpremultiply_on_load(int flag_true_if_should_unpremultiply); +STBIDEF void stbi_set_unpremultiply_on_load(int flag_true_if_should_unpremultiply); // indicate whether we should process iphone images back to canonical format, // or just pass them through "as-is" @@ -552,32 +536,23 @@ STBIDEF void stbi_set_flip_vertically_on_load(int flag_true_if_should_flip); // as above, but only applies to images loaded on the thread that calls the function // this function is only available if your compiler supports thread-local variables; // calling it will fail to link if your compiler doesn't -STBIDEF void -stbi_set_unpremultiply_on_load_thread(int flag_true_if_should_unpremultiply); -STBIDEF void -stbi_convert_iphone_png_to_rgb_thread(int flag_true_if_should_convert); -STBIDEF void -stbi_set_flip_vertically_on_load_thread(int flag_true_if_should_flip); +STBIDEF void stbi_set_unpremultiply_on_load_thread(int flag_true_if_should_unpremultiply); +STBIDEF void stbi_convert_iphone_png_to_rgb_thread(int flag_true_if_should_convert); +STBIDEF void stbi_set_flip_vertically_on_load_thread(int flag_true_if_should_flip); // ZLIB client - used by PNG, available for other purposes STBIDEF char * stbi_zlib_decode_malloc_guesssize(const char * buffer, int len, - int initial_size, - int * outlen); -STBIDEF char * stbi_zlib_decode_malloc_guesssize_headerflag(const char * buffer, - int len, - int initial_size, - int * outlen, + int initial_size, int * outlen); +STBIDEF char * stbi_zlib_decode_malloc_guesssize_headerflag(const char * buffer, int len, + int initial_size, int * outlen, int parse_header); -STBIDEF char * stbi_zlib_decode_malloc(const char * buffer, int len, - int * outlen); -STBIDEF int stbi_zlib_decode_buffer(char * obuffer, int olen, - const char * ibuffer, int ilen); +STBIDEF char * stbi_zlib_decode_malloc(const char * buffer, int len, int * outlen); +STBIDEF int stbi_zlib_decode_buffer(char * obuffer, int olen, const char * ibuffer, int ilen); -STBIDEF char * stbi_zlib_decode_noheader_malloc(const char * buffer, int len, - int * outlen); -STBIDEF int stbi_zlib_decode_noheader_buffer(char * obuffer, int olen, - const char * ibuffer, int ilen); +STBIDEF char * stbi_zlib_decode_noheader_malloc(const char * buffer, int len, int * outlen); +STBIDEF int stbi_zlib_decode_noheader_buffer(char * obuffer, int olen, const char * ibuffer, + int ilen); #ifdef __cplusplus } @@ -590,11 +565,10 @@ STBIDEF int stbi_zlib_decode_noheader_buffer(char * obuffer, int olen, #ifdef STB_IMAGE_IMPLEMENTATION -#if defined(STBI_ONLY_JPEG) || defined(STBI_ONLY_PNG) \ - || defined(STBI_ONLY_BMP) || defined(STBI_ONLY_TGA) \ - || defined(STBI_ONLY_GIF) || defined(STBI_ONLY_PSD) \ - || defined(STBI_ONLY_HDR) || defined(STBI_ONLY_PIC) \ - || defined(STBI_ONLY_PNM) || defined(STBI_ONLY_ZLIB) +#if defined(STBI_ONLY_JPEG) || defined(STBI_ONLY_PNG) || defined(STBI_ONLY_BMP) \ + || defined(STBI_ONLY_TGA) || defined(STBI_ONLY_GIF) || defined(STBI_ONLY_PSD) \ + || defined(STBI_ONLY_HDR) || defined(STBI_ONLY_PIC) || defined(STBI_ONLY_PNM) \ + || defined(STBI_ONLY_ZLIB) #ifndef STBI_ONLY_JPEG #define STBI_NO_JPEG #endif @@ -624,8 +598,7 @@ STBIDEF int stbi_zlib_decode_noheader_buffer(char * obuffer, int olen, #endif #endif -#if defined(STBI_NO_PNG) && !defined(STBI_SUPPORT_ZLIB) \ - && !defined(STBI_NO_ZLIB) +#if defined(STBI_NO_PNG) && !defined(STBI_SUPPORT_ZLIB) && !defined(STBI_NO_ZLIB) #define STBI_NO_ZLIB #endif @@ -671,8 +644,7 @@ STBIDEF int stbi_zlib_decode_noheader_buffer(char * obuffer, int olen, #define STBI_THREAD_LOCAL __thread #elif defined(_MSC_VER) #define STBI_THREAD_LOCAL __declspec(thread) -#elif defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L \ - && !defined(__STDC_NO_THREADS__) +#elif defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L && !defined(__STDC_NO_THREADS__) #define STBI_THREAD_LOCAL _Thread_local #endif @@ -755,8 +727,8 @@ typedef unsigned char validate_uint32[sizeof(stbi__uint32) == 4 ? 1 : -1]; #define STBI_NO_SIMD #endif -#if defined(__MINGW32__) && defined(STBI__X86_TARGET) \ - && !defined(STBI_MINGW_ENABLE_SSE2) && !defined(STBI_NO_SIMD) +#if defined(__MINGW32__) && defined(STBI__X86_TARGET) && !defined(STBI_MINGW_ENABLE_SSE2) \ + && !defined(STBI_NO_SIMD) // Note that __MINGW32__ doesn't actually mean 32-bit, so we have to avoid STBI__X64_TARGET // // 32-bit MinGW wants ESP to be 16-byte aligned, but this is not in the @@ -771,8 +743,7 @@ typedef unsigned char validate_uint32[sizeof(stbi__uint32) == 4 ? 1 : -1]; #define STBI_NO_SIMD #endif -#if !defined(STBI_NO_SIMD) \ - && (defined(STBI__X86_TARGET) || defined(STBI__X64_TARGET)) +#if !defined(STBI_NO_SIMD) && (defined(STBI__X86_TARGET) || defined(STBI__X64_TARGET)) #define STBI_SSE2 #include <emmintrin.h> @@ -868,8 +839,7 @@ typedef struct { static void stbi__refill_buffer(stbi__context * s); // initialize a memory-decode context -static void stbi__start_mem(stbi__context * s, stbi_uc const * buffer, - int len) { +static void stbi__start_mem(stbi__context * s, stbi_uc const * buffer, int len) { s->io.read = NULL; s->read_from_callbacks = 0; s->callback_already_read = 0; @@ -878,8 +848,7 @@ static void stbi__start_mem(stbi__context * s, stbi_uc const * buffer, } // initialize a callback-based context -static void stbi__start_callbacks(stbi__context * s, stbi_io_callbacks * c, - void * user) { +static void stbi__start_callbacks(stbi__context * s, stbi_io_callbacks * c, void * user) { s->io = *c; s->io_user_data = user; s->buflen = sizeof(s->buffer_start); @@ -941,68 +910,68 @@ typedef struct { #ifndef STBI_NO_JPEG static int stbi__jpeg_test(stbi__context * s); -static void * stbi__jpeg_load(stbi__context * s, int * x, int * y, int * comp, - int req_comp, stbi__result_info * ri); +static void * stbi__jpeg_load(stbi__context * s, int * x, int * y, int * comp, int req_comp, + stbi__result_info * ri); static int stbi__jpeg_info(stbi__context * s, int * x, int * y, int * comp); #endif #ifndef STBI_NO_PNG static int stbi__png_test(stbi__context * s); -static void * stbi__png_load(stbi__context * s, int * x, int * y, int * comp, - int req_comp, stbi__result_info * ri); +static void * stbi__png_load(stbi__context * s, int * x, int * y, int * comp, int req_comp, + stbi__result_info * ri); static int stbi__png_info(stbi__context * s, int * x, int * y, int * comp); static int stbi__png_is16(stbi__context * s); #endif #ifndef STBI_NO_BMP static int stbi__bmp_test(stbi__context * s); -static void * stbi__bmp_load(stbi__context * s, int * x, int * y, int * comp, - int req_comp, stbi__result_info * ri); +static void * stbi__bmp_load(stbi__context * s, int * x, int * y, int * comp, int req_comp, + stbi__result_info * ri); static int stbi__bmp_info(stbi__context * s, int * x, int * y, int * comp); #endif #ifndef STBI_NO_TGA static int stbi__tga_test(stbi__context * s); -static void * stbi__tga_load(stbi__context * s, int * x, int * y, int * comp, - int req_comp, stbi__result_info * ri); +static void * stbi__tga_load(stbi__context * s, int * x, int * y, int * comp, int req_comp, + stbi__result_info * ri); static int stbi__tga_info(stbi__context * s, int * x, int * y, int * comp); #endif #ifndef STBI_NO_PSD static int stbi__psd_test(stbi__context * s); -static void * stbi__psd_load(stbi__context * s, int * x, int * y, int * comp, - int req_comp, stbi__result_info * ri, int bpc); +static void * stbi__psd_load(stbi__context * s, int * x, int * y, int * comp, int req_comp, + stbi__result_info * ri, int bpc); static int stbi__psd_info(stbi__context * s, int * x, int * y, int * comp); static int stbi__psd_is16(stbi__context * s); #endif #ifndef STBI_NO_HDR static int stbi__hdr_test(stbi__context * s); -static float * stbi__hdr_load(stbi__context * s, int * x, int * y, int * comp, - int req_comp, stbi__result_info * ri); +static float * stbi__hdr_load(stbi__context * s, int * x, int * y, int * comp, int req_comp, + stbi__result_info * ri); static int stbi__hdr_info(stbi__context * s, int * x, int * y, int * comp); #endif #ifndef STBI_NO_PIC static int stbi__pic_test(stbi__context * s); -static void * stbi__pic_load(stbi__context * s, int * x, int * y, int * comp, - int req_comp, stbi__result_info * ri); +static void * stbi__pic_load(stbi__context * s, int * x, int * y, int * comp, int req_comp, + stbi__result_info * ri); static int stbi__pic_info(stbi__context * s, int * x, int * y, int * comp); #endif #ifndef STBI_NO_GIF static int stbi__gif_test(stbi__context * s); -static void * stbi__gif_load(stbi__context * s, int * x, int * y, int * comp, - int req_comp, stbi__result_info * ri); -static void * stbi__load_gif_main(stbi__context * s, int ** delays, int * x, - int * y, int * z, int * comp, int req_comp); +static void * stbi__gif_load(stbi__context * s, int * x, int * y, int * comp, int req_comp, + stbi__result_info * ri); +static void * stbi__load_gif_main(stbi__context * s, int ** delays, int * x, int * y, int * z, + int * comp, int req_comp); static int stbi__gif_info(stbi__context * s, int * x, int * y, int * comp); #endif #ifndef STBI_NO_PNM static int stbi__pnm_test(stbi__context * s); -static void * stbi__pnm_load(stbi__context * s, int * x, int * y, int * comp, - int req_comp, stbi__result_info * ri); +static void * stbi__pnm_load(stbi__context * s, int * x, int * y, int * comp, int req_comp, + stbi__result_info * ri); static int stbi__pnm_info(stbi__context * s, int * x, int * y, int * comp); static int stbi__pnm_is16(stbi__context * s); #endif @@ -1013,9 +982,7 @@ static #endif const char * stbi__g_failure_reason; -STBIDEF const char * stbi_failure_reason(void) { - return stbi__g_failure_reason; -} +STBIDEF const char * stbi_failure_reason(void) { return stbi__g_failure_reason; } #ifndef STBI_NO_FAILURE_STRINGS static int stbi__err(const char * str) { @@ -1074,8 +1041,7 @@ static int stbi__mad3sizes_valid(int a, int b, int c, int add) { #if !defined(STBI_NO_LINEAR) || !defined(STBI_NO_HDR) || !defined(STBI_NO_PNM) static int stbi__mad4sizes_valid(int a, int b, int c, int d, int add) { return stbi__mul2sizes_valid(a, b) && stbi__mul2sizes_valid(a * b, c) - && stbi__mul2sizes_valid(a * b * c, d) - && stbi__addsizes_valid(a * b * c * d, add); + && stbi__mul2sizes_valid(a * b * c, d) && stbi__addsizes_valid(a * b * c * d, add); } #endif @@ -1102,8 +1068,7 @@ static void * stbi__malloc_mad4(int a, int b, int c, int d, int add) { // returns 1 if the sum of two signed ints is valid (between -2^31 and 2^31-1 inclusive), 0 on overflow. static int stbi__addints_valid(int a, int b) { - if ((a >= 0) != (b >= 0)) - return 1; // a and b have different signs, so no overflow + if ((a >= 0) != (b >= 0)) return 1; // a and b have different signs, so no overflow if (a < 0 && b < 0) return a >= INT_MIN @@ -1116,9 +1081,7 @@ static int stbi__mul2shorts_valid(int a, int b) { if (b == 0 || b == -1) return 1; // multiplication by 0 is always 0; check for -1 so SHRT_MIN/b doesn't overflow if ((a >= 0) == (b >= 0)) - return a - <= SHRT_MAX - / b; // product is positive, so similar to mul2sizes_valid + return a <= SHRT_MAX / b; // product is positive, so similar to mul2sizes_valid if (b < 0) return a <= SHRT_MIN / b; // same as a * b >= SHRT_MIN return a >= SHRT_MIN / b; } @@ -1136,8 +1099,7 @@ static int stbi__mul2shorts_valid(int a, int b) { #endif #define stbi__errpf(x, y) ((float *) (size_t) (stbi__err(x, y) ? NULL : NULL)) -#define stbi__errpuc(x, y) \ - ((unsigned char *) (size_t) (stbi__err(x, y) ? NULL : NULL)) +#define stbi__errpuc(x, y) ((unsigned char *) (size_t) (stbi__err(x, y) ? NULL : NULL)) STBIDEF void stbi_image_free(void * retval_from_stbi_load) { STBI_FREE(retval_from_stbi_load); @@ -1163,8 +1125,7 @@ STBIDEF void stbi_set_flip_vertically_on_load(int flag_true_if_should_flip) { static STBI_THREAD_LOCAL int stbi__vertically_flip_on_load_local, stbi__vertically_flip_on_load_set; -STBIDEF void -stbi_set_flip_vertically_on_load_thread(int flag_true_if_should_flip) { +STBIDEF void stbi_set_flip_vertically_on_load_thread(int flag_true_if_should_flip) { stbi__vertically_flip_on_load_local = flag_true_if_should_flip; stbi__vertically_flip_on_load_set = 1; } @@ -1174,12 +1135,11 @@ stbi_set_flip_vertically_on_load_thread(int flag_true_if_should_flip) { : stbi__vertically_flip_on_load_global) #endif // STBI_THREAD_LOCAL -static void * stbi__load_main(stbi__context * s, int * x, int * y, int * comp, - int req_comp, stbi__result_info * ri, int bpc) { +static void * stbi__load_main(stbi__context * s, int * x, int * y, int * comp, int req_comp, + stbi__result_info * ri, int bpc) { memset(ri, 0, sizeof(*ri)); // make sure it's initialized if we add new fields - ri->bits_per_channel - = 8; // default is 8 so most paths don't have to be changed + ri->bits_per_channel = 8; // default is 8 so most paths don't have to be changed ri->channel_order = STBI_ORDER_RGB; // all current input & output are this, but this is here so we can add BGR order ri->num_channels = 0; @@ -1196,8 +1156,7 @@ static void * stbi__load_main(stbi__context * s, int * x, int * y, int * comp, if (stbi__gif_test(s)) return stbi__gif_load(s, x, y, comp, req_comp, ri); #endif #ifndef STBI_NO_PSD - if (stbi__psd_test(s)) - return stbi__psd_load(s, x, y, comp, req_comp, ri, bpc); + if (stbi__psd_test(s)) return stbi__psd_load(s, x, y, comp, req_comp, ri, bpc); #else STBI_NOTUSED(bpc); #endif @@ -1227,12 +1186,10 @@ static void * stbi__load_main(stbi__context * s, int * x, int * y, int * comp, if (stbi__tga_test(s)) return stbi__tga_load(s, x, y, comp, req_comp, ri); #endif - return stbi__errpuc("unknown image type", - "Image not of any known type, or corrupt"); + return stbi__errpuc("unknown image type", "Image not of any known type, or corrupt"); } -static stbi_uc * stbi__convert_16_to_8(stbi__uint16 * orig, int w, int h, - int channels) { +static stbi_uc * stbi__convert_16_to_8(stbi__uint16 * orig, int w, int h, int channels) { int i; int img_len = w * h * channels; stbi_uc * reduced; @@ -1249,15 +1206,13 @@ static stbi_uc * stbi__convert_16_to_8(stbi__uint16 * orig, int w, int h, return reduced; } -static stbi__uint16 * stbi__convert_8_to_16(stbi_uc * orig, int w, int h, - int channels) { +static stbi__uint16 * stbi__convert_8_to_16(stbi_uc * orig, int w, int h, int channels) { int i; int img_len = w * h * channels; stbi__uint16 * enlarged; enlarged = (stbi__uint16 *) stbi__malloc(img_len * 2); - if (enlarged == NULL) - return (stbi__uint16 *) stbi__errpuc("outofmem", "Out of memory"); + if (enlarged == NULL) return (stbi__uint16 *) stbi__errpuc("outofmem", "Out of memory"); for (i = 0; i < img_len; ++i) enlarged[i] @@ -1269,8 +1224,7 @@ static stbi__uint16 * stbi__convert_8_to_16(stbi_uc * orig, int w, int h, return enlarged; } -static void stbi__vertical_flip(void * image, int w, int h, - int bytes_per_pixel) { +static void stbi__vertical_flip(void * image, int w, int h, int bytes_per_pixel) { int row; size_t bytes_per_row = (size_t) w * bytes_per_pixel; stbi_uc temp[2048]; @@ -1282,8 +1236,7 @@ static void stbi__vertical_flip(void * image, int w, int h, // swap row0 with row1 size_t bytes_left = bytes_per_row; while (bytes_left) { - size_t bytes_copy - = (bytes_left < sizeof(temp)) ? bytes_left : sizeof(temp); + size_t bytes_copy = (bytes_left < sizeof(temp)) ? bytes_left : sizeof(temp); memcpy(temp, row0, bytes_copy); memcpy(row0, row1, bytes_copy); memcpy(row1, temp, bytes_copy); @@ -1308,10 +1261,8 @@ static void stbi__vertical_flip_slices(void * image, int w, int h, int z, } #endif -static unsigned char * stbi__load_and_postprocess_8bit(stbi__context * s, - int * x, int * y, - int * comp, - int req_comp) { +static unsigned char * stbi__load_and_postprocess_8bit(stbi__context * s, int * x, int * y, + int * comp, int req_comp) { stbi__result_info ri; void * result = stbi__load_main(s, x, y, comp, req_comp, &ri, 8); @@ -1336,10 +1287,8 @@ static unsigned char * stbi__load_and_postprocess_8bit(stbi__context * s, return (unsigned char *) result; } -static stbi__uint16 * stbi__load_and_postprocess_16bit(stbi__context * s, - int * x, int * y, - int * comp, - int req_comp) { +static stbi__uint16 * stbi__load_and_postprocess_16bit(stbi__context * s, int * x, int * y, + int * comp, int req_comp) { stbi__result_info ri; void * result = stbi__load_main(s, x, y, comp, req_comp, &ri, 16); @@ -1366,8 +1315,8 @@ static stbi__uint16 * stbi__load_and_postprocess_16bit(stbi__context * s, } #if !defined(STBI_NO_HDR) && !defined(STBI_NO_LINEAR) -static void stbi__float_postprocess(float * result, int * x, int * y, - int * comp, int req_comp) { +static void stbi__float_postprocess(float * result, int * x, int * y, int * comp, + int req_comp) { if (stbi__vertically_flip_on_load && result != NULL) { int channels = req_comp ? req_comp : *comp; stbi__vertical_flip(result, *x, *y, channels * sizeof(float)); @@ -1378,19 +1327,20 @@ static void stbi__float_postprocess(float * result, int * x, int * y, #ifndef STBI_NO_STDIO #if defined(_WIN32) && defined(STBI_WINDOWS_UTF8) -STBI_EXTERN __declspec(dllimport) int __stdcall MultiByteToWideChar( - unsigned int cp, unsigned long flags, const char * str, int cbmb, - wchar_t * widestr, int cchwide); +STBI_EXTERN +__declspec(dllimport) int __stdcall MultiByteToWideChar(unsigned int cp, unsigned long flags, + const char * str, int cbmb, + wchar_t * widestr, int cchwide); STBI_EXTERN __declspec(dllimport) int __stdcall WideCharToMultiByte( - unsigned int cp, unsigned long flags, const wchar_t * widestr, int cchwide, - char * str, int cbmb, const char * defchar, int * used_default); + unsigned int cp, unsigned long flags, const wchar_t * widestr, int cchwide, char * str, + int cbmb, const char * defchar, int * used_default); #endif #if defined(_WIN32) && defined(STBI_WINDOWS_UTF8) STBIDEF int stbi_convert_wchar_to_utf8(char * buffer, size_t bufferlen, const wchar_t * input) { - return WideCharToMultiByte(65001 /* UTF8 */, 0, input, -1, buffer, - (int) bufferlen, NULL, NULL); + return WideCharToMultiByte(65001 /* UTF8 */, 0, input, -1, buffer, (int) bufferlen, NULL, + NULL); } #endif @@ -1433,8 +1383,7 @@ STBIDEF stbi_uc * stbi_load(char const * filename, int * x, int * y, int * comp, return result; } -STBIDEF stbi_uc * stbi_load_from_file(FILE * f, int * x, int * y, int * comp, - int req_comp) { +STBIDEF stbi_uc * stbi_load_from_file(FILE * f, int * x, int * y, int * comp, int req_comp) { unsigned char * result; stbi__context s; stbi__start_file(&s, f); @@ -1446,8 +1395,8 @@ STBIDEF stbi_uc * stbi_load_from_file(FILE * f, int * x, int * y, int * comp, return result; } -STBIDEF stbi__uint16 * stbi_load_from_file_16(FILE * f, int * x, int * y, - int * comp, int req_comp) { +STBIDEF stbi__uint16 * stbi_load_from_file_16(FILE * f, int * x, int * y, int * comp, + int req_comp) { stbi__uint16 * result; stbi__context s; stbi__start_file(&s, f); @@ -1459,12 +1408,11 @@ STBIDEF stbi__uint16 * stbi_load_from_file_16(FILE * f, int * x, int * y, return result; } -STBIDEF stbi_us * stbi_load_16(char const * filename, int * x, int * y, - int * comp, int req_comp) { +STBIDEF stbi_us * stbi_load_16(char const * filename, int * x, int * y, int * comp, + int req_comp) { FILE * f = stbi__fopen(filename, "rb"); stbi__uint16 * result; - if (!f) - return (stbi_us *) stbi__errpuc("can't fopen", "Unable to open file"); + if (!f) return (stbi_us *) stbi__errpuc("can't fopen", "Unable to open file"); result = stbi_load_from_file_16(f, x, y, comp, req_comp); fclose(f); return result; @@ -1472,52 +1420,44 @@ STBIDEF stbi_us * stbi_load_16(char const * filename, int * x, int * y, #endif //!STBI_NO_STDIO -STBIDEF stbi_us * stbi_load_16_from_memory(stbi_uc const * buffer, int len, - int * x, int * y, - int * channels_in_file, - int desired_channels) { +STBIDEF stbi_us * stbi_load_16_from_memory(stbi_uc const * buffer, int len, int * x, int * y, + int * channels_in_file, int desired_channels) { stbi__context s; stbi__start_mem(&s, buffer, len); - return stbi__load_and_postprocess_16bit(&s, x, y, channels_in_file, - desired_channels); + return stbi__load_and_postprocess_16bit(&s, x, y, channels_in_file, desired_channels); } -STBIDEF stbi_us * stbi_load_16_from_callbacks(stbi_io_callbacks const * clbk, - void * user, int * x, int * y, - int * channels_in_file, +STBIDEF stbi_us * stbi_load_16_from_callbacks(stbi_io_callbacks const * clbk, void * user, + int * x, int * y, int * channels_in_file, int desired_channels) { stbi__context s; stbi__start_callbacks(&s, (stbi_io_callbacks *) clbk, user); - return stbi__load_and_postprocess_16bit(&s, x, y, channels_in_file, - desired_channels); + return stbi__load_and_postprocess_16bit(&s, x, y, channels_in_file, desired_channels); } -STBIDEF stbi_uc * stbi_load_from_memory(stbi_uc const * buffer, int len, - int * x, int * y, int * comp, - int req_comp) { +STBIDEF stbi_uc * stbi_load_from_memory(stbi_uc const * buffer, int len, int * x, int * y, + int * comp, int req_comp) { stbi__context s; stbi__start_mem(&s, buffer, len); return stbi__load_and_postprocess_8bit(&s, x, y, comp, req_comp); } -STBIDEF stbi_uc * stbi_load_from_callbacks(stbi_io_callbacks const * clbk, - void * user, int * x, int * y, - int * comp, int req_comp) { +STBIDEF stbi_uc * stbi_load_from_callbacks(stbi_io_callbacks const * clbk, void * user, + int * x, int * y, int * comp, int req_comp) { stbi__context s; stbi__start_callbacks(&s, (stbi_io_callbacks *) clbk, user); return stbi__load_and_postprocess_8bit(&s, x, y, comp, req_comp); } #ifndef STBI_NO_GIF -STBIDEF stbi_uc * stbi_load_gif_from_memory(stbi_uc const * buffer, int len, - int ** delays, int * x, int * y, - int * z, int * comp, int req_comp) { +STBIDEF stbi_uc * stbi_load_gif_from_memory(stbi_uc const * buffer, int len, int ** delays, + int * x, int * y, int * z, int * comp, + int req_comp) { unsigned char * result; stbi__context s; stbi__start_mem(&s, buffer, len); - result = (unsigned char *) stbi__load_gif_main(&s, delays, x, y, z, comp, - req_comp); + result = (unsigned char *) stbi__load_gif_main(&s, delays, x, y, z, comp, req_comp); if (stbi__vertically_flip_on_load) { stbi__vertical_flip_slices(result, *x, *y, *z, *comp); } @@ -1539,30 +1479,26 @@ static float * stbi__loadf_main(stbi__context * s, int * x, int * y, int * comp, } #endif data = stbi__load_and_postprocess_8bit(s, x, y, comp, req_comp); - if (data) - return stbi__ldr_to_hdr(data, *x, *y, req_comp ? req_comp : *comp); - return stbi__errpf("unknown image type", - "Image not of any known type, or corrupt"); + if (data) return stbi__ldr_to_hdr(data, *x, *y, req_comp ? req_comp : *comp); + return stbi__errpf("unknown image type", "Image not of any known type, or corrupt"); } -STBIDEF float * stbi_loadf_from_memory(stbi_uc const * buffer, int len, int * x, - int * y, int * comp, int req_comp) { +STBIDEF float * stbi_loadf_from_memory(stbi_uc const * buffer, int len, int * x, int * y, + int * comp, int req_comp) { stbi__context s; stbi__start_mem(&s, buffer, len); return stbi__loadf_main(&s, x, y, comp, req_comp); } -STBIDEF float * stbi_loadf_from_callbacks(stbi_io_callbacks const * clbk, - void * user, int * x, int * y, - int * comp, int req_comp) { +STBIDEF float * stbi_loadf_from_callbacks(stbi_io_callbacks const * clbk, void * user, int * x, + int * y, int * comp, int req_comp) { stbi__context s; stbi__start_callbacks(&s, (stbi_io_callbacks *) clbk, user); return stbi__loadf_main(&s, x, y, comp, req_comp); } #ifndef STBI_NO_STDIO -STBIDEF float * stbi_loadf(char const * filename, int * x, int * y, int * comp, - int req_comp) { +STBIDEF float * stbi_loadf(char const * filename, int * x, int * y, int * comp, int req_comp) { float * result; FILE * f = stbi__fopen(filename, "rb"); if (!f) return stbi__errpf("can't fopen", "Unable to open file"); @@ -1571,8 +1507,7 @@ STBIDEF float * stbi_loadf(char const * filename, int * x, int * y, int * comp, return result; } -STBIDEF float * stbi_loadf_from_file(FILE * f, int * x, int * y, int * comp, - int req_comp) { +STBIDEF float * stbi_loadf_from_file(FILE * f, int * x, int * y, int * comp, int req_comp) { stbi__context s; stbi__start_file(&s, f); return stbi__loadf_main(&s, x, y, comp, req_comp); @@ -1624,8 +1559,7 @@ STBIDEF int stbi_is_hdr_from_file(FILE * f) { } #endif // !STBI_NO_STDIO -STBIDEF int stbi_is_hdr_from_callbacks(stbi_io_callbacks const * clbk, - void * user) { +STBIDEF int stbi_is_hdr_from_callbacks(stbi_io_callbacks const * clbk, void * user) { #ifndef STBI_NO_HDR stbi__context s; stbi__start_callbacks(&s, (stbi_io_callbacks *) clbk, user); @@ -1646,12 +1580,8 @@ STBIDEF void stbi_ldr_to_hdr_scale(float scale) { stbi__l2h_scale = scale; } static float stbi__h2l_gamma_i = 1.0f / 2.2f, stbi__h2l_scale_i = 1.0f; -STBIDEF void stbi_hdr_to_ldr_gamma(float gamma) { - stbi__h2l_gamma_i = 1 / gamma; -} -STBIDEF void stbi_hdr_to_ldr_scale(float scale) { - stbi__h2l_scale_i = 1 / scale; -} +STBIDEF void stbi_hdr_to_ldr_gamma(float gamma) { stbi__h2l_gamma_i = 1 / gamma; } +STBIDEF void stbi_hdr_to_ldr_scale(float scale) { stbi__h2l_scale_i = 1 / scale; } ////////////////////////////////////////////////////////////////////////////// // @@ -1736,8 +1666,7 @@ static int stbi__getn(stbi__context * s, stbi_uc * buffer, int n) { memcpy(buffer, s->img_buffer, blen); - count = (s->io.read)(s->io_user_data, (char *) buffer + blen, - n - blen); + count = (s->io.read)(s->io_user_data, (char *) buffer + blen, n - blen); res = (count == (n - blen)); s->img_buffer = s->img_buffer_end; return res; @@ -1788,8 +1717,7 @@ static stbi__uint32 stbi__get32le(stbi__context * s) { } #endif -#define STBI__BYTECAST(x) \ - ((stbi_uc) ((x) & 255)) // truncate int to byte without warnings +#define STBI__BYTECAST(x) ((stbi_uc) ((x) & 255)) // truncate int to byte without warnings #if defined(STBI_NO_JPEG) && defined(STBI_NO_PNG) && defined(STBI_NO_BMP) \ && defined(STBI_NO_PSD) && defined(STBI_NO_TGA) && defined(STBI_NO_GIF) \ @@ -1817,9 +1745,8 @@ static stbi_uc stbi__compute_y(int r, int g, int b) { && defined(STBI_NO_PNM) // nothing #else -static unsigned char * stbi__convert_format(unsigned char * data, int img_n, - int req_comp, unsigned int x, - unsigned int y) { +static unsigned char * stbi__convert_format(unsigned char * data, int img_n, int req_comp, + unsigned int x, unsigned int y) { int i, j; unsigned char * good; @@ -1871,18 +1798,14 @@ static unsigned char * stbi__convert_format(unsigned char * data, int img_n, dest[3] = 255; } break; - STBI__CASE(3, 1) { - dest[0] = stbi__compute_y(src[0], src[1], src[2]); - } + STBI__CASE(3, 1) { dest[0] = stbi__compute_y(src[0], src[1], src[2]); } break; STBI__CASE(3, 2) { dest[0] = stbi__compute_y(src[0], src[1], src[2]); dest[1] = 255; } break; - STBI__CASE(4, 1) { - dest[0] = stbi__compute_y(src[0], src[1], src[2]); - } + STBI__CASE(4, 1) { dest[0] = stbi__compute_y(src[0], src[1], src[2]); } break; STBI__CASE(4, 2) { dest[0] = stbi__compute_y(src[0], src[1], src[2]); @@ -1899,8 +1822,7 @@ static unsigned char * stbi__convert_format(unsigned char * data, int img_n, STBI_ASSERT(0); STBI_FREE(data); STBI_FREE(good); - return stbi__errpuc("unsupported", - "Unsupported format conversion"); + return stbi__errpuc("unsupported", "Unsupported format conversion"); } #undef STBI__CASE } @@ -1921,9 +1843,8 @@ static stbi__uint16 stbi__compute_y_16(int r, int g, int b) { #if defined(STBI_NO_PNG) && defined(STBI_NO_PSD) // nothing #else -static stbi__uint16 * stbi__convert_format16(stbi__uint16 * data, int img_n, - int req_comp, unsigned int x, - unsigned int y) { +static stbi__uint16 * stbi__convert_format16(stbi__uint16 * data, int img_n, int req_comp, + unsigned int x, unsigned int y) { int i, j; stbi__uint16 * good; @@ -1975,18 +1896,14 @@ static stbi__uint16 * stbi__convert_format16(stbi__uint16 * data, int img_n, dest[3] = 0xffff; } break; - STBI__CASE(3, 1) { - dest[0] = stbi__compute_y_16(src[0], src[1], src[2]); - } + STBI__CASE(3, 1) { dest[0] = stbi__compute_y_16(src[0], src[1], src[2]); } break; STBI__CASE(3, 2) { dest[0] = stbi__compute_y_16(src[0], src[1], src[2]); dest[1] = 0xffff; } break; - STBI__CASE(4, 1) { - dest[0] = stbi__compute_y_16(src[0], src[1], src[2]); - } + STBI__CASE(4, 1) { dest[0] = stbi__compute_y_16(src[0], src[1], src[2]); } break; STBI__CASE(4, 2) { dest[0] = stbi__compute_y_16(src[0], src[1], src[2]); @@ -2003,8 +1920,8 @@ static stbi__uint16 * stbi__convert_format16(stbi__uint16 * data, int img_n, STBI_ASSERT(0); STBI_FREE(data); STBI_FREE(good); - return (stbi__uint16 *) stbi__errpuc( - "unsupported", "Unsupported format conversion"); + return (stbi__uint16 *) stbi__errpuc("unsupported", + "Unsupported format conversion"); } #undef STBI__CASE } @@ -2029,9 +1946,8 @@ static float * stbi__ldr_to_hdr(stbi_uc * data, int x, int y, int comp) { else n = comp - 1; for (i = 0; i < x * y; ++i) { for (k = 0; k < n; ++k) { - output[i * comp + k] - = (float) (pow(data[i * comp + k] / 255.0f, stbi__l2h_gamma) - * stbi__l2h_scale); + output[i * comp + k] = (float) (pow(data[i * comp + k] / 255.0f, stbi__l2h_gamma) + * stbi__l2h_scale); } } if (n < comp) { @@ -2060,10 +1976,9 @@ static stbi_uc * stbi__hdr_to_ldr(float * data, int x, int y, int comp) { else n = comp - 1; for (i = 0; i < x * y; ++i) { for (k = 0; k < n; ++k) { - float z = (float) pow(data[i * comp + k] * stbi__h2l_scale_i, - stbi__h2l_gamma_i) - * 255 - + 0.5f; + float z + = (float) pow(data[i * comp + k] * stbi__h2l_scale_i, stbi__h2l_gamma_i) * 255 + + 0.5f; if (z < 0) z = 0; if (z > 255) z = 255; output[i * comp + k] = (stbi_uc) stbi__float2int(z); @@ -2164,11 +2079,10 @@ typedef struct { // kernels void (*idct_block_kernel)(stbi_uc * out, int out_stride, short data[64]); - void (*YCbCr_to_RGB_kernel)(stbi_uc * out, const stbi_uc * y, - const stbi_uc * pcb, const stbi_uc * pcr, - int count, int step); - stbi_uc * (*resample_row_hv_2_kernel)(stbi_uc * out, stbi_uc * in_near, - stbi_uc * in_far, int w, int hs); + void (*YCbCr_to_RGB_kernel)(stbi_uc * out, const stbi_uc * y, const stbi_uc * pcb, + const stbi_uc * pcr, int count, int step); + stbi_uc * (*resample_row_hv_2_kernel)(stbi_uc * out, stbi_uc * in_near, stbi_uc * in_far, + int w, int hs); } stbi__jpeg; static int stbi__build_huffman(stbi__huffman * h, int * count) { @@ -2191,8 +2105,7 @@ static int stbi__build_huffman(stbi__huffman * h, int * count) { h->delta[j] = k - code; if (h->size[k] == j) { while (h->size[k] == j) h->code[k++] = (stbi__uint16) (code++); - if (code - 1 >= (1u << j)) - return stbi__err("bad code lengths", "Corrupt JPEG"); + if (code - 1 >= (1u << j)) return stbi__err("bad code lengths", "Corrupt JPEG"); } // compute largest code + 1 for this size, preshifted as needed later h->maxcode[j] = code << (16 - j); @@ -2230,14 +2143,12 @@ static void stbi__build_fast_ac(stbi__int16 * fast_ac, stbi__huffman * h) { if (magbits && len + magbits <= FAST_BITS) { // magnitude code followed by receive_extend code - int k = ((i << len) & ((1 << FAST_BITS) - 1)) - >> (FAST_BITS - magbits); + int k = ((i << len) & ((1 << FAST_BITS) - 1)) >> (FAST_BITS - magbits); int m = 1 << (magbits - 1); if (k < m) k += (~0U << magbits) + 1; // if the result is small enough, we can fit it in fast_ac table if (k >= -128 && k <= 127) - fast_ac[i] = (stbi__int16) ((k * 256) + (run * 16) - + (len + magbits)); + fast_ac[i] = (stbi__int16) ((k * 256) + (run * 16) + (len + magbits)); } } } @@ -2262,12 +2173,10 @@ static void stbi__grow_buffer_unsafe(stbi__jpeg * j) { // (1 << n) - 1 static const stbi__uint32 stbi__bmask[17] - = {0, 1, 3, 7, 15, 31, 63, 127, 255, - 511, 1023, 2047, 4095, 8191, 16383, 32767, 65535}; + = {0, 1, 3, 7, 15, 31, 63, 127, 255, 511, 1023, 2047, 4095, 8191, 16383, 32767, 65535}; // decode a jpeg huffman value from the bitstream -stbi_inline static int stbi__jpeg_huff_decode(stbi__jpeg * j, - stbi__huffman * h) { +stbi_inline static int stbi__jpeg_huff_decode(stbi__jpeg * j, stbi__huffman * h) { unsigned int temp; int c, k; @@ -2306,9 +2215,8 @@ stbi_inline static int stbi__jpeg_huff_decode(stbi__jpeg * j, c = ((j->code_buffer >> (32 - k)) & stbi__bmask[k]) + h->delta[k]; if (c < 0 || c >= 256) // symbol id out of bounds! return -1; - STBI_ASSERT( - (((j->code_buffer) >> (32 - h->size[c])) & stbi__bmask[h->size[c]]) - == h->code[c]); + STBI_ASSERT((((j->code_buffer) >> (32 - h->size[c])) & stbi__bmask[h->size[c]]) + == h->code[c]); // convert the id to a symbol j->code_bits -= k; @@ -2317,9 +2225,8 @@ stbi_inline static int stbi__jpeg_huff_decode(stbi__jpeg * j, } // bias[n] = (-1<<n) + 1 -static const int stbi__jbias[16] - = {0, -1, -3, -7, -15, -31, -63, -127, - -255, -511, -1023, -2047, -4095, -8191, -16383, -32767}; +static const int stbi__jbias[16] = {0, -1, -3, -7, -15, -31, -63, -127, + -255, -511, -1023, -2047, -4095, -8191, -16383, -32767}; // combined JPEG 'receive' and JPEG 'extend', since baseline // always extends everything it receives. @@ -2366,17 +2273,15 @@ stbi_inline static int stbi__jpeg_get_bit(stbi__jpeg * j) { // given a value that's at position X in the zigzag stream, // where does it appear in the 8x8 matrix coded as row-major? static const stbi_uc stbi__jpeg_dezigzag[64 + 15] - = {0, 1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5, 12, 19, 26, 33, - 40, 48, 41, 34, 27, 20, 13, 6, 7, 14, 21, 28, 35, 42, 49, 56, 57, 50, 43, - 36, 29, 22, 15, 23, 30, 37, 44, 51, 58, 59, 52, 45, 38, 31, 39, 46, 53, - 60, 61, 54, 47, 55, 62, 63, + = {0, 1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5, 12, 19, 26, 33, 40, 48, 41, 34, + 27, 20, 13, 6, 7, 14, 21, 28, 35, 42, 49, 56, 57, 50, 43, 36, 29, 22, 15, 23, 30, 37, + 44, 51, 58, 59, 52, 45, 38, 31, 39, 46, 53, 60, 61, 54, 47, 55, 62, 63, // let corrupt input sample past end 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63}; // decode one 64-entry block-- -static int stbi__jpeg_decode_block(stbi__jpeg * j, short data[64], - stbi__huffman * hdc, stbi__huffman * hac, - stbi__int16 * fac, int b, +static int stbi__jpeg_decode_block(stbi__jpeg * j, short data[64], stbi__huffman * hdc, + stbi__huffman * hac, stbi__int16 * fac, int b, stbi__uint16 * dequant) { int diff, dc, k; int t; @@ -2409,9 +2314,8 @@ static int stbi__jpeg_decode_block(stbi__jpeg * j, short data[64], k += (r >> 4) & 15; // run s = r & 15; // combined length if (s > j->code_bits) - return stbi__err( - "bad huffman code", - "Combined length longer than code bits available"); + return stbi__err("bad huffman code", + "Combined length longer than code bits available"); j->code_buffer <<= s; j->code_bits -= s; // decode into unzigzag'd location @@ -2436,12 +2340,11 @@ static int stbi__jpeg_decode_block(stbi__jpeg * j, short data[64], return 1; } -static int stbi__jpeg_decode_block_prog_dc(stbi__jpeg * j, short data[64], - stbi__huffman * hdc, int b) { +static int stbi__jpeg_decode_block_prog_dc(stbi__jpeg * j, short data[64], stbi__huffman * hdc, + int b) { int diff, dc; int t; - if (j->spec_end != 0) - return stbi__err("can't merge dc and ac", "Corrupt JPEG"); + if (j->spec_end != 0) return stbi__err("can't merge dc and ac", "Corrupt JPEG"); if (j->code_bits < 16) stbi__grow_buffer_unsafe(j); @@ -2449,8 +2352,7 @@ static int stbi__jpeg_decode_block_prog_dc(stbi__jpeg * j, short data[64], // first scan for DC coefficient, must be first memset(data, 0, 64 * sizeof(data[0])); // 0 all the ac values now t = stbi__jpeg_huff_decode(j, hdc); - if (t < 0 || t > 15) - return stbi__err("can't merge dc and ac", "Corrupt JPEG"); + if (t < 0 || t > 15) return stbi__err("can't merge dc and ac", "Corrupt JPEG"); diff = t ? stbi__extend_receive(j, t) : 0; if (!stbi__addints_valid(j->img_comp[b].dc_pred, diff)) @@ -2469,12 +2371,10 @@ static int stbi__jpeg_decode_block_prog_dc(stbi__jpeg * j, short data[64], // @OPTIMIZE: store non-zigzagged during the decode passes, // and only de-zigzag when dequantizing -static int stbi__jpeg_decode_block_prog_ac(stbi__jpeg * j, short data[64], - stbi__huffman * hac, +static int stbi__jpeg_decode_block_prog_ac(stbi__jpeg * j, short data[64], stbi__huffman * hac, stbi__int16 * fac) { int k; - if (j->spec_start == 0) - return stbi__err("can't merge dc and ac", "Corrupt JPEG"); + if (j->spec_start == 0) return stbi__err("can't merge dc and ac", "Corrupt JPEG"); if (j->succ_high == 0) { int shift = j->succ_low; @@ -2495,17 +2395,15 @@ static int stbi__jpeg_decode_block_prog_ac(stbi__jpeg * j, short data[64], k += (r >> 4) & 15; // run s = r & 15; // combined length if (s > j->code_bits) - return stbi__err( - "bad huffman code", - "Combined length longer than code bits available"); + return stbi__err("bad huffman code", + "Combined length longer than code bits available"); j->code_buffer <<= s; j->code_bits -= s; zig = stbi__jpeg_dezigzag[k++]; data[zig] = (short) ((r >> 8) * (1 << shift)); } else { int rs = stbi__jpeg_huff_decode(j, hac); - if (rs < 0) - return stbi__err("bad huffman code", "Corrupt JPEG"); + if (rs < 0) return stbi__err("bad huffman code", "Corrupt JPEG"); s = rs & 15; r = rs >> 4; if (s == 0) { @@ -2519,8 +2417,7 @@ static int stbi__jpeg_decode_block_prog_ac(stbi__jpeg * j, short data[64], } else { k += r; zig = stbi__jpeg_dezigzag[k++]; - data[zig] - = (short) (stbi__extend_receive(j, s) * (1 << shift)); + data[zig] = (short) (stbi__extend_receive(j, s) * (1 << shift)); } } } while (k <= j->spec_end); @@ -2547,8 +2444,7 @@ static int stbi__jpeg_decode_block_prog_ac(stbi__jpeg * j, short data[64], int rs = stbi__jpeg_huff_decode( j, hac); // @OPTIMIZE see if we can use the fast path here, advance-by-r is so slow, eh - if (rs < 0) - return stbi__err("bad huffman code", "Corrupt JPEG"); + if (rs < 0) return stbi__err("bad huffman code", "Corrupt JPEG"); s = rs & 15; r = rs >> 4; if (s == 0) { @@ -2562,8 +2458,7 @@ static int stbi__jpeg_decode_block_prog_ac(stbi__jpeg * j, short data[64], // so we don't have to do anything special here } } else { - if (s != 1) - return stbi__err("bad huffman code", "Corrupt JPEG"); + if (s != 1) return stbi__err("bad huffman code", "Corrupt JPEG"); // sign bit if (stbi__jpeg_get_bit(j)) s = bit; else s = -bit; @@ -2651,15 +2546,14 @@ static void stbi__idct_block(stbi_uc * out, int out_stride, short data[64]) { // columns for (i = 0; i < 8; ++i, ++d, ++v) { // if all zeroes, shortcut -- this avoids dequantizing 0s and IDCTing - if (d[8] == 0 && d[16] == 0 && d[24] == 0 && d[32] == 0 && d[40] == 0 - && d[48] == 0 && d[56] == 0) { + if (d[8] == 0 && d[16] == 0 && d[24] == 0 && d[32] == 0 && d[40] == 0 && d[48] == 0 + && d[56] == 0) { // no shortcut 0 seconds // (1|2|3|4|5|6|7)==0 0 seconds // all separate -0.047 seconds // 1 && 2|3 && 4|5 && 6|7: -0.047 seconds int dcterm = d[0] * 4; - v[0] = v[8] = v[16] = v[24] = v[32] = v[40] = v[48] = v[56] - = dcterm; + v[0] = v[8] = v[16] = v[24] = v[32] = v[40] = v[48] = v[56] = dcterm; } else { STBI__IDCT_1D(d[0], d[8], d[16], d[24], d[32], d[40], d[48], d[56]) // constants scaled things up by 1<<12; let's bring them back @@ -2729,10 +2623,8 @@ static void stbi__idct_simd(stbi_uc * out, int out_stride, short data[64]) { // out = in << 12 (in 16-bit, out 32-bit) #define dct_widen(out, in) \ - __m128i out##_l \ - = _mm_srai_epi32(_mm_unpacklo_epi16(_mm_setzero_si128(), (in)), 4); \ - __m128i out##_h \ - = _mm_srai_epi32(_mm_unpackhi_epi16(_mm_setzero_si128(), (in)), 4) + __m128i out##_l = _mm_srai_epi32(_mm_unpacklo_epi16(_mm_setzero_si128(), (in)), 4); \ + __m128i out##_h = _mm_srai_epi32(_mm_unpackhi_epi16(_mm_setzero_si128(), (in)), 4) // wide add #define dct_wadd(out, a, b) \ @@ -2751,10 +2643,8 @@ static void stbi__idct_simd(stbi_uc * out, int out_stride, short data[64]) { __m128i abiased_h = _mm_add_epi32(a##_h, bias); \ dct_wadd(sum, abiased, b); \ dct_wsub(dif, abiased, b); \ - out0 = _mm_packs_epi32(_mm_srai_epi32(sum_l, s), \ - _mm_srai_epi32(sum_h, s)); \ - out1 = _mm_packs_epi32(_mm_srai_epi32(dif_l, s), \ - _mm_srai_epi32(dif_h, s)); \ + out0 = _mm_packs_epi32(_mm_srai_epi32(sum_l, s), _mm_srai_epi32(sum_h, s)); \ + out1 = _mm_packs_epi32(_mm_srai_epi32(dif_l, s), _mm_srai_epi32(dif_h, s)); \ } // 8-bit interleave step (for transposes) @@ -2798,28 +2688,21 @@ static void stbi__idct_simd(stbi_uc * out, int out_stride, short data[64]) { } __m128i rot0_0 - = dct_const(stbi__f2f(0.5411961f), - stbi__f2f(0.5411961f) + stbi__f2f(-1.847759065f)); - __m128i rot0_1 = dct_const(stbi__f2f(0.5411961f) + stbi__f2f(0.765366865f), - stbi__f2f(0.5411961f)); - __m128i rot1_0 - = dct_const(stbi__f2f(1.175875602f) + stbi__f2f(-0.899976223f), - stbi__f2f(1.175875602f)); - __m128i rot1_1 - = dct_const(stbi__f2f(1.175875602f), - stbi__f2f(1.175875602f) + stbi__f2f(-2.562915447f)); - __m128i rot2_0 - = dct_const(stbi__f2f(-1.961570560f) + stbi__f2f(0.298631336f), - stbi__f2f(-1.961570560f)); - __m128i rot2_1 - = dct_const(stbi__f2f(-1.961570560f), - stbi__f2f(-1.961570560f) + stbi__f2f(3.072711026f)); - __m128i rot3_0 - = dct_const(stbi__f2f(-0.390180644f) + stbi__f2f(2.053119869f), - stbi__f2f(-0.390180644f)); - __m128i rot3_1 - = dct_const(stbi__f2f(-0.390180644f), - stbi__f2f(-0.390180644f) + stbi__f2f(1.501321110f)); + = dct_const(stbi__f2f(0.5411961f), stbi__f2f(0.5411961f) + stbi__f2f(-1.847759065f)); + __m128i rot0_1 + = dct_const(stbi__f2f(0.5411961f) + stbi__f2f(0.765366865f), stbi__f2f(0.5411961f)); + __m128i rot1_0 = dct_const(stbi__f2f(1.175875602f) + stbi__f2f(-0.899976223f), + stbi__f2f(1.175875602f)); + __m128i rot1_1 = dct_const(stbi__f2f(1.175875602f), + stbi__f2f(1.175875602f) + stbi__f2f(-2.562915447f)); + __m128i rot2_0 = dct_const(stbi__f2f(-1.961570560f) + stbi__f2f(0.298631336f), + stbi__f2f(-1.961570560f)); + __m128i rot2_1 = dct_const(stbi__f2f(-1.961570560f), + stbi__f2f(-1.961570560f) + stbi__f2f(3.072711026f)); + __m128i rot3_0 = dct_const(stbi__f2f(-0.390180644f) + stbi__f2f(2.053119869f), + stbi__f2f(-0.390180644f)); + __m128i rot3_1 = dct_const(stbi__f2f(-0.390180644f), + stbi__f2f(-0.390180644f) + stbi__f2f(1.501321110f)); // rounding biases in column/row passes, see stbi__idct_block for explanation. __m128i bias_0 = _mm_set1_epi32(512); @@ -3030,8 +2913,7 @@ static void stbi__idct_simd(stbi_uc * out, int out_stride, short data[64]) { } #define dct_trn32(x, y) \ { \ - int32x4x2_t t \ - = vtrnq_s32(vreinterpretq_s32_s16(x), vreinterpretq_s32_s16(y)); \ + int32x4x2_t t = vtrnq_s32(vreinterpretq_s32_s16(x), vreinterpretq_s32_s16(y)); \ x = vreinterpretq_s16_s32(t.val[0]); \ y = vreinterpretq_s16_s32(t.val[1]); \ } @@ -3092,15 +2974,13 @@ static void stbi__idct_simd(stbi_uc * out, int out_stride, short data[64]) { } #define dct_trn8_16(x, y) \ { \ - uint16x4x2_t t \ - = vtrn_u16(vreinterpret_u16_u8(x), vreinterpret_u16_u8(y)); \ + uint16x4x2_t t = vtrn_u16(vreinterpret_u16_u8(x), vreinterpret_u16_u8(y)); \ x = vreinterpret_u8_u16(t.val[0]); \ y = vreinterpret_u8_u16(t.val[1]); \ } #define dct_trn8_32(x, y) \ { \ - uint32x2x2_t t \ - = vtrn_u32(vreinterpret_u32_u8(x), vreinterpret_u32_u8(y)); \ + uint32x2x2_t t = vtrn_u32(vreinterpret_u32_u8(x), vreinterpret_u32_u8(y)); \ x = vreinterpret_u8_u32(t.val[0]); \ y = vreinterpret_u8_u32(t.val[1]); \ } @@ -3211,14 +3091,13 @@ static int stbi__parse_entropy_coded_data(stbi__jpeg * z) { for (j = 0; j < h; ++j) { for (i = 0; i < w; ++i) { int ha = z->img_comp[n].ha; - if (!stbi__jpeg_decode_block( - z, data, z->huff_dc + z->img_comp[n].hd, - z->huff_ac + ha, z->fast_ac[ha], n, - z->dequant[z->img_comp[n].tq])) + if (!stbi__jpeg_decode_block(z, data, z->huff_dc + z->img_comp[n].hd, + z->huff_ac + ha, z->fast_ac[ha], n, + z->dequant[z->img_comp[n].tq])) return 0; - z->idct_block_kernel( - z->img_comp[n].data + z->img_comp[n].w2 * j * 8 + i * 8, - z->img_comp[n].w2, data); + z->idct_block_kernel(z->img_comp[n].data + z->img_comp[n].w2 * j * 8 + + i * 8, + z->img_comp[n].w2, data); // every data block is an MCU, so countdown the restart interval if (--z->todo <= 0) { if (z->code_bits < 24) stbi__grow_buffer_unsafe(z); @@ -3245,15 +3124,14 @@ static int stbi__parse_entropy_coded_data(stbi__jpeg * z) { int x2 = (i * z->img_comp[n].h + x) * 8; int y2 = (j * z->img_comp[n].v + y) * 8; int ha = z->img_comp[n].ha; - if (!stbi__jpeg_decode_block( - z, data, z->huff_dc + z->img_comp[n].hd, - z->huff_ac + ha, z->fast_ac[ha], n, - z->dequant[z->img_comp[n].tq])) + if (!stbi__jpeg_decode_block(z, data, + z->huff_dc + z->img_comp[n].hd, + z->huff_ac + ha, z->fast_ac[ha], + n, z->dequant[z->img_comp[n].tq])) return 0; - z->idct_block_kernel( - z->img_comp[n].data + z->img_comp[n].w2 * y2 - + x2, - z->img_comp[n].w2, data); + z->idct_block_kernel(z->img_comp[n].data + + z->img_comp[n].w2 * y2 + x2, + z->img_comp[n].w2, data); } } } @@ -3280,16 +3158,16 @@ static int stbi__parse_entropy_coded_data(stbi__jpeg * z) { int h = (z->img_comp[n].y + 7) >> 3; for (j = 0; j < h; ++j) { for (i = 0; i < w; ++i) { - short * data = z->img_comp[n].coeff - + 64 * (i + j * z->img_comp[n].coeff_w); + short * data + = z->img_comp[n].coeff + 64 * (i + j * z->img_comp[n].coeff_w); if (z->spec_start == 0) { if (!stbi__jpeg_decode_block_prog_dc( z, data, &z->huff_dc[z->img_comp[n].hd], n)) return 0; } else { int ha = z->img_comp[n].ha; - if (!stbi__jpeg_decode_block_prog_ac( - z, data, &z->huff_ac[ha], z->fast_ac[ha])) + if (!stbi__jpeg_decode_block_prog_ac(z, data, &z->huff_ac[ha], + z->fast_ac[ha])) return 0; } // every data block is an MCU, so countdown the restart interval @@ -3314,12 +3192,10 @@ static int stbi__parse_entropy_coded_data(stbi__jpeg * z) { for (x = 0; x < z->img_comp[n].h; ++x) { int x2 = (i * z->img_comp[n].h + x); int y2 = (j * z->img_comp[n].v + y); - short * data - = z->img_comp[n].coeff - + 64 * (x2 + y2 * z->img_comp[n].coeff_w); + short * data = z->img_comp[n].coeff + + 64 * (x2 + y2 * z->img_comp[n].coeff_w); if (!stbi__jpeg_decode_block_prog_dc( - z, data, &z->huff_dc[z->img_comp[n].hd], - n)) + z, data, &z->huff_dc[z->img_comp[n].hd], n)) return 0; } } @@ -3352,12 +3228,12 @@ static void stbi__jpeg_finish(stbi__jpeg * z) { int h = (z->img_comp[n].y + 7) >> 3; for (j = 0; j < h; ++j) { for (i = 0; i < w; ++i) { - short * data = z->img_comp[n].coeff - + 64 * (i + j * z->img_comp[n].coeff_w); + short * data + = z->img_comp[n].coeff + 64 * (i + j * z->img_comp[n].coeff_w); stbi__jpeg_dequantize(data, z->dequant[z->img_comp[n].tq]); - z->idct_block_kernel( - z->img_comp[n].data + z->img_comp[n].w2 * j * 8 + i * 8, - z->img_comp[n].w2, data); + z->idct_block_kernel(z->img_comp[n].data + z->img_comp[n].w2 * j * 8 + + i * 8, + z->img_comp[n].w2, data); } } } @@ -3371,8 +3247,7 @@ static int stbi__process_marker(stbi__jpeg * z, int m) { return stbi__err("expected marker", "Corrupt JPEG"); case 0xDD: // DRI - specify restart interval - if (stbi__get16be(z->s) != 4) - return stbi__err("bad DRI len", "Corrupt JPEG"); + if (stbi__get16be(z->s) != 4) return stbi__err("bad DRI len", "Corrupt JPEG"); z->restart_interval = stbi__get16be(z->s); return 1; @@ -3382,14 +3257,12 @@ static int stbi__process_marker(stbi__jpeg * z, int m) { int q = stbi__get8(z->s); int p = q >> 4, sixteen = (p != 0); int t = q & 15, i; - if (p != 0 && p != 1) - return stbi__err("bad DQT type", "Corrupt JPEG"); + if (p != 0 && p != 1) return stbi__err("bad DQT type", "Corrupt JPEG"); if (t > 3) return stbi__err("bad DQT table", "Corrupt JPEG"); for (i = 0; i < 64; ++i) z->dequant[t][stbi__jpeg_dezigzag[i]] - = (stbi__uint16) (sixteen ? stbi__get16be(z->s) - : stbi__get8(z->s)); + = (stbi__uint16) (sixteen ? stbi__get16be(z->s) : stbi__get8(z->s)); L -= (sixteen ? 129 : 65); } return L == 0; @@ -3402,8 +3275,7 @@ static int stbi__process_marker(stbi__jpeg * z, int m) { int q = stbi__get8(z->s); int tc = q >> 4; int th = q & 15; - if (tc > 1 || th > 3) - return stbi__err("bad DHT header", "Corrupt JPEG"); + if (tc > 1 || th > 3) return stbi__err("bad DHT header", "Corrupt JPEG"); for (i = 0; i < 16; ++i) { sizes[i] = stbi__get8(z->s); n += sizes[i]; @@ -3421,8 +3293,7 @@ static int stbi__process_marker(stbi__jpeg * z, int m) { v = z->huff_ac[th].values; } for (i = 0; i < n; ++i) v[i] = stbi__get8(z->s); - if (tc != 0) - stbi__build_fast_ac(z->fast_ac[th], z->huff_ac + th); + if (tc != 0) stbi__build_fast_ac(z->fast_ac[th], z->huff_ac + th); L -= n; } return L == 0; @@ -3475,8 +3346,7 @@ static int stbi__process_scan_header(stbi__jpeg * z) { z->scan_n = stbi__get8(z->s); if (z->scan_n < 1 || z->scan_n > 4 || z->scan_n > (int) z->s->img_n) return stbi__err("bad SOS component count", "Corrupt JPEG"); - if (Ls != 6 + 2 * z->scan_n) - return stbi__err("bad SOS len", "Corrupt JPEG"); + if (Ls != 6 + 2 * z->scan_n) return stbi__err("bad SOS len", "Corrupt JPEG"); for (i = 0; i < z->scan_n; ++i) { int id = stbi__get8(z->s), which; int q = stbi__get8(z->s); @@ -3484,11 +3354,9 @@ static int stbi__process_scan_header(stbi__jpeg * z) { if (z->img_comp[which].id == id) break; if (which == z->s->img_n) return 0; // no match z->img_comp[which].hd = q >> 4; - if (z->img_comp[which].hd > 3) - return stbi__err("bad DC huff", "Corrupt JPEG"); + if (z->img_comp[which].hd > 3) return stbi__err("bad DC huff", "Corrupt JPEG"); z->img_comp[which].ha = q & 15; - if (z->img_comp[which].ha > 3) - return stbi__err("bad AC huff", "Corrupt JPEG"); + if (z->img_comp[which].ha > 3) return stbi__err("bad AC huff", "Corrupt JPEG"); z->order[i] = which; } @@ -3500,9 +3368,8 @@ static int stbi__process_scan_header(stbi__jpeg * z) { z->succ_high = (aa >> 4); z->succ_low = (aa & 15); if (z->progressive) { - if (z->spec_start > 63 || z->spec_end > 63 - || z->spec_start > z->spec_end || z->succ_high > 13 - || z->succ_low > 13) + if (z->spec_start > 63 || z->spec_end > 63 || z->spec_start > z->spec_end + || z->succ_high > 13 || z->succ_low > 13) return stbi__err("bad SOS", "Corrupt JPEG"); } else { if (z->spec_start != 0) return stbi__err("bad SOS", "Corrupt JPEG"); @@ -3543,24 +3410,21 @@ static int stbi__process_frame_header(stbi__jpeg * z, int scan) { if (Lf < 11) return stbi__err("bad SOF len", "Corrupt JPEG"); // JPEG p = stbi__get8(s); if (p != 8) - return stbi__err( - "only 8-bit", - "JPEG format not supported: 8-bit only"); // JPEG baseline + return stbi__err("only 8-bit", + "JPEG format not supported: 8-bit only"); // JPEG baseline s->img_y = stbi__get16be(s); if (s->img_y == 0) return stbi__err( "no header height", "JPEG format not supported: delayed height"); // Legal, but we don't handle it--but neither does IJG s->img_x = stbi__get16be(s); - if (s->img_x == 0) - return stbi__err("0 width", "Corrupt JPEG"); // JPEG requires + if (s->img_x == 0) return stbi__err("0 width", "Corrupt JPEG"); // JPEG requires if (s->img_y > STBI_MAX_DIMENSIONS) return stbi__err("too large", "Very large image (corrupt?)"); if (s->img_x > STBI_MAX_DIMENSIONS) return stbi__err("too large", "Very large image (corrupt?)"); c = stbi__get8(s); - if (c != 3 && c != 1 && c != 4) - return stbi__err("bad component count", "Corrupt JPEG"); + if (c != 3 && c != 1 && c != 4) return stbi__err("bad component count", "Corrupt JPEG"); s->img_n = c; for (i = 0; i < c; ++i) { z->img_comp[i].data = NULL; @@ -3598,10 +3462,8 @@ static int stbi__process_frame_header(stbi__jpeg * z, int scan) { // check that plane subsampling factors are integer ratios; our resamplers can't deal with fractional ratios // and I've never seen a non-corrupted JPEG file actually use them for (i = 0; i < s->img_n; ++i) { - if (h_max % z->img_comp[i].h != 0) - return stbi__err("bad H", "Corrupt JPEG"); - if (v_max % z->img_comp[i].v != 0) - return stbi__err("bad V", "Corrupt JPEG"); + if (h_max % z->img_comp[i].h != 0) return stbi__err("bad H", "Corrupt JPEG"); + if (v_max % z->img_comp[i].v != 0) return stbi__err("bad V", "Corrupt JPEG"); } // compute interleaved mcu info @@ -3629,25 +3491,22 @@ static int stbi__process_frame_header(stbi__jpeg * z, int scan) { z->img_comp[i].coeff = 0; z->img_comp[i].raw_coeff = 0; z->img_comp[i].linebuf = NULL; - z->img_comp[i].raw_data - = stbi__malloc_mad2(z->img_comp[i].w2, z->img_comp[i].h2, 15); + z->img_comp[i].raw_data = stbi__malloc_mad2(z->img_comp[i].w2, z->img_comp[i].h2, 15); if (z->img_comp[i].raw_data == NULL) - return stbi__free_jpeg_components( - z, i + 1, stbi__err("outofmem", "Out of memory")); + return stbi__free_jpeg_components(z, i + 1, + stbi__err("outofmem", "Out of memory")); // align blocks for idct using mmx/sse - z->img_comp[i].data - = (stbi_uc *) (((size_t) z->img_comp[i].raw_data + 15) & ~15); + z->img_comp[i].data = (stbi_uc *) (((size_t) z->img_comp[i].raw_data + 15) & ~15); if (z->progressive) { // w2, h2 are multiples of 8 (see above) z->img_comp[i].coeff_w = z->img_comp[i].w2 / 8; z->img_comp[i].coeff_h = z->img_comp[i].h2 / 8; - z->img_comp[i].raw_coeff = stbi__malloc_mad3( - z->img_comp[i].w2, z->img_comp[i].h2, sizeof(short), 15); + z->img_comp[i].raw_coeff + = stbi__malloc_mad3(z->img_comp[i].w2, z->img_comp[i].h2, sizeof(short), 15); if (z->img_comp[i].raw_coeff == NULL) - return stbi__free_jpeg_components( - z, i + 1, stbi__err("outofmem", "Out of memory")); - z->img_comp[i].coeff - = (short *) (((size_t) z->img_comp[i].raw_coeff + 15) & ~15); + return stbi__free_jpeg_components(z, i + 1, + stbi__err("outofmem", "Out of memory")); + z->img_comp[i].coeff = (short *) (((size_t) z->img_comp[i].raw_coeff + 15) & ~15); } } @@ -3731,8 +3590,7 @@ static int stbi__decode_jpeg_image(stbi__jpeg * j) { int Ld = stbi__get16be(j->s); stbi__uint32 NL = stbi__get16be(j->s); if (Ld != 4) return stbi__err("bad DNL len", "Corrupt JPEG"); - if (NL != j->s->img_y) - return stbi__err("bad DNL height", "Corrupt JPEG"); + if (NL != j->s->img_y) return stbi__err("bad DNL height", "Corrupt JPEG"); m = stbi__get_marker(j); } else { if (!stbi__process_marker(j, m)) return 1; @@ -3745,13 +3603,13 @@ static int stbi__decode_jpeg_image(stbi__jpeg * j) { // static jfif-centered resampling (across block boundaries) -typedef stbi_uc * (*resample_row_func)(stbi_uc * out, stbi_uc * in0, - stbi_uc * in1, int w, int hs); +typedef stbi_uc * (*resample_row_func)(stbi_uc * out, stbi_uc * in0, stbi_uc * in1, int w, + int hs); #define stbi__div4(x) ((stbi_uc) ((x) >> 2)) -static stbi_uc * resample_row_1(stbi_uc * out, stbi_uc * in_near, - stbi_uc * in_far, int w, int hs) { +static stbi_uc * resample_row_1(stbi_uc * out, stbi_uc * in_near, stbi_uc * in_far, int w, + int hs) { STBI_NOTUSED(out); STBI_NOTUSED(in_far); STBI_NOTUSED(w); @@ -3759,8 +3617,8 @@ static stbi_uc * resample_row_1(stbi_uc * out, stbi_uc * in_near, return in_near; } -static stbi_uc * stbi__resample_row_v_2(stbi_uc * out, stbi_uc * in_near, - stbi_uc * in_far, int w, int hs) { +static stbi_uc * stbi__resample_row_v_2(stbi_uc * out, stbi_uc * in_near, stbi_uc * in_far, + int w, int hs) { // need to generate two samples vertically for every one in input int i; STBI_NOTUSED(hs); @@ -3768,8 +3626,8 @@ static stbi_uc * stbi__resample_row_v_2(stbi_uc * out, stbi_uc * in_near, return out; } -static stbi_uc * stbi__resample_row_h_2(stbi_uc * out, stbi_uc * in_near, - stbi_uc * in_far, int w, int hs) { +static stbi_uc * stbi__resample_row_h_2(stbi_uc * out, stbi_uc * in_near, stbi_uc * in_far, + int w, int hs) { // need to generate two samples horizontally for every one in input int i; stbi_uc * input = in_near; @@ -3798,8 +3656,8 @@ static stbi_uc * stbi__resample_row_h_2(stbi_uc * out, stbi_uc * in_near, #define stbi__div16(x) ((stbi_uc) ((x) >> 4)) -static stbi_uc * stbi__resample_row_hv_2(stbi_uc * out, stbi_uc * in_near, - stbi_uc * in_far, int w, int hs) { +static stbi_uc * stbi__resample_row_hv_2(stbi_uc * out, stbi_uc * in_near, stbi_uc * in_far, + int w, int hs) { // need to generate 2x2 samples for every one in input int i, t0, t1; if (w == 1) { @@ -3858,8 +3716,7 @@ static stbi_uc * stbi__resample_row_hv_2_simd(stbi_uc * out, stbi_uc * in_near, __m128i prv0 = _mm_slli_si128(curr, 2); __m128i nxt0 = _mm_srli_si128(curr, 2); __m128i prev = _mm_insert_epi16(prv0, t1, 0); - __m128i next - = _mm_insert_epi16(nxt0, 3 * in_near[i + 8] + in_far[i + 8], 7); + __m128i next = _mm_insert_epi16(nxt0, 3 * in_near[i + 8] + in_far[i + 8], 7); // horizontal filter, polyphase implementation since it's convenient: // even pixels = 3*cur + prev = cur*4 + (prev - cur) @@ -3899,8 +3756,7 @@ static stbi_uc * stbi__resample_row_hv_2_simd(stbi_uc * out, stbi_uc * in_near, int16x8_t prv0 = vextq_s16(curr, curr, 7); int16x8_t nxt0 = vextq_s16(curr, curr, 1); int16x8_t prev = vsetq_lane_s16(t1, prv0, 0); - int16x8_t next - = vsetq_lane_s16(3 * in_near[i + 8] + in_far[i + 8], nxt0, 7); + int16x8_t next = vsetq_lane_s16(3 * in_near[i + 8] + in_far[i + 8], nxt0, 7); // horizontal filter, polyphase implementation since it's convenient: // even pixels = 3*cur + prev = cur*4 + (prev - cur) @@ -3941,8 +3797,8 @@ static stbi_uc * stbi__resample_row_hv_2_simd(stbi_uc * out, stbi_uc * in_near, } #endif -static stbi_uc * stbi__resample_row_generic(stbi_uc * out, stbi_uc * in_near, - stbi_uc * in_far, int w, int hs) { +static stbi_uc * stbi__resample_row_generic(stbi_uc * out, stbi_uc * in_near, stbi_uc * in_far, + int w, int hs) { // resample with nearest-neighbor int i, j; STBI_NOTUSED(in_far); @@ -3954,9 +3810,8 @@ static stbi_uc * stbi__resample_row_generic(stbi_uc * out, stbi_uc * in_near, // this is a reduced-precision calculation of YCbCr-to-RGB introduced // to make sure the code produces the same results in both SIMD and scalar #define stbi__float2fixed(x) (((int) ((x) * 4096.0f + 0.5f)) << 8) -static void stbi__YCbCr_to_RGB_row(stbi_uc * out, const stbi_uc * y, - const stbi_uc * pcb, const stbi_uc * pcr, - int count, int step) { +static void stbi__YCbCr_to_RGB_row(stbi_uc * out, const stbi_uc * y, const stbi_uc * pcb, + const stbi_uc * pcr, int count, int step) { int i; for (i = 0; i < count; ++i) { int y_fixed = (y[i] << 20) + (1 << 19); // rounding @@ -3991,9 +3846,8 @@ static void stbi__YCbCr_to_RGB_row(stbi_uc * out, const stbi_uc * y, } #if defined(STBI_SSE2) || defined(STBI_NEON) -static void stbi__YCbCr_to_RGB_simd(stbi_uc * out, stbi_uc const * y, - stbi_uc const * pcb, stbi_uc const * pcr, - int count, int step) { +static void stbi__YCbCr_to_RGB_simd(stbi_uc * out, stbi_uc const * y, stbi_uc const * pcb, + stbi_uc const * pcr, int count, int step) { int i = 0; #ifdef STBI_SSE2 @@ -4004,10 +3858,8 @@ static void stbi__YCbCr_to_RGB_simd(stbi_uc * out, stbi_uc const * y, // this is a fairly straightforward implementation and not super-optimized. __m128i signflip = _mm_set1_epi8(-0x80); __m128i cr_const0 = _mm_set1_epi16((short) (1.40200f * 4096.0f + 0.5f)); - __m128i cr_const1 - = _mm_set1_epi16(-(short) (0.71414f * 4096.0f + 0.5f)); - __m128i cb_const0 - = _mm_set1_epi16(-(short) (0.34414f * 4096.0f + 0.5f)); + __m128i cr_const1 = _mm_set1_epi16(-(short) (0.71414f * 4096.0f + 0.5f)); + __m128i cb_const0 = _mm_set1_epi16(-(short) (0.34414f * 4096.0f + 0.5f)); __m128i cb_const1 = _mm_set1_epi16((short) (1.77200f * 4096.0f + 0.5f)); __m128i y_bias = _mm_set1_epi8((char) (unsigned char) 128); __m128i xw = _mm_set1_epi16(255); // alpha channel @@ -4074,10 +3926,8 @@ static void stbi__YCbCr_to_RGB_simd(stbi_uc * out, stbi_uc const * y, uint8x8_t y_bytes = vld1_u8(y + i); uint8x8_t cr_bytes = vld1_u8(pcr + i); uint8x8_t cb_bytes = vld1_u8(pcb + i); - int8x8_t cr_biased - = vreinterpret_s8_u8(vsub_u8(cr_bytes, signflip)); - int8x8_t cb_biased - = vreinterpret_s8_u8(vsub_u8(cb_bytes, signflip)); + int8x8_t cr_biased = vreinterpret_s8_u8(vsub_u8(cr_bytes, signflip)); + int8x8_t cb_biased = vreinterpret_s8_u8(vsub_u8(cb_bytes, signflip)); // expand to s16 int16x8_t yws = vreinterpretq_s16_u16(vshll_n_u8(y_bytes, 4)); @@ -4181,14 +4031,13 @@ static stbi_uc stbi__blinn_8x8(stbi_uc x, stbi_uc y) { return (stbi_uc) ((t + (t >> 8)) >> 8); } -static stbi_uc * load_jpeg_image(stbi__jpeg * z, int * out_x, int * out_y, - int * comp, int req_comp) { +static stbi_uc * load_jpeg_image(stbi__jpeg * z, int * out_x, int * out_y, int * comp, + int req_comp) { int n, decode_n, is_rgb; z->s->img_n = 0; // make stbi__cleanup_jpeg safe // validate req_comp - if (req_comp < 0 || req_comp > 4) - return stbi__errpuc("bad req_comp", "Internal error"); + if (req_comp < 0 || req_comp > 4) return stbi__errpuc("bad req_comp", "Internal error"); // load a jpeg image from whichever source, but leave in YCbCr format if (!stbi__decode_jpeg_image(z)) { @@ -4199,8 +4048,7 @@ static stbi_uc * load_jpeg_image(stbi__jpeg * z, int * out_x, int * out_y, // determine actual number of components to generate n = req_comp ? req_comp : z->s->img_n >= 3 ? 3 : 1; - is_rgb = z->s->img_n == 3 - && (z->rgb == 3 || (z->app14_color_transform == 0 && !z->jfif)); + is_rgb = z->s->img_n == 3 && (z->rgb == 3 || (z->app14_color_transform == 0 && !z->jfif)); if (z->s->img_n == 3 && n < 3 && !is_rgb) decode_n = 1; else decode_n = z->s->img_n; @@ -4240,12 +4088,9 @@ static stbi_uc * load_jpeg_image(stbi__jpeg * z, int * out_x, int * out_y, r->line0 = r->line1 = z->img_comp[k].data; if (r->hs == 1 && r->vs == 1) r->resample = resample_row_1; - else if (r->hs == 1 && r->vs == 2) - r->resample = stbi__resample_row_v_2; - else if (r->hs == 2 && r->vs == 1) - r->resample = stbi__resample_row_h_2; - else if (r->hs == 2 && r->vs == 2) - r->resample = z->resample_row_hv_2_kernel; + else if (r->hs == 1 && r->vs == 2) r->resample = stbi__resample_row_v_2; + else if (r->hs == 2 && r->vs == 1) r->resample = stbi__resample_row_h_2; + else if (r->hs == 2 && r->vs == 2) r->resample = z->resample_row_hv_2_kernel; else r->resample = stbi__resample_row_generic; } @@ -4262,14 +4107,12 @@ static stbi_uc * load_jpeg_image(stbi__jpeg * z, int * out_x, int * out_y, for (k = 0; k < decode_n; ++k) { stbi__resample * r = &res_comp[k]; int y_bot = r->ystep >= (r->vs >> 1); - coutput[k] = r->resample( - z->img_comp[k].linebuf, y_bot ? r->line1 : r->line0, - y_bot ? r->line0 : r->line1, r->w_lores, r->hs); + coutput[k] = r->resample(z->img_comp[k].linebuf, y_bot ? r->line1 : r->line0, + y_bot ? r->line0 : r->line1, r->w_lores, r->hs); if (++r->ystep >= r->vs) { r->ystep = 0; r->line0 = r->line1; - if (++r->ypos < z->img_comp[k].y) - r->line1 += z->img_comp[k].w2; + if (++r->ypos < z->img_comp[k].y) r->line1 += z->img_comp[k].w2; } } if (n >= 3) { @@ -4284,8 +4127,7 @@ static stbi_uc * load_jpeg_image(stbi__jpeg * z, int * out_x, int * out_y, out += n; } } else { - z->YCbCr_to_RGB_kernel(out, y, coutput[1], coutput[2], - z->s->img_x, n); + z->YCbCr_to_RGB_kernel(out, y, coutput[1], coutput[2], z->s->img_x, n); } } else if (z->s->img_n == 4) { if (z->app14_color_transform == 0) { // CMYK @@ -4298,8 +4140,7 @@ static stbi_uc * load_jpeg_image(stbi__jpeg * z, int * out_x, int * out_y, out += n; } } else if (z->app14_color_transform == 2) { // YCCK - z->YCbCr_to_RGB_kernel(out, y, coutput[1], coutput[2], - z->s->img_x, n); + z->YCbCr_to_RGB_kernel(out, y, coutput[1], coutput[2], z->s->img_x, n); for (i = 0; i < z->s->img_x; ++i) { stbi_uc m = coutput[3][i]; out[0] = stbi__blinn_8x8(255 - out[0], m); @@ -4308,8 +4149,7 @@ static stbi_uc * load_jpeg_image(stbi__jpeg * z, int * out_x, int * out_y, out += n; } } else { // YCbCr + alpha? Ignore the fourth channel for now - z->YCbCr_to_RGB_kernel(out, y, coutput[1], coutput[2], - z->s->img_x, n); + z->YCbCr_to_RGB_kernel(out, y, coutput[1], coutput[2], z->s->img_x, n); } } else for (i = 0; i < z->s->img_x; ++i) { @@ -4321,12 +4161,12 @@ static stbi_uc * load_jpeg_image(stbi__jpeg * z, int * out_x, int * out_y, if (is_rgb) { if (n == 1) for (i = 0; i < z->s->img_x; ++i) - *out++ = stbi__compute_y( - coutput[0][i], coutput[1][i], coutput[2][i]); + *out++ + = stbi__compute_y(coutput[0][i], coutput[1][i], coutput[2][i]); else { for (i = 0; i < z->s->img_x; ++i, out += 2) { - out[0] = stbi__compute_y( - coutput[0][i], coutput[1][i], coutput[2][i]); + out[0] + = stbi__compute_y(coutput[0][i], coutput[1][i], coutput[2][i]); out[1] = 255; } } @@ -4342,8 +4182,7 @@ static stbi_uc * load_jpeg_image(stbi__jpeg * z, int * out_x, int * out_y, } } else if (z->s->img_n == 4 && z->app14_color_transform == 2) { for (i = 0; i < z->s->img_x; ++i) { - out[0] = stbi__blinn_8x8(255 - coutput[0][i], - coutput[3][i]); + out[0] = stbi__blinn_8x8(255 - coutput[0][i], coutput[3][i]); out[1] = 255; out += n; } @@ -4362,16 +4201,13 @@ static stbi_uc * load_jpeg_image(stbi__jpeg * z, int * out_x, int * out_y, stbi__cleanup_jpeg(z); *out_x = z->s->img_x; *out_y = z->s->img_y; - if (comp) - *comp = z->s->img_n >= 3 - ? 3 - : 1; // report original components, not output + if (comp) *comp = z->s->img_n >= 3 ? 3 : 1; // report original components, not output return output; } } -static void * stbi__jpeg_load(stbi__context * s, int * x, int * y, int * comp, - int req_comp, stbi__result_info * ri) { +static void * stbi__jpeg_load(stbi__context * s, int * x, int * y, int * comp, int req_comp, + stbi__result_info * ri) { unsigned char * result; stbi__jpeg * j = (stbi__jpeg *) stbi__malloc(sizeof(stbi__jpeg)); if (!j) return stbi__errpuc("outofmem", "Out of memory"); @@ -4460,8 +4296,7 @@ stbi_inline static int stbi__bit_reverse(int v, int bits) { return stbi__bitreverse16(v) >> (16 - bits); } -static int stbi__zbuild_huffman(stbi__zhuffman * z, const stbi_uc * sizelist, - int num) { +static int stbi__zbuild_huffman(stbi__zhuffman * z, const stbi_uc * sizelist, int num) { int i, k = 0; int code, next_code[16], sizes[17]; @@ -4479,8 +4314,7 @@ static int stbi__zbuild_huffman(stbi__zhuffman * z, const stbi_uc * sizelist, z->firstsymbol[i] = (stbi__uint16) k; code = (code + sizes[i]); if (sizes[i]) - if (code - 1 >= (1 << i)) - return stbi__err("bad codelengths", "Corrupt PNG"); + if (code - 1 >= (1 << i)) return stbi__err("bad codelengths", "Corrupt PNG"); z->maxcode[i] = code << (16 - i); // preshift for inner loop code <<= 1; k += sizes[i]; @@ -4526,9 +4360,7 @@ typedef struct { stbi__zhuffman z_length, z_distance; } stbi__zbuf; -stbi_inline static int stbi__zeof(stbi__zbuf * z) { - return (z->zbuffer >= z->zbuffer_end); -} +stbi_inline static int stbi__zeof(stbi__zbuf * z) { return (z->zbuffer >= z->zbuffer_end); } stbi_inline static stbi_uc stbi__zget8(stbi__zbuf * z) { return stbi__zeof(z) ? 0 : *z->zbuffer++; @@ -4565,15 +4397,13 @@ static int stbi__zhuffman_decode_slowpath(stbi__zbuf * a, stbi__zhuffman * z) { // code size is s, so: b = (k >> (16 - s)) - z->firstcode[s] + z->firstsymbol[s]; if (b >= STBI__ZNSYMS) return -1; // some data was corrupt somewhere! - if (z->size[b] != s) - return -1; // was originally an assert, but report failure instead. + if (z->size[b] != s) return -1; // was originally an assert, but report failure instead. a->code_buffer >>= s; a->num_bits -= s; return z->value[b]; } -stbi_inline static int stbi__zhuffman_decode(stbi__zbuf * a, - stbi__zhuffman * z) { +stbi_inline static int stbi__zhuffman_decode(stbi__zbuf * a, stbi__zhuffman * z) { int b, s; if (a->num_bits < 16) { if (stbi__zeof(a)) { @@ -4608,12 +4438,10 @@ static int stbi__zexpand(stbi__zbuf * z, char * zout, char * q; unsigned int cur, limit, old_limit; z->zout = zout; - if (!z->z_expandable) - return stbi__err("output buffer limit", "Corrupt PNG"); + if (!z->z_expandable) return stbi__err("output buffer limit", "Corrupt PNG"); cur = (unsigned int) (z->zout - z->zout_start); limit = old_limit = (unsigned) (z->zout_end - z->zout_start); - if (UINT_MAX - cur < (unsigned) n) - return stbi__err("outofmem", "Out of memory"); + if (UINT_MAX - cur < (unsigned) n) return stbi__err("outofmem", "Out of memory"); while (cur + n > limit) { if (limit > UINT_MAX / 2) return stbi__err("outofmem", "Out of memory"); limit *= 2; @@ -4631,18 +4459,16 @@ static const int stbi__zlength_base[31] = {3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0}; -static const int stbi__zlength_extra[31] - = {0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, - 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, 0, 0}; +static const int stbi__zlength_extra[31] = {0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, + 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, 0, 0}; static const int stbi__zdist_base[32] = {1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577, 0, 0}; -static const int stbi__zdist_extra[32] - = {0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, - 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13}; +static const int stbi__zdist_extra[32] = {0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, + 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13}; static int stbi__parse_huffman_block(stbi__zbuf * a) { char * zout = a->zout; @@ -4677,18 +4503,15 @@ static int stbi__parse_huffman_block(stbi__zbuf * a) { "Corrupt PNG"); // per DEFLATE, length codes 286 and 287 must not appear in compressed data z -= 257; len = stbi__zlength_base[z]; - if (stbi__zlength_extra[z]) - len += stbi__zreceive(a, stbi__zlength_extra[z]); + if (stbi__zlength_extra[z]) len += stbi__zreceive(a, stbi__zlength_extra[z]); z = stbi__zhuffman_decode(a, &a->z_distance); if (z < 0 || z >= 30) return stbi__err( "bad huffman code", "Corrupt PNG"); // per DEFLATE, distance codes 30 and 31 must not appear in compressed data dist = stbi__zdist_base[z]; - if (stbi__zdist_extra[z]) - dist += stbi__zreceive(a, stbi__zdist_extra[z]); - if (zout - a->zout_start < dist) - return stbi__err("bad dist", "Corrupt PNG"); + if (stbi__zdist_extra[z]) dist += stbi__zreceive(a, stbi__zdist_extra[z]); + if (zout - a->zout_start < dist) return stbi__err("bad dist", "Corrupt PNG"); if (len > a->zout_end - zout) { if (!stbi__zexpand(a, zout, len)) return 0; zout = a->zout; @@ -4733,8 +4556,7 @@ static int stbi__compute_huffman_codes(stbi__zbuf * a) { n = 0; while (n < ntot) { int c = stbi__zhuffman_decode(a, &z_codelength); - if (c < 0 || c >= 19) - return stbi__err("bad codelengths", "Corrupt PNG"); + if (c < 0 || c >= 19) return stbi__err("bad codelengths", "Corrupt PNG"); if (c < 16) lencodes[n++] = (stbi_uc) c; else { stbi_uc fill = 0; @@ -4749,8 +4571,7 @@ static int stbi__compute_huffman_codes(stbi__zbuf * a) { } else { return stbi__err("bad codelengths", "Corrupt PNG"); } - if (ntot - n < c) - return stbi__err("bad codelengths", "Corrupt PNG"); + if (ntot - n < c) return stbi__err("bad codelengths", "Corrupt PNG"); memset(lencodes + n, fill, c); n += c; } @@ -4768,8 +4589,7 @@ static int stbi__parse_uncompressed_block(stbi__zbuf * a) { // drain the bit-packed data into header k = 0; while (a->num_bits > 0) { - header[k++] - = (stbi_uc) (a->code_buffer & 255); // suppress MSVC run-time check + header[k++] = (stbi_uc) (a->code_buffer & 255); // suppress MSVC run-time check a->code_buffer >>= 8; a->num_bits -= 8; } @@ -4779,8 +4599,7 @@ static int stbi__parse_uncompressed_block(stbi__zbuf * a) { len = header[1] * 256 + header[0]; nlen = header[3] * 256 + header[2]; if (nlen != (len ^ 0xffff)) return stbi__err("zlib corrupt", "Corrupt PNG"); - if (a->zbuffer + len > a->zbuffer_end) - return stbi__err("read past buffer", "Corrupt PNG"); + if (a->zbuffer + len > a->zbuffer_end) return stbi__err("read past buffer", "Corrupt PNG"); if (a->zout + len > a->zout_end) if (!stbi__zexpand(a, a->zout, len)) return 0; memcpy(a->zout, a->zbuffer, len); @@ -4794,8 +4613,7 @@ static int stbi__parse_zlib_header(stbi__zbuf * a) { int cm = cmf & 15; /* int cinfo = cmf >> 4; */ int flg = stbi__zget8(a); - if (stbi__zeof(a)) - return stbi__err("bad zlib header", "Corrupt PNG"); // zlib spec + if (stbi__zeof(a)) return stbi__err("bad zlib header", "Corrupt PNG"); // zlib spec if ((cmf * 256 + flg) % 31 != 0) return stbi__err("bad zlib header", "Corrupt PNG"); // zlib spec if (flg & 32) @@ -4809,18 +4627,16 @@ static int stbi__parse_zlib_header(stbi__zbuf * a) { } static const stbi_uc stbi__zdefault_length[STBI__ZNSYMS] - = {8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, - 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, - 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, - 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, - 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, - 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, - 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, - 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, - 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, - 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, - 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 7, 7, 7, 7, 7, 7, 7, 7, - 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8}; + = {8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9, + 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, + 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, + 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, + 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 7, 7, 7, 7, 7, + 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8}; static const stbi_uc stbi__zdefault_distance[32] = {5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5}; @@ -4854,11 +4670,9 @@ static int stbi__parse_zlib(stbi__zbuf * a, int parse_header) { } else { if (type == 1) { // use fixed code lengths - if (!stbi__zbuild_huffman(&a->z_length, stbi__zdefault_length, - STBI__ZNSYMS)) + if (!stbi__zbuild_huffman(&a->z_length, stbi__zdefault_length, STBI__ZNSYMS)) return 0; - if (!stbi__zbuild_huffman(&a->z_distance, - stbi__zdefault_distance, 32)) + if (!stbi__zbuild_huffman(&a->z_distance, stbi__zdefault_distance, 32)) return 0; } else { if (!stbi__compute_huffman_codes(a)) return 0; @@ -4869,8 +4683,7 @@ static int stbi__parse_zlib(stbi__zbuf * a, int parse_header) { return 1; } -static int stbi__do_zlib(stbi__zbuf * a, char * obuf, int olen, int exp, - int parse_header) { +static int stbi__do_zlib(stbi__zbuf * a, char * obuf, int olen, int exp, int parse_header) { a->zout_start = obuf; a->zout = obuf; a->zout_end = obuf + olen; @@ -4880,8 +4693,7 @@ static int stbi__do_zlib(stbi__zbuf * a, char * obuf, int olen, int exp, } STBIDEF char * stbi_zlib_decode_malloc_guesssize(const char * buffer, int len, - int initial_size, - int * outlen) { + int initial_size, int * outlen) { stbi__zbuf a; char * p = (char *) stbi__malloc(initial_size); if (p == NULL) return NULL; @@ -4896,15 +4708,12 @@ STBIDEF char * stbi_zlib_decode_malloc_guesssize(const char * buffer, int len, } } -STBIDEF char * stbi_zlib_decode_malloc(char const * buffer, int len, - int * outlen) { +STBIDEF char * stbi_zlib_decode_malloc(char const * buffer, int len, int * outlen) { return stbi_zlib_decode_malloc_guesssize(buffer, len, 16384, outlen); } -STBIDEF char * stbi_zlib_decode_malloc_guesssize_headerflag(const char * buffer, - int len, - int initial_size, - int * outlen, +STBIDEF char * stbi_zlib_decode_malloc_guesssize_headerflag(const char * buffer, int len, + int initial_size, int * outlen, int parse_header) { stbi__zbuf a; char * p = (char *) stbi__malloc(initial_size); @@ -4920,18 +4729,15 @@ STBIDEF char * stbi_zlib_decode_malloc_guesssize_headerflag(const char * buffer, } } -STBIDEF int stbi_zlib_decode_buffer(char * obuffer, int olen, - char const * ibuffer, int ilen) { +STBIDEF int stbi_zlib_decode_buffer(char * obuffer, int olen, char const * ibuffer, int ilen) { stbi__zbuf a; a.zbuffer = (stbi_uc *) ibuffer; a.zbuffer_end = (stbi_uc *) ibuffer + ilen; - if (stbi__do_zlib(&a, obuffer, olen, 0, 1)) - return (int) (a.zout - a.zout_start); + if (stbi__do_zlib(&a, obuffer, olen, 0, 1)) return (int) (a.zout - a.zout_start); else return -1; } -STBIDEF char * stbi_zlib_decode_noheader_malloc(char const * buffer, int len, - int * outlen) { +STBIDEF char * stbi_zlib_decode_noheader_malloc(char const * buffer, int len, int * outlen) { stbi__zbuf a; char * p = (char *) stbi__malloc(16384); if (p == NULL) return NULL; @@ -4946,13 +4752,12 @@ STBIDEF char * stbi_zlib_decode_noheader_malloc(char const * buffer, int len, } } -STBIDEF int stbi_zlib_decode_noheader_buffer(char * obuffer, int olen, - const char * ibuffer, int ilen) { +STBIDEF int stbi_zlib_decode_noheader_buffer(char * obuffer, int olen, const char * ibuffer, + int ilen) { stbi__zbuf a; a.zbuffer = (stbi_uc *) ibuffer; a.zbuffer_end = (stbi_uc *) ibuffer + ilen; - if (stbi__do_zlib(&a, obuffer, olen, 0, 0)) - return (int) (a.zout - a.zout_start); + if (stbi__do_zlib(&a, obuffer, olen, 0, 0)) return (int) (a.zout - a.zout_start); else return -1; } #endif @@ -4984,8 +4789,7 @@ static int stbi__check_png_header(stbi__context * s) { static const stbi_uc png_sig[8] = {137, 80, 78, 71, 13, 10, 26, 10}; int i; for (i = 0; i < 8; ++i) - if (stbi__get8(s) != png_sig[i]) - return stbi__err("bad png sig", "Not a PNG"); + if (stbi__get8(s) != png_sig[i]) return stbi__err("bad png sig", "Not a PNG"); return 1; } @@ -5022,14 +4826,13 @@ static int stbi__paeth(int a, int b, int c) { return t1; } -static const stbi_uc stbi__depth_scale_table[9] - = {0, 0xff, 0x55, 0, 0x11, 0, 0, 0, 0x01}; +static const stbi_uc stbi__depth_scale_table[9] = {0, 0xff, 0x55, 0, 0x11, 0, 0, 0, 0x01}; // adds an extra all-255 alpha channel // dest == src is legal // img_n must be 1 or 3 -static void stbi__create_png_alpha_expand8(stbi_uc * dest, stbi_uc * src, - stbi__uint32 x, int img_n) { +static void stbi__create_png_alpha_expand8(stbi_uc * dest, stbi_uc * src, stbi__uint32 x, + int img_n) { int i; // must process data backwards since we allow dest==src if (img_n == 1) { @@ -5049,9 +4852,8 @@ static void stbi__create_png_alpha_expand8(stbi_uc * dest, stbi_uc * src, } // create the png data from post-deflated data -static int stbi__create_png_image_raw(stbi__png * a, stbi_uc * raw, - stbi__uint32 raw_len, int out_n, - stbi__uint32 x, stbi__uint32 y, int depth, +static int stbi__create_png_image_raw(stbi__png * a, stbi_uc * raw, stbi__uint32 raw_len, + int out_n, stbi__uint32 x, stbi__uint32 y, int depth, int color) { int bytes = (depth == 16 ? 2 : 1); stbi__context * s = a->s; @@ -5067,8 +4869,8 @@ static int stbi__create_png_image_raw(stbi__png * a, stbi_uc * raw, int width = x; STBI_ASSERT(out_n == s->img_n || out_n == s->img_n + 1); - a->out = (stbi_uc *) stbi__malloc_mad3( - x, y, output_bytes, 0); // extra bytes to write off the end into + a->out = (stbi_uc *) stbi__malloc_mad3(x, y, output_bytes, + 0); // extra bytes to write off the end into if (!a->out) return stbi__err("outofmem", "Out of memory"); // note: error exits here don't need to clean up a->out individually, @@ -5123,32 +4925,28 @@ static int stbi__create_png_image_raw(stbi__png * a, stbi_uc * raw, cur[k] = STBI__BYTECAST(raw[k] + cur[k - filter_bytes]); break; case STBI__F_up: - for (k = 0; k < nk; ++k) - cur[k] = STBI__BYTECAST(raw[k] + prior[k]); + for (k = 0; k < nk; ++k) cur[k] = STBI__BYTECAST(raw[k] + prior[k]); break; case STBI__F_avg: for (k = 0; k < filter_bytes; ++k) cur[k] = STBI__BYTECAST(raw[k] + (prior[k] >> 1)); for (k = filter_bytes; k < nk; ++k) - cur[k] = STBI__BYTECAST( - raw[k] + ((prior[k] + cur[k - filter_bytes]) >> 1)); + cur[k] + = STBI__BYTECAST(raw[k] + ((prior[k] + cur[k - filter_bytes]) >> 1)); break; case STBI__F_paeth: for (k = 0; k < filter_bytes; ++k) cur[k] = STBI__BYTECAST( - raw[k] - + prior[k]); // prior[k] == stbi__paeth(0,prior[k],0) + raw[k] + prior[k]); // prior[k] == stbi__paeth(0,prior[k],0) for (k = filter_bytes; k < nk; ++k) - cur[k] = STBI__BYTECAST( - raw[k] - + stbi__paeth(cur[k - filter_bytes], prior[k], - prior[k - filter_bytes])); + cur[k] = STBI__BYTECAST(raw[k] + + stbi__paeth(cur[k - filter_bytes], prior[k], + prior[k - filter_bytes])); break; case STBI__F_avg_first: memcpy(cur, raw, filter_bytes); for (k = filter_bytes; k < nk; ++k) - cur[k] - = STBI__BYTECAST(raw[k] + (cur[k - filter_bytes] >> 1)); + cur[k] = STBI__BYTECAST(raw[k] + (cur[k - filter_bytes] >> 1)); break; } @@ -5156,9 +4954,8 @@ static int stbi__create_png_image_raw(stbi__png * a, stbi_uc * raw, // expand decoded bits in cur to dest, also adding an extra alpha channel if desired if (depth < 8) { - stbi_uc scale = (color == 0) - ? stbi__depth_scale_table[depth] - : 1; // scale grayscale values to 0..255 range + stbi_uc scale = (color == 0) ? stbi__depth_scale_table[depth] + : 1; // scale grayscale values to 0..255 range stbi_uc * in = cur; stbi_uc * out = dest; stbi_uc inb = 0; @@ -5187,8 +4984,7 @@ static int stbi__create_png_image_raw(stbi__png * a, stbi_uc * raw, } // insert alpha=255 values if desired - if (img_n != out_n) - stbi__create_png_alpha_expand8(dest, dest, x, img_n); + if (img_n != out_n) stbi__create_png_alpha_expand8(dest, dest, x, img_n); } else if (depth == 8) { if (img_n == out_n) memcpy(dest, cur, x * img_n); else stbi__create_png_alpha_expand8(dest, cur, x, img_n); @@ -5227,20 +5023,18 @@ static int stbi__create_png_image_raw(stbi__png * a, stbi_uc * raw, } static int stbi__create_png_image(stbi__png * a, stbi_uc * image_data, - stbi__uint32 image_data_len, int out_n, - int depth, int color, int interlaced) { + stbi__uint32 image_data_len, int out_n, int depth, int color, + int interlaced) { int bytes = (depth == 16 ? 2 : 1); int out_bytes = out_n * bytes; stbi_uc * final; int p; if (!interlaced) - return stbi__create_png_image_raw(a, image_data, image_data_len, out_n, - a->s->img_x, a->s->img_y, depth, - color); + return stbi__create_png_image_raw(a, image_data, image_data_len, out_n, a->s->img_x, + a->s->img_y, depth, color); // de-interlacing - final - = (stbi_uc *) stbi__malloc_mad3(a->s->img_x, a->s->img_y, out_bytes, 0); + final = (stbi_uc *) stbi__malloc_mad3(a->s->img_x, a->s->img_y, out_bytes, 0); if (!final) return stbi__err("outofmem", "Out of memory"); for (p = 0; p < 7; ++p) { int xorig[] = {0, 4, 0, 2, 0, 1, 0}; @@ -5252,10 +5046,9 @@ static int stbi__create_png_image(stbi__png * a, stbi_uc * image_data, x = (a->s->img_x - xorig[p] + xspc[p] - 1) / xspc[p]; y = (a->s->img_y - yorig[p] + yspc[p] - 1) / yspc[p]; if (x && y) { - stbi__uint32 img_len - = ((((a->s->img_n * x * depth) + 7) >> 3) + 1) * y; - if (!stbi__create_png_image_raw(a, image_data, image_data_len, - out_n, x, y, depth, color)) { + stbi__uint32 img_len = ((((a->s->img_n * x * depth) + 7) >> 3) + 1) * y; + if (!stbi__create_png_image_raw(a, image_data, image_data_len, out_n, x, y, depth, + color)) { STBI_FREE(final); return 0; } @@ -5263,8 +5056,7 @@ static int stbi__create_png_image(stbi__png * a, stbi_uc * image_data, for (i = 0; i < x; ++i) { int out_y = j * yspc[p] + yorig[p]; int out_x = i * xspc[p] + xorig[p]; - memcpy(final + out_y * a->s->img_x * out_bytes - + out_x * out_bytes, + memcpy(final + out_y * a->s->img_x * out_bytes + out_x * out_bytes, a->out + (j * x + i) * out_bytes, out_bytes); } } @@ -5301,8 +5093,7 @@ static int stbi__compute_transparency(stbi__png * z, stbi_uc tc[3], int out_n) { return 1; } -static int stbi__compute_transparency16(stbi__png * z, stbi__uint16 tc[3], - int out_n) { +static int stbi__compute_transparency16(stbi__png * z, stbi__uint16 tc[3], int out_n) { stbi__context * s = z->s; stbi__uint32 i, pixel_count = s->img_x * s->img_y; stbi__uint16 * p = (stbi__uint16 *) z->out; @@ -5325,8 +5116,7 @@ static int stbi__compute_transparency16(stbi__png * z, stbi__uint16 tc[3], return 1; } -static int stbi__expand_png_palette(stbi__png * a, stbi_uc * palette, int len, - int pal_img_n) { +static int stbi__expand_png_palette(stbi__png * a, stbi_uc * palette, int len, int pal_img_n) { stbi__uint32 i, pixel_count = a->s->img_x * a->s->img_y; stbi_uc *p, *temp_out, *orig = a->out; @@ -5365,8 +5155,7 @@ static int stbi__expand_png_palette(stbi__png * a, stbi_uc * palette, int len, static int stbi__unpremultiply_on_load_global = 0; static int stbi__de_iphone_flag_global = 0; -STBIDEF void -stbi_set_unpremultiply_on_load(int flag_true_if_should_unpremultiply) { +STBIDEF void stbi_set_unpremultiply_on_load(int flag_true_if_should_unpremultiply) { stbi__unpremultiply_on_load_global = flag_true_if_should_unpremultiply; } @@ -5380,17 +5169,14 @@ STBIDEF void stbi_convert_iphone_png_to_rgb(int flag_true_if_should_convert) { #else static STBI_THREAD_LOCAL int stbi__unpremultiply_on_load_local, stbi__unpremultiply_on_load_set; -static STBI_THREAD_LOCAL int stbi__de_iphone_flag_local, - stbi__de_iphone_flag_set; +static STBI_THREAD_LOCAL int stbi__de_iphone_flag_local, stbi__de_iphone_flag_set; -STBIDEF void -stbi_set_unpremultiply_on_load_thread(int flag_true_if_should_unpremultiply) { +STBIDEF void stbi_set_unpremultiply_on_load_thread(int flag_true_if_should_unpremultiply) { stbi__unpremultiply_on_load_local = flag_true_if_should_unpremultiply; stbi__unpremultiply_on_load_set = 1; } -STBIDEF void -stbi_convert_iphone_png_to_rgb_thread(int flag_true_if_should_convert) { +STBIDEF void stbi_convert_iphone_png_to_rgb_thread(int flag_true_if_should_convert) { stbi__de_iphone_flag_local = flag_true_if_should_convert; stbi__de_iphone_flag_set = 1; } @@ -5399,8 +5185,7 @@ stbi_convert_iphone_png_to_rgb_thread(int flag_true_if_should_convert) { (stbi__unpremultiply_on_load_set ? stbi__unpremultiply_on_load_local \ : stbi__unpremultiply_on_load_global) #define stbi__de_iphone_flag \ - (stbi__de_iphone_flag_set ? stbi__de_iphone_flag_local \ - : stbi__de_iphone_flag_global) + (stbi__de_iphone_flag_set ? stbi__de_iphone_flag_local : stbi__de_iphone_flag_global) #endif // STBI_THREAD_LOCAL static void stbi__de_iphone(stbi__png * z) { @@ -5446,8 +5231,7 @@ static void stbi__de_iphone(stbi__png * z) { } #define STBI__PNG_TYPE(a, b, c, d) \ - (((unsigned) (a) << 24) + ((unsigned) (b) << 16) + ((unsigned) (c) << 8) \ - + (unsigned) (d)) + (((unsigned) (a) << 24) + ((unsigned) (b) << 16) + ((unsigned) (c) << 8) + (unsigned) (d)) static int stbi__parse_png_file(stbi__png * z, int scan, int req_comp) { stbi_uc palette[1024], pal_img_n = 0; @@ -5476,43 +5260,34 @@ static int stbi__parse_png_file(stbi__png * z, int scan, int req_comp) { int comp, filter; if (!first) return stbi__err("multiple IHDR", "Corrupt PNG"); first = 0; - if (c.length != 13) - return stbi__err("bad IHDR len", "Corrupt PNG"); + if (c.length != 13) return stbi__err("bad IHDR len", "Corrupt PNG"); s->img_x = stbi__get32be(s); s->img_y = stbi__get32be(s); if (s->img_y > STBI_MAX_DIMENSIONS) - return stbi__err("too large", - "Very large image (corrupt?)"); + return stbi__err("too large", "Very large image (corrupt?)"); if (s->img_x > STBI_MAX_DIMENSIONS) - return stbi__err("too large", - "Very large image (corrupt?)"); + return stbi__err("too large", "Very large image (corrupt?)"); z->depth = stbi__get8(s); - if (z->depth != 1 && z->depth != 2 && z->depth != 4 - && z->depth != 8 && z->depth != 16) + if (z->depth != 1 && z->depth != 2 && z->depth != 4 && z->depth != 8 + && z->depth != 16) return stbi__err("1/2/4/8/16-bit only", "PNG not supported: 1/2/4/8/16-bit only"); color = stbi__get8(s); if (color > 6) return stbi__err("bad ctype", "Corrupt PNG"); - if (color == 3 && z->depth == 16) - return stbi__err("bad ctype", "Corrupt PNG"); + if (color == 3 && z->depth == 16) return stbi__err("bad ctype", "Corrupt PNG"); if (color == 3) pal_img_n = 3; - else if (color & 1) - return stbi__err("bad ctype", "Corrupt PNG"); + else if (color & 1) return stbi__err("bad ctype", "Corrupt PNG"); comp = stbi__get8(s); if (comp) return stbi__err("bad comp method", "Corrupt PNG"); filter = stbi__get8(s); - if (filter) - return stbi__err("bad filter method", "Corrupt PNG"); + if (filter) return stbi__err("bad filter method", "Corrupt PNG"); interlace = stbi__get8(s); - if (interlace > 1) - return stbi__err("bad interlace method", "Corrupt PNG"); - if (!s->img_x || !s->img_y) - return stbi__err("0-pixel image", "Corrupt PNG"); + if (interlace > 1) return stbi__err("bad interlace method", "Corrupt PNG"); + if (!s->img_x || !s->img_y) return stbi__err("0-pixel image", "Corrupt PNG"); if (!pal_img_n) { s->img_n = (color & 2 ? 3 : 1) + (color & 4 ? 1 : 0); if ((1 << 30) / s->img_x / s->img_n < s->img_y) - return stbi__err("too large", - "Image too large to decode"); + return stbi__err("too large", "Image too large to decode"); } else { // if paletted, then pal_n is our final components, and // img_n is # components to decompress/filter. @@ -5526,11 +5301,9 @@ static int stbi__parse_png_file(stbi__png * z, int scan, int req_comp) { case STBI__PNG_TYPE('P', 'L', 'T', 'E'): { if (first) return stbi__err("first not IHDR", "Corrupt PNG"); - if (c.length > 256 * 3) - return stbi__err("invalid PLTE", "Corrupt PNG"); + if (c.length > 256 * 3) return stbi__err("invalid PLTE", "Corrupt PNG"); pal_len = c.length / 3; - if (pal_len * 3 != c.length) - return stbi__err("invalid PLTE", "Corrupt PNG"); + if (pal_len * 3 != c.length) return stbi__err("invalid PLTE", "Corrupt PNG"); for (i = 0; i < pal_len; ++i) { palette[i * 4 + 0] = stbi__get8(s); palette[i * 4 + 1] = stbi__get8(s); @@ -5542,23 +5315,18 @@ static int stbi__parse_png_file(stbi__png * z, int scan, int req_comp) { case STBI__PNG_TYPE('t', 'R', 'N', 'S'): { if (first) return stbi__err("first not IHDR", "Corrupt PNG"); - if (z->idata) - return stbi__err("tRNS after IDAT", "Corrupt PNG"); + if (z->idata) return stbi__err("tRNS after IDAT", "Corrupt PNG"); if (pal_img_n) { if (scan == STBI__SCAN_header) { s->img_n = 4; return 1; } - if (pal_len == 0) - return stbi__err("tRNS before PLTE", "Corrupt PNG"); - if (c.length > pal_len) - return stbi__err("bad tRNS len", "Corrupt PNG"); + if (pal_len == 0) return stbi__err("tRNS before PLTE", "Corrupt PNG"); + if (c.length > pal_len) return stbi__err("bad tRNS len", "Corrupt PNG"); pal_img_n = 4; - for (i = 0; i < c.length; ++i) - palette[i * 4 + 3] = stbi__get8(s); + for (i = 0; i < c.length; ++i) palette[i * 4 + 3] = stbi__get8(s); } else { - if (!(s->img_n & 1)) - return stbi__err("tRNS with alpha", "Corrupt PNG"); + if (!(s->img_n & 1)) return stbi__err("tRNS with alpha", "Corrupt PNG"); if (c.length != (stbi__uint32) s->img_n * 2) return stbi__err("bad tRNS len", "Corrupt PNG"); has_trans = 1; @@ -5569,14 +5337,12 @@ static int stbi__parse_png_file(stbi__png * z, int scan, int req_comp) { } if (z->depth == 16) { for (k = 0; k < s->img_n; ++k) - tc16[k] = (stbi__uint16) stbi__get16be( - s); // copy the values as-is + tc16[k] = (stbi__uint16) stbi__get16be(s); // copy the values as-is } else { for (k = 0; k < s->img_n; ++k) - tc[k] - = (stbi_uc) (stbi__get16be(s) & 255) - * stbi__depth_scale_table - [z->depth]; // non 8-bit images will be larger + tc[k] = (stbi_uc) (stbi__get16be(s) & 255) + * stbi__depth_scale_table + [z->depth]; // non 8-bit images will be larger } } break; @@ -5584,28 +5350,23 @@ static int stbi__parse_png_file(stbi__png * z, int scan, int req_comp) { case STBI__PNG_TYPE('I', 'D', 'A', 'T'): { if (first) return stbi__err("first not IHDR", "Corrupt PNG"); - if (pal_img_n && !pal_len) - return stbi__err("no PLTE", "Corrupt PNG"); + if (pal_img_n && !pal_len) return stbi__err("no PLTE", "Corrupt PNG"); if (scan == STBI__SCAN_header) { // header scan definitely stops at first IDAT if (pal_img_n) s->img_n = pal_img_n; return 1; } if (c.length > (1u << 30)) - return stbi__err("IDAT size limit", - "IDAT section larger than 2^30 bytes"); + return stbi__err("IDAT size limit", "IDAT section larger than 2^30 bytes"); if ((int) (ioff + c.length) < (int) ioff) return 0; if (ioff + c.length > idata_limit) { stbi__uint32 idata_limit_old = idata_limit; stbi_uc * p; - if (idata_limit == 0) - idata_limit = c.length > 4096 ? c.length : 4096; + if (idata_limit == 0) idata_limit = c.length > 4096 ? c.length : 4096; while (ioff + c.length > idata_limit) idata_limit *= 2; STBI_NOTUSED(idata_limit_old); - p = (stbi_uc *) STBI_REALLOC_SIZED( - z->idata, idata_limit_old, idata_limit); - if (p == NULL) - return stbi__err("outofmem", "Out of memory"); + p = (stbi_uc *) STBI_REALLOC_SIZED(z->idata, idata_limit_old, idata_limit); + if (p == NULL) return stbi__err("outofmem", "Out of memory"); z->idata = p; } if (!stbi__getn(s, z->idata + ioff, c.length)) @@ -5618,48 +5379,36 @@ static int stbi__parse_png_file(stbi__png * z, int scan, int req_comp) { stbi__uint32 raw_len, bpl; if (first) return stbi__err("first not IHDR", "Corrupt PNG"); if (scan != STBI__SCAN_load) return 1; - if (z->idata == NULL) - return stbi__err("no IDAT", "Corrupt PNG"); + if (z->idata == NULL) return stbi__err("no IDAT", "Corrupt PNG"); // initial guess for decoded data size to avoid unnecessary reallocs - bpl = (s->img_x * z->depth + 7) - / 8; // bytes per line, per component + bpl = (s->img_x * z->depth + 7) / 8; // bytes per line, per component raw_len = bpl * s->img_y * s->img_n /* pixels */ + s->img_y /* filter mode per row */; - z->expanded - = (stbi_uc *) stbi_zlib_decode_malloc_guesssize_headerflag( - (char *) z->idata, ioff, raw_len, (int *) &raw_len, - !is_iphone); + z->expanded = (stbi_uc *) stbi_zlib_decode_malloc_guesssize_headerflag( + (char *) z->idata, ioff, raw_len, (int *) &raw_len, !is_iphone); if (z->expanded == NULL) return 0; // zlib should set error STBI_FREE(z->idata); z->idata = NULL; - if ((req_comp == s->img_n + 1 && req_comp != 3 && !pal_img_n) - || has_trans) + if ((req_comp == s->img_n + 1 && req_comp != 3 && !pal_img_n) || has_trans) s->img_out_n = s->img_n + 1; else s->img_out_n = s->img_n; - if (!stbi__create_png_image(z, z->expanded, raw_len, - s->img_out_n, z->depth, color, - interlace)) + if (!stbi__create_png_image(z, z->expanded, raw_len, s->img_out_n, z->depth, + color, interlace)) return 0; if (has_trans) { if (z->depth == 16) { - if (!stbi__compute_transparency16(z, tc16, - s->img_out_n)) - return 0; + if (!stbi__compute_transparency16(z, tc16, s->img_out_n)) return 0; } else { - if (!stbi__compute_transparency(z, tc, s->img_out_n)) - return 0; + if (!stbi__compute_transparency(z, tc, s->img_out_n)) return 0; } } - if (is_iphone && stbi__de_iphone_flag && s->img_out_n > 2) - stbi__de_iphone(z); + if (is_iphone && stbi__de_iphone_flag && s->img_out_n > 2) stbi__de_iphone(z); if (pal_img_n) { // pal_img_n == 3 or 4 s->img_n = pal_img_n; // record the actual colors we had s->img_out_n = pal_img_n; if (req_comp >= 3) s->img_out_n = req_comp; - if (!stbi__expand_png_palette(z, palette, pal_len, - s->img_out_n)) - return 0; + if (!stbi__expand_png_palette(z, palette, pal_len, s->img_out_n)) return 0; } else if (has_trans) { // non-paletted image with tRNS -> source image has (constant) alpha ++s->img_n; @@ -5683,9 +5432,8 @@ static int stbi__parse_png_file(stbi__png * z, int scan, int req_comp) { invalid_chunk[2] = STBI__BYTECAST(c.type >> 8); invalid_chunk[3] = STBI__BYTECAST(c.type >> 0); #endif - return stbi__err( - invalid_chunk, - "PNG not supported: unknown PNG chunk type"); + return stbi__err(invalid_chunk, + "PNG not supported: unknown PNG chunk type"); } stbi__skip(s, c.length); break; @@ -5695,11 +5443,10 @@ static int stbi__parse_png_file(stbi__png * z, int scan, int req_comp) { } } -static void * stbi__do_png(stbi__png * p, int * x, int * y, int * n, - int req_comp, stbi__result_info * ri) { +static void * stbi__do_png(stbi__png * p, int * x, int * y, int * n, int req_comp, + stbi__result_info * ri) { void * result = NULL; - if (req_comp < 0 || req_comp > 4) - return stbi__errpuc("bad req_comp", "Internal error"); + if (req_comp < 0 || req_comp > 4) return stbi__errpuc("bad req_comp", "Internal error"); if (stbi__parse_png_file(p, STBI__SCAN_load, req_comp)) { if (p->depth <= 8) ri->bits_per_channel = 8; else if (p->depth == 16) ri->bits_per_channel = 16; @@ -5710,13 +5457,11 @@ static void * stbi__do_png(stbi__png * p, int * x, int * y, int * n, p->out = NULL; if (req_comp && req_comp != p->s->img_out_n) { if (ri->bits_per_channel == 8) - result = stbi__convert_format((unsigned char *) result, - p->s->img_out_n, req_comp, - p->s->img_x, p->s->img_y); + result = stbi__convert_format((unsigned char *) result, p->s->img_out_n, + req_comp, p->s->img_x, p->s->img_y); else - result = stbi__convert_format16((stbi__uint16 *) result, - p->s->img_out_n, req_comp, - p->s->img_x, p->s->img_y); + result = stbi__convert_format16((stbi__uint16 *) result, p->s->img_out_n, + req_comp, p->s->img_x, p->s->img_y); p->s->img_out_n = req_comp; if (result == NULL) return result; } @@ -5734,8 +5479,8 @@ static void * stbi__do_png(stbi__png * p, int * x, int * y, int * n, return result; } -static void * stbi__png_load(stbi__context * s, int * x, int * y, int * comp, - int req_comp, stbi__result_info * ri) { +static void * stbi__png_load(stbi__context * s, int * x, int * y, int * comp, int req_comp, + stbi__result_info * ri) { stbi__png p; p.s = s; return stbi__do_png(&p, x, y, comp, req_comp, ri); @@ -5926,8 +5671,8 @@ static void * stbi__bmp_parse_header(stbi__context * s, stbi__bmp_data * info) { "BMP type not supported: unsupported " "compression"); // this includes PNG/JPEG modes if (compress == 3 && info->bpp != 16 && info->bpp != 32) - return stbi__errpuc( - "bad BMP", "bad BMP"); // bitfields requires 16 or 32 bits/pixel + return stbi__errpuc("bad BMP", + "bad BMP"); // bitfields requires 16 or 32 bits/pixel stbi__get32le(s); // discard sizeof stbi__get32le(s); // discard hres stbi__get32le(s); // discard vres @@ -5958,18 +5703,15 @@ static void * stbi__bmp_parse_header(stbi__context * s, stbi__bmp_data * info) { } else { // V4/V5 header int i; - if (hsz != 108 && hsz != 124) - return stbi__errpuc("bad BMP", "bad BMP"); + if (hsz != 108 && hsz != 124) return stbi__errpuc("bad BMP", "bad BMP"); info->mr = stbi__get32le(s); info->mg = stbi__get32le(s); info->mb = stbi__get32le(s); info->ma = stbi__get32le(s); - if (compress - != 3) // override mr/mg/mb unless in BI_BITFIELDS mode, as per docs + if (compress != 3) // override mr/mg/mb unless in BI_BITFIELDS mode, as per docs stbi__bmp_set_mask_defaults(info, compress); stbi__get32le(s); // discard color space - for (i = 0; i < 12; ++i) - stbi__get32le(s); // discard color space parameters + for (i = 0; i < 12; ++i) stbi__get32le(s); // discard color space parameters if (hsz == 124) { stbi__get32le(s); // discard rendering intent stbi__get32le(s); // discard offset of profile data @@ -5981,8 +5723,8 @@ static void * stbi__bmp_parse_header(stbi__context * s, stbi__bmp_data * info) { return (void *) 1; } -static void * stbi__bmp_load(stbi__context * s, int * x, int * y, int * comp, - int req_comp, stbi__result_info * ri) { +static void * stbi__bmp_load(stbi__context * s, int * x, int * y, int * comp, int req_comp, + stbi__result_info * ri) { stbi_uc * out; unsigned int mr = 0, mg = 0, mb = 0, ma = 0, all_a; stbi_uc pal[256][4]; @@ -5992,8 +5734,7 @@ static void * stbi__bmp_load(stbi__context * s, int * x, int * y, int * comp, STBI_NOTUSED(ri); info.all_a = 255; - if (stbi__bmp_parse_header(s, &info) == NULL) - return NULL; // error code already set + if (stbi__bmp_parse_header(s, &info) == NULL) return NULL; // error code already set flip_vertically = ((int) s->img_y) > 0; s->img_y = abs((int) s->img_y); @@ -6012,17 +5753,14 @@ static void * stbi__bmp_load(stbi__context * s, int * x, int * y, int * comp, if (info.hsz == 12) { if (info.bpp < 24) psize = (info.offset - info.extra_read - 24) / 3; } else { - if (info.bpp < 16) - psize = (info.offset - info.extra_read - info.hsz) >> 2; + if (info.bpp < 16) psize = (info.offset - info.extra_read - info.hsz) >> 2; } if (psize == 0) { // accept some number of extra bytes after the header, but if the offset points either to before // the header ends or implies a large amount of extra data, reject the file as malformed int bytes_read_so_far - = s->callback_already_read - + (int) (s->img_buffer - s->img_buffer_original); - int header_limit - = 1024; // max we actually read is below 256 bytes currently. + = s->callback_already_read + (int) (s->img_buffer - s->img_buffer_original); + int header_limit = 1024; // max we actually read is below 256 bytes currently. int extra_data_limit = 256 * 4; // what ordinarily goes here is a palette; 256 entries*4 bytes is its max size. @@ -6116,8 +5854,8 @@ static void * stbi__bmp_load(stbi__context * s, int * x, int * y, int * comp, } } } else { - int rshift = 0, gshift = 0, bshift = 0, ashift = 0, rcount = 0, - gcount = 0, bcount = 0, acount = 0; + int rshift = 0, gshift = 0, bshift = 0, ashift = 0, rcount = 0, gcount = 0, bcount = 0, + acount = 0; int z = 0; int easy = 0; stbi__skip(s, info.offset - info.extra_read - info.hsz); @@ -6128,9 +5866,7 @@ static void * stbi__bmp_load(stbi__context * s, int * x, int * y, int * comp, if (info.bpp == 24) { easy = 1; } else if (info.bpp == 32) { - if (mb == 0xff && mg == 0xff00 && mr == 0x00ff0000 - && ma == 0xff000000) - easy = 2; + if (mb == 0xff && mg == 0xff00 && mr == 0x00ff0000 && ma == 0xff000000) easy = 2; } if (!easy) { if (!mr || !mg || !mb) { @@ -6167,15 +5903,11 @@ static void * stbi__bmp_load(stbi__context * s, int * x, int * y, int * comp, int bpp = info.bpp; for (i = 0; i < (int) s->img_x; ++i) { stbi__uint32 v - = (bpp == 16 ? (stbi__uint32) stbi__get16le(s) - : stbi__get32le(s)); + = (bpp == 16 ? (stbi__uint32) stbi__get16le(s) : stbi__get32le(s)); unsigned int a; - out[z++] = STBI__BYTECAST( - stbi__shiftsigned(v & mr, rshift, rcount)); - out[z++] = STBI__BYTECAST( - stbi__shiftsigned(v & mg, gshift, gcount)); - out[z++] = STBI__BYTECAST( - stbi__shiftsigned(v & mb, bshift, bcount)); + out[z++] = STBI__BYTECAST(stbi__shiftsigned(v & mr, rshift, rcount)); + out[z++] = STBI__BYTECAST(stbi__shiftsigned(v & mg, gshift, gcount)); + out[z++] = STBI__BYTECAST(stbi__shiftsigned(v & mb, bshift, bcount)); a = (ma ? stbi__shiftsigned(v & ma, ashift, acount) : 255); all_a |= a; if (target == 4) out[z++] = STBI__BYTECAST(a); @@ -6204,8 +5936,7 @@ static void * stbi__bmp_load(stbi__context * s, int * x, int * y, int * comp, if (req_comp && req_comp != target) { out = stbi__convert_format(out, target, req_comp, s->img_x, s->img_y); - if (out == NULL) - return out; // stbi__convert_format frees input on failure + if (out == NULL) return out; // stbi__convert_format frees input on failure } *x = s->img_x; @@ -6240,8 +5971,7 @@ static int stbi__tga_get_comp(int bits_per_pixel, int is_grey, int * is_rgb16) { } static int stbi__tga_info(stbi__context * s, int * x, int * y, int * comp) { - int tga_w, tga_h, tga_comp, tga_image_type, tga_bits_per_pixel, - tga_colormap_bpp; + int tga_w, tga_h, tga_comp, tga_image_type, tga_bits_per_pixel, tga_colormap_bpp; int sz, tga_colormap_type; stbi__get8(s); // discard Offset tga_colormap_type = stbi__get8(s); // colormap type @@ -6255,8 +5985,7 @@ static int stbi__tga_info(stbi__context * s, int * x, int * y, int * comp) { stbi__rewind(s); return 0; } - stbi__skip( - s, 4); // skip index of first colormap entry and number of entries + stbi__skip(s, 4); // skip index of first colormap entry and number of entries sz = stbi__get8(s); // check bits per palette color entry if ((sz != 8) && (sz != 15) && (sz != 16) && (sz != 24) && (sz != 32)) { stbi__rewind(s); @@ -6265,8 +5994,8 @@ static int stbi__tga_info(stbi__context * s, int * x, int * y, int * comp) { stbi__skip(s, 4); // skip image x and y origin tga_colormap_bpp = sz; } else { // "normal" image w/o colormap - only RGB or grey allowed, +/- RLE - if ((tga_image_type != 2) && (tga_image_type != 3) - && (tga_image_type != 10) && (tga_image_type != 11)) { + if ((tga_image_type != 2) && (tga_image_type != 3) && (tga_image_type != 10) + && (tga_image_type != 11)) { stbi__rewind(s); return 0; // only RGB or grey allowed, +/- RLE } @@ -6294,9 +6023,8 @@ static int stbi__tga_info(stbi__context * s, int * x, int * y, int * comp) { } tga_comp = stbi__tga_get_comp(tga_colormap_bpp, 0, NULL); } else { - tga_comp = stbi__tga_get_comp( - tga_bits_per_pixel, (tga_image_type == 3) || (tga_image_type == 11), - NULL); + tga_comp = stbi__tga_get_comp(tga_bits_per_pixel, + (tga_image_type == 3) || (tga_image_type == 11), NULL); } if (!tga_comp) { stbi__rewind(s); @@ -6316,13 +6044,10 @@ static int stbi__tga_test(stbi__context * s) { if (tga_color_type > 1) goto errorEnd; // only RGB or indexed allowed sz = stbi__get8(s); // image type if (tga_color_type == 1) { // colormapped (paletted) image - if (sz != 1 && sz != 9) - goto errorEnd; // colortype 1 demands image type 1 or 9 - stbi__skip( - s, 4); // skip index of first colormap entry and number of entries + if (sz != 1 && sz != 9) goto errorEnd; // colortype 1 demands image type 1 or 9 + stbi__skip(s, 4); // skip index of first colormap entry and number of entries sz = stbi__get8(s); // check bits per palette color entry - if ((sz != 8) && (sz != 15) && (sz != 16) && (sz != 24) && (sz != 32)) - goto errorEnd; + if ((sz != 8) && (sz != 15) && (sz != 16) && (sz != 24) && (sz != 32)) goto errorEnd; stbi__skip(s, 4); // skip image x and y origin } else { // "normal" image w/o colormap if ((sz != 2) && (sz != 3) && (sz != 10) && (sz != 11)) @@ -6334,8 +6059,7 @@ static int stbi__tga_test(stbi__context * s) { sz = stbi__get8(s); // bits per pixel if ((tga_color_type == 1) && (sz != 8) && (sz != 16)) goto errorEnd; // for colormapped images, bpp is size of an index - if ((sz != 8) && (sz != 15) && (sz != 16) && (sz != 24) && (sz != 32)) - goto errorEnd; + if ((sz != 8) && (sz != 15) && (sz != 16) && (sz != 24) && (sz != 32)) goto errorEnd; res = 1; // if we got this far, everything's good and we can return 1 instead of 0 @@ -6363,8 +6087,8 @@ static void stbi__tga_read_rgb16(stbi__context * s, stbi_uc * out) { // so let's treat all 15 and 16bit TGAs as RGB with no alpha. } -static void * stbi__tga_load(stbi__context * s, int * x, int * y, int * comp, - int req_comp, stbi__result_info * ri) { +static void * stbi__tga_load(stbi__context * s, int * x, int * y, int * comp, int req_comp, + stbi__result_info * ri) { // read in the TGA header stuff int tga_offset = stbi__get8(s); int tga_indexed = stbi__get8(s); @@ -6406,11 +6130,8 @@ static void * stbi__tga_load(stbi__context * s, int * x, int * y, int * comp, tga_inverted = 1 - ((tga_inverted >> 5) & 1); // If I'm paletted, then I'll use the number of bits from the palette - if (tga_indexed) - tga_comp = stbi__tga_get_comp(tga_palette_bits, 0, &tga_rgb16); - else - tga_comp = stbi__tga_get_comp(tga_bits_per_pixel, (tga_image_type == 3), - &tga_rgb16); + if (tga_indexed) tga_comp = stbi__tga_get_comp(tga_palette_bits, 0, &tga_rgb16); + else tga_comp = stbi__tga_get_comp(tga_bits_per_pixel, (tga_image_type == 3), &tga_rgb16); if (!tga_comp) // shouldn't really happen, stbi__tga_test() should have ensured basic consistency return stbi__errpuc("bad format", "Can't find out TGA pixelformat"); @@ -6423,8 +6144,7 @@ static void * stbi__tga_load(stbi__context * s, int * x, int * y, int * comp, if (!stbi__mad3sizes_valid(tga_width, tga_height, tga_comp, 0)) return stbi__errpuc("too large", "Corrupt TGA"); - tga_data = (unsigned char *) stbi__malloc_mad3(tga_width, tga_height, - tga_comp, 0); + tga_data = (unsigned char *) stbi__malloc_mad3(tga_width, tga_height, tga_comp, 0); if (!tga_data) return stbi__errpuc("outofmem", "Out of memory"); // skip to the data's starting position (offset usually = 0) @@ -6439,8 +6159,7 @@ static void * stbi__tga_load(stbi__context * s, int * x, int * y, int * comp, } else { // do I need to load a palette? if (tga_indexed) { - if (tga_palette_len - == 0) { /* you have to have at least one entry! */ + if (tga_palette_len == 0) { /* you have to have at least one entry! */ STBI_FREE(tga_data); return stbi__errpuc("bad palette", "Corrupt TGA"); } @@ -6448,8 +6167,7 @@ static void * stbi__tga_load(stbi__context * s, int * x, int * y, int * comp, // any data to skip? (offset usually = 0) stbi__skip(s, tga_palette_start); // load the palette - tga_palette = (unsigned char *) stbi__malloc_mad2(tga_palette_len, - tga_comp, 0); + tga_palette = (unsigned char *) stbi__malloc_mad2(tga_palette_len, tga_comp, 0); if (!tga_palette) { STBI_FREE(tga_data); return stbi__errpuc("outofmem", "Out of memory"); @@ -6461,8 +6179,7 @@ static void * stbi__tga_load(stbi__context * s, int * x, int * y, int * comp, stbi__tga_read_rgb16(s, pal_entry); pal_entry += tga_comp; } - } else if (!stbi__getn(s, tga_palette, - tga_palette_len * tga_comp)) { + } else if (!stbi__getn(s, tga_palette, tga_palette_len * tga_comp)) { STBI_FREE(tga_data); STBI_FREE(tga_palette); return stbi__errpuc("bad palette", "Corrupt TGA"); @@ -6489,8 +6206,7 @@ static void * stbi__tga_load(stbi__context * s, int * x, int * y, int * comp, // load however much data we did have if (tga_indexed) { // read in index, then perform the lookup - int pal_idx = (tga_bits_per_pixel == 8) ? stbi__get8(s) - : stbi__get16le(s); + int pal_idx = (tga_bits_per_pixel == 8) ? stbi__get8(s) : stbi__get16le(s); if (pal_idx >= tga_palette_len) { // invalid index pal_idx = 0; @@ -6513,8 +6229,7 @@ static void * stbi__tga_load(stbi__context * s, int * x, int * y, int * comp, } // end of reading a pixel // copy data - for (j = 0; j < tga_comp; ++j) - tga_data[i * tga_comp + j] = raw_data[j]; + for (j = 0; j < tga_comp; ++j) tga_data[i * tga_comp + j] = raw_data[j]; // in case we're in RLE mode, keep counting down --RLE_count; @@ -6552,13 +6267,11 @@ static void * stbi__tga_load(stbi__context * s, int * x, int * y, int * comp, // convert to target component count if (req_comp && req_comp != tga_comp) - tga_data = stbi__convert_format(tga_data, tga_comp, req_comp, tga_width, - tga_height); + tga_data = stbi__convert_format(tga_data, tga_comp, req_comp, tga_width, tga_height); // the things I do to get rid of an error message, and yet keep // Microsoft's C compilers happy... [8^( - tga_palette_start = tga_palette_len = tga_palette_bits = tga_x_origin - = tga_y_origin = 0; + tga_palette_start = tga_palette_len = tga_palette_bits = tga_x_origin = tga_y_origin = 0; STBI_NOTUSED(tga_palette_start); // OK, done return tga_data; @@ -6575,8 +6288,7 @@ static int stbi__psd_test(stbi__context * s) { return r; } -static int stbi__psd_decode_rle(stbi__context * s, stbi_uc * p, - int pixelCount) { +static int stbi__psd_decode_rle(stbi__context * s, stbi_uc * p, int pixelCount) { int count, nleft, len; count = 0; @@ -6613,8 +6325,8 @@ static int stbi__psd_decode_rle(stbi__context * s, stbi_uc * p, return 1; } -static void * stbi__psd_load(stbi__context * s, int * x, int * y, int * comp, - int req_comp, stbi__result_info * ri, int bpc) { +static void * stbi__psd_load(stbi__context * s, int * x, int * y, int * comp, int req_comp, + stbi__result_info * ri, int bpc) { int pixelCount; int channelCount, compression; int channel, i; @@ -6629,8 +6341,7 @@ static void * stbi__psd_load(stbi__context * s, int * x, int * y, int * comp, // Check file type version. if (stbi__get16be(s) != 1) - return stbi__errpuc("wrong version", - "Unsupported version of PSD image"); + return stbi__errpuc("wrong version", "Unsupported version of PSD image"); // Skip 6 reserved bytes. stbi__skip(s, 6); @@ -6653,8 +6364,7 @@ static void * stbi__psd_load(stbi__context * s, int * x, int * y, int * comp, // Make sure the depth is 8 bits. bitdepth = stbi__get16be(s); if (bitdepth != 8 && bitdepth != 16) - return stbi__errpuc("unsupported bit depth", - "PSD bit depth is not 8 or 16 bit"); + return stbi__errpuc("unsupported bit depth", "PSD bit depth is not 8 or 16 bit"); // Make sure the color mode is RGB. // Valid options are: @@ -6667,8 +6377,7 @@ static void * stbi__psd_load(stbi__context * s, int * x, int * y, int * comp, // 8: Duotone // 9: Lab color if (stbi__get16be(s) != 3) - return stbi__errpuc("wrong color format", - "PSD is not in RGB color format"); + return stbi__errpuc("wrong color format", "PSD is not in RGB color format"); // Skip the Mode Data. (It's the palette for indexed color; other info for other modes.) stbi__skip(s, stbi__get32be(s)); @@ -6685,12 +6394,10 @@ static void * stbi__psd_load(stbi__context * s, int * x, int * y, int * comp, // 1: RLE compressed compression = stbi__get16be(s); if (compression > 1) - return stbi__errpuc("bad compression", - "PSD has an unknown compression format"); + return stbi__errpuc("bad compression", "PSD has an unknown compression format"); // Check size - if (!stbi__mad3sizes_valid(4, w, h, 0)) - return stbi__errpuc("too large", "Corrupt PSD"); + if (!stbi__mad3sizes_valid(4, w, h, 0)) return stbi__errpuc("too large", "Corrupt PSD"); // Create the destination image. @@ -6726,8 +6433,7 @@ static void * stbi__psd_load(stbi__context * s, int * x, int * y, int * comp, p = out + channel; if (channel >= channelCount) { // Fill this channel with default data. - for (i = 0; i < pixelCount; i++, p += 4) - *p = (channel == 3 ? 255 : 0); + for (i = 0; i < pixelCount; i++, p += 4) *p = (channel == 3 ? 255 : 0); } else { // Read the RLE data. if (!stbi__psd_decode_rle(s, p, pixelCount)) { @@ -6765,8 +6471,7 @@ static void * stbi__psd_load(stbi__context * s, int * x, int * y, int * comp, for (i = 0; i < pixelCount; i++, p += 4) *p = (stbi_uc) (stbi__get16be(s) >> 8); } else { - for (i = 0; i < pixelCount; i++, p += 4) - *p = stbi__get8(s); + for (i = 0; i < pixelCount; i++, p += 4) *p = stbi__get8(s); } } } @@ -6805,11 +6510,9 @@ static void * stbi__psd_load(stbi__context * s, int * x, int * y, int * comp, // convert to desired output format if (req_comp && req_comp != 4) { if (ri->bits_per_channel == 16) - out = (stbi_uc *) stbi__convert_format16((stbi__uint16 *) out, 4, - req_comp, w, h); + out = (stbi_uc *) stbi__convert_format16((stbi__uint16 *) out, 4, req_comp, w, h); else out = stbi__convert_format(out, 4, req_comp, w, h); - if (out == NULL) - return out; // stbi__convert_format frees input on failure + if (out == NULL) return out; // stbi__convert_format frees input on failure } if (comp) *comp = 4; @@ -6857,8 +6560,7 @@ static stbi_uc * stbi__readval(stbi__context * s, int channel, stbi_uc * dest) { for (i = 0; i < 4; ++i, mask >>= 1) { if (channel & mask) { - if (stbi__at_eof(s)) - return stbi__errpuc("bad file", "PIC file too short"); + if (stbi__at_eof(s)) return stbi__errpuc("bad file", "PIC file too short"); dest[i] = stbi__get8(s); } } @@ -6873,8 +6575,8 @@ static void stbi__copyval(int channel, stbi_uc * dest, const stbi_uc * src) { if (channel & mask) dest[i] = src[i]; } -static stbi_uc * stbi__pic_load_core(stbi__context * s, int width, int height, - int * comp, stbi_uc * result) { +static stbi_uc * stbi__pic_load_core(stbi__context * s, int width, int height, int * comp, + stbi_uc * result) { int act_comp = 0, num_packets = 0, y, chained; stbi__pic_packet packets[10]; @@ -6897,8 +6599,7 @@ static stbi_uc * stbi__pic_load_core(stbi__context * s, int width, int height, if (stbi__at_eof(s)) return stbi__errpuc("bad file", "file too short (reading packets)"); - if (packet->size != 8) - return stbi__errpuc("bad format", "packet isn't 8bpp"); + if (packet->size != 8) return stbi__errpuc("bad format", "packet isn't 8bpp"); } while (chained); *comp = (act_comp & 0x10 ? 4 : 3); // has alpha channel? @@ -6912,8 +6613,7 @@ static stbi_uc * stbi__pic_load_core(stbi__context * s, int width, int height, switch (packet->type) { default: - return stbi__errpuc("bad format", - "packet has bad compression type"); + return stbi__errpuc("bad format", "packet has bad compression type"); case 0: { //uncompressed int x; @@ -6932,8 +6632,8 @@ static stbi_uc * stbi__pic_load_core(stbi__context * s, int width, int height, count = stbi__get8(s); if (stbi__at_eof(s)) - return stbi__errpuc( - "bad file", "file too short (pure read count)"); + return stbi__errpuc("bad file", + "file too short (pure read count)"); if (count > left) count = (stbi_uc) left; @@ -6950,9 +6650,8 @@ static stbi_uc * stbi__pic_load_core(stbi__context * s, int width, int height, while (left > 0) { int count = stbi__get8(s), i; if (stbi__at_eof(s)) - return stbi__errpuc( - "bad file", - "file too short (mixed read count)"); + return stbi__errpuc("bad file", + "file too short (mixed read count)"); if (count >= 128) { // Repeated stbi_uc value[4]; @@ -6960,23 +6659,19 @@ static stbi_uc * stbi__pic_load_core(stbi__context * s, int width, int height, if (count == 128) count = stbi__get16be(s); else count -= 127; if (count > left) - return stbi__errpuc("bad file", - "scanline overrun"); + return stbi__errpuc("bad file", "scanline overrun"); - if (!stbi__readval(s, packet->channel, value)) - return 0; + if (!stbi__readval(s, packet->channel, value)) return 0; for (i = 0; i < count; ++i, dest += 4) stbi__copyval(packet->channel, dest, value); } else { // Raw ++count; if (count > left) - return stbi__errpuc("bad file", - "scanline overrun"); + return stbi__errpuc("bad file", "scanline overrun"); for (i = 0; i < count; ++i, dest += 4) - if (!stbi__readval(s, packet->channel, dest)) - return 0; + if (!stbi__readval(s, packet->channel, dest)) return 0; } left -= count; } @@ -6989,8 +6684,8 @@ static stbi_uc * stbi__pic_load_core(stbi__context * s, int width, int height, return result; } -static void * stbi__pic_load(stbi__context * s, int * px, int * py, int * comp, - int req_comp, stbi__result_info * ri) { +static void * stbi__pic_load(stbi__context * s, int * px, int * py, int * comp, int req_comp, + stbi__result_info * ri) { stbi_uc * result; int i, x, y, internal_comp; STBI_NOTUSED(ri); @@ -7007,8 +6702,7 @@ static void * stbi__pic_load(stbi__context * s, int * px, int * py, int * comp, if (x > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large", "Very large image (corrupt?)"); - if (stbi__at_eof(s)) - return stbi__errpuc("bad file", "file too short (pic header)"); + if (stbi__at_eof(s)) return stbi__errpuc("bad file", "file too short (pic header)"); if (!stbi__mad3sizes_valid(x, y, 4, 0)) return stbi__errpuc("too large", "PIC image too large to decode"); @@ -7053,8 +6747,7 @@ typedef struct { typedef struct { int w, h; stbi_uc * out; // output buffer (always 4 components) - stbi_uc * - background; // The current "background" as far as a gif is concerned + stbi_uc * background; // The current "background" as far as a gif is concerned stbi_uc * history; int flags, bgindex, ratio, transparent, eflags; stbi_uc pal[256][4]; @@ -7087,8 +6780,8 @@ static int stbi__gif_test(stbi__context * s) { return r; } -static void stbi__gif_parse_colortable(stbi__context * s, stbi_uc pal[256][4], - int num_entries, int transp) { +static void stbi__gif_parse_colortable(stbi__context * s, stbi_uc pal[256][4], int num_entries, + int transp) { int i; for (i = 0; i < num_entries; ++i) { pal[i][2] = stbi__get8(s); @@ -7098,16 +6791,14 @@ static void stbi__gif_parse_colortable(stbi__context * s, stbi_uc pal[256][4], } } -static int stbi__gif_header(stbi__context * s, stbi__gif * g, int * comp, - int is_info) { +static int stbi__gif_header(stbi__context * s, stbi__gif * g, int * comp, int is_info) { stbi_uc version; if (stbi__get8(s) != 'G' || stbi__get8(s) != 'I' || stbi__get8(s) != 'F' || stbi__get8(s) != '8') return stbi__err("not GIF", "Corrupt GIF"); version = stbi__get8(s); - if (version != '7' && version != '9') - return stbi__err("not GIF", "Corrupt GIF"); + if (version != '7' && version != '9') return stbi__err("not GIF", "Corrupt GIF"); if (stbi__get8(s) != 'a') return stbi__err("not GIF", "Corrupt GIF"); stbi__g_failure_reason = ""; @@ -7124,13 +6815,11 @@ static int stbi__gif_header(stbi__context * s, stbi__gif * g, int * comp, return stbi__err("too large", "Very large image (corrupt?)"); if (comp != 0) - *comp - = 4; // can't actually tell whether it's 3 or 4 until we parse the comments + *comp = 4; // can't actually tell whether it's 3 or 4 until we parse the comments if (is_info) return 1; - if (g->flags & 0x80) - stbi__gif_parse_colortable(s, g->pal, 2 << (g->flags & 7), -1); + if (g->flags & 0x80) stbi__gif_parse_colortable(s, g->pal, 2 << (g->flags & 7), -1); return 1; } @@ -7155,8 +6844,7 @@ static void stbi__out_gif_code(stbi__gif * g, stbi__uint16 code) { // recurse to decode the prefixes, since the linked-list is backwards, // and working backwards through an interleaved image would be nasty - if (g->codes[code].prefix >= 0) - stbi__out_gif_code(g, g->codes[code].prefix); + if (g->codes[code].prefix >= 0) stbi__out_gif_code(g, g->codes[code].prefix); if (g->cur_y >= g->max_y) return; @@ -7248,11 +6936,9 @@ static stbi_uc * stbi__process_gif_raster(stbi__context * s, stbi__gif * g) { p->prefix = (stbi__int16) oldcode; p->first = g->codes[oldcode].first; - p->suffix - = (code == avail) ? p->first : g->codes[code].first; + p->suffix = (code == avail) ? p->first : g->codes[code].first; } else if (code == avail) - return stbi__errpuc("illegal code in raster", - "Corrupt GIF"); + return stbi__errpuc("illegal code in raster", "Corrupt GIF"); stbi__out_gif_code(g, (stbi__uint16) code); @@ -7271,9 +6957,8 @@ static stbi_uc * stbi__process_gif_raster(stbi__context * s, stbi__gif * g) { // this function is designed to support animated gifs, although stb_image doesn't support it // two back is the image from two frames ago, used for a very specific disposal format -static stbi_uc * stbi__gif_load_next(stbi__context * s, stbi__gif * g, - int * comp, int req_comp, - stbi_uc * two_back) { +static stbi_uc * stbi__gif_load_next(stbi__context * s, stbi__gif * g, int * comp, + int req_comp, stbi_uc * two_back) { int dispose; int first_frame; int pi; @@ -7382,13 +7067,11 @@ static stbi_uc * stbi__gif_load_next(stbi__context * s, stbi__gif * g, if (g->lflags & 0x80) { stbi__gif_parse_colortable(s, g->lpal, 2 << (g->lflags & 7), - g->eflags & 0x01 ? g->transparent - : -1); + g->eflags & 0x01 ? g->transparent : -1); g->color_table = (stbi_uc *) g->lpal; } else if (g->flags & 0x80) { g->color_table = (stbi_uc *) g->pal; - } else - return stbi__errpuc("missing color table", "Corrupt GIF"); + } else return stbi__errpuc("missing color table", "Corrupt GIF"); o = stbi__process_gif_raster(s, g); if (!o) return NULL; @@ -7417,10 +7100,9 @@ static stbi_uc * stbi__gif_load_next(stbi__context * s, stbi__gif * g, len = stbi__get8(s); if (len == 4) { g->eflags = stbi__get8(s); - g->delay - = 10 - * stbi__get16le( - s); // delay - 1/100th of a second, saving as 1/1000ths. + g->delay = 10 + * stbi__get16le( + s); // delay - 1/100th of a second, saving as 1/1000ths. // unset old transparent if (g->transparent >= 0) { @@ -7448,8 +7130,7 @@ static stbi_uc * stbi__gif_load_next(stbi__context * s, stbi__gif * g, } case 0x3B: // gif stream termination code - return ( - stbi_uc *) s; // using '1' causes warning on some compilers + return (stbi_uc *) s; // using '1' causes warning on some compilers default: return stbi__errpuc("unknown code", "Corrupt GIF"); @@ -7457,8 +7138,7 @@ static stbi_uc * stbi__gif_load_next(stbi__context * s, stbi__gif * g, } } -static void * stbi__load_gif_main_outofmem(stbi__gif * g, stbi_uc * out, - int ** delays) { +static void * stbi__load_gif_main_outofmem(stbi__gif * g, stbi_uc * out, int ** delays) { STBI_FREE(g->out); STBI_FREE(g->history); STBI_FREE(g->background); @@ -7468,8 +7148,8 @@ static void * stbi__load_gif_main_outofmem(stbi__gif * g, stbi_uc * out, return stbi__errpuc("outofmem", "Out of memory"); } -static void * stbi__load_gif_main(stbi__context * s, int ** delays, int * x, - int * y, int * z, int * comp, int req_comp) { +static void * stbi__load_gif_main(stbi__context * s, int ** delays, int * x, int * y, int * z, + int * comp, int req_comp) { if (stbi__gif_test(s)) { int layers = 0; stbi_uc * u = 0; @@ -7499,34 +7179,28 @@ static void * stbi__load_gif_main(stbi__context * s, int ** delays, int * x, stride = g.w * g.h * 4; if (out) { - void * tmp = (stbi_uc *) STBI_REALLOC_SIZED( - out, out_size, layers * stride); - if (!tmp) - return stbi__load_gif_main_outofmem(&g, out, delays); + void * tmp + = (stbi_uc *) STBI_REALLOC_SIZED(out, out_size, layers * stride); + if (!tmp) return stbi__load_gif_main_outofmem(&g, out, delays); else { out = (stbi_uc *) tmp; out_size = layers * stride; } if (delays) { - int * new_delays = (int *) STBI_REALLOC_SIZED( - *delays, delays_size, sizeof(int) * layers); - if (!new_delays) - return stbi__load_gif_main_outofmem(&g, out, - delays); + int * new_delays = (int *) STBI_REALLOC_SIZED(*delays, delays_size, + sizeof(int) * layers); + if (!new_delays) return stbi__load_gif_main_outofmem(&g, out, delays); *delays = new_delays; delays_size = layers * sizeof(int); } } else { out = (stbi_uc *) stbi__malloc(layers * stride); - if (!out) - return stbi__load_gif_main_outofmem(&g, out, delays); + if (!out) return stbi__load_gif_main_outofmem(&g, out, delays); out_size = layers * stride; if (delays) { *delays = (int *) stbi__malloc(layers * sizeof(int)); - if (!*delays) - return stbi__load_gif_main_outofmem(&g, out, - delays); + if (!*delays) return stbi__load_gif_main_outofmem(&g, out, delays); delays_size = layers * sizeof(int); } } @@ -7557,8 +7231,8 @@ static void * stbi__load_gif_main(stbi__context * s, int ** delays, int * x, } } -static void * stbi__gif_load(stbi__context * s, int * x, int * y, int * comp, - int req_comp, stbi__result_info * ri) { +static void * stbi__gif_load(stbi__context * s, int * x, int * y, int * comp, int req_comp, + stbi__result_info * ri) { stbi_uc * u = 0; stbi__gif g; memset(&g, 0, sizeof(g)); @@ -7572,8 +7246,7 @@ static void * stbi__gif_load(stbi__context * s, int * x, int * y, int * comp, // moved conversion to after successful load so that the same // can be done for multiple frames. - if (req_comp && req_comp != 4) - u = stbi__convert_format(u, 4, req_comp, g.w, g.h); + if (req_comp && req_comp != 4) u = stbi__convert_format(u, 4, req_comp, g.w, g.h); } else if (g.out) { // if there was an error and we allocated an image buffer, free it! STBI_FREE(g.out); @@ -7639,8 +7312,7 @@ static void stbi__hdr_convert(float * output, stbi_uc * input, int req_comp) { float f1; // Exponent f1 = (float) ldexp(1.0f, input[3] - (int) (128 + 8)); - if (req_comp <= 2) - output[0] = (input[0] + input[1] + input[2]) * f1 / 3; + if (req_comp <= 2) output[0] = (input[0] + input[1] + input[2]) * f1 / 3; else { output[0] = input[0] * f1; output[1] = input[1] * f1; @@ -7664,8 +7336,8 @@ static void stbi__hdr_convert(float * output, stbi_uc * input, int req_comp) { } } -static float * stbi__hdr_load(stbi__context * s, int * x, int * y, int * comp, - int req_comp, stbi__result_info * ri) { +static float * stbi__hdr_load(stbi__context * s, int * x, int * y, int * comp, int req_comp, + stbi__result_info * ri) { char buffer[STBI__HDR_BUFLEN]; char * token; int valid = 0; @@ -7680,8 +7352,7 @@ static float * stbi__hdr_load(stbi__context * s, int * x, int * y, int * comp, // Check identifier headerToken = stbi__hdr_gettoken(s, buffer); - if (strcmp(headerToken, "#?RADIANCE") != 0 - && strcmp(headerToken, "#?RGBE") != 0) + if (strcmp(headerToken, "#?RADIANCE") != 0 && strcmp(headerToken, "#?RGBE") != 0) return stbi__errpf("not HDR", "Corrupt HDR image"); // Parse header @@ -7691,8 +7362,7 @@ static float * stbi__hdr_load(stbi__context * s, int * x, int * y, int * comp, if (strcmp(token, "FORMAT=32-bit_rle_rgbe") == 0) valid = 1; } - if (!valid) - return stbi__errpf("unsupported format", "Unsupported HDR format"); + if (!valid) return stbi__errpf("unsupported format", "Unsupported HDR format"); // Parse width and height // can't use sscanf() if we're not using stdio! @@ -7722,8 +7392,7 @@ static float * stbi__hdr_load(stbi__context * s, int * x, int * y, int * comp, return stbi__errpf("too large", "HDR image is too large"); // Read data - hdr_data = (float *) stbi__malloc_mad4(width, height, req_comp, - sizeof(float), 0); + hdr_data = (float *) stbi__malloc_mad4(width, height, req_comp, sizeof(float), 0); if (!hdr_data) return stbi__errpf("outofmem", "Out of memory"); // Load image data @@ -7735,9 +7404,8 @@ static float * stbi__hdr_load(stbi__context * s, int * x, int * y, int * comp, stbi_uc rgbe[4]; main_decode_loop: stbi__getn(s, rgbe, 4); - stbi__hdr_convert(hdr_data + j * width * req_comp - + i * req_comp, - rgbe, req_comp); + stbi__hdr_convert(hdr_data + j * width * req_comp + i * req_comp, rgbe, + req_comp); } } } else { @@ -7767,8 +7435,7 @@ static float * stbi__hdr_load(stbi__context * s, int * x, int * y, int * comp, if (len != width) { STBI_FREE(hdr_data); STBI_FREE(scanline); - return stbi__errpf("invalid decoded scanline length", - "corrupt HDR"); + return stbi__errpf("invalid decoded scanline length", "corrupt HDR"); } if (scanline == NULL) { scanline = (stbi_uc *) stbi__malloc_mad2(width, 4, 0); @@ -7790,27 +7457,23 @@ static float * stbi__hdr_load(stbi__context * s, int * x, int * y, int * comp, if ((count == 0) || (count > nleft)) { STBI_FREE(hdr_data); STBI_FREE(scanline); - return stbi__errpf("corrupt", - "bad RLE data in HDR"); + return stbi__errpf("corrupt", "bad RLE data in HDR"); } - for (z = 0; z < count; ++z) - scanline[i++ * 4 + k] = value; + for (z = 0; z < count; ++z) scanline[i++ * 4 + k] = value; } else { // Dump if ((count == 0) || (count > nleft)) { STBI_FREE(hdr_data); STBI_FREE(scanline); - return stbi__errpf("corrupt", - "bad RLE data in HDR"); + return stbi__errpf("corrupt", "bad RLE data in HDR"); } - for (z = 0; z < count; ++z) - scanline[i++ * 4 + k] = stbi__get8(s); + for (z = 0; z < count; ++z) scanline[i++ * 4 + k] = stbi__get8(s); } } } for (i = 0; i < width; ++i) - stbi__hdr_convert(hdr_data + (j * width + i) * req_comp, - scanline + i * 4, req_comp); + stbi__hdr_convert(hdr_data + (j * width + i) * req_comp, scanline + i * 4, + req_comp); } if (scanline) STBI_FREE(scanline); } @@ -8026,13 +7689,13 @@ static int stbi__pnm_test(stbi__context * s) { return 1; } -static void * stbi__pnm_load(stbi__context * s, int * x, int * y, int * comp, - int req_comp, stbi__result_info * ri) { +static void * stbi__pnm_load(stbi__context * s, int * x, int * y, int * comp, int req_comp, + stbi__result_info * ri) { stbi_uc * out; STBI_NOTUSED(ri); - ri->bits_per_channel = stbi__pnm_info(s, (int *) &s->img_x, - (int *) &s->img_y, (int *) &s->img_n); + ri->bits_per_channel + = stbi__pnm_info(s, (int *) &s->img_x, (int *) &s->img_y, (int *) &s->img_n); if (ri->bits_per_channel == 0) return 0; if (s->img_y > STBI_MAX_DIMENSIONS) @@ -8044,48 +7707,40 @@ static void * stbi__pnm_load(stbi__context * s, int * x, int * y, int * comp, *y = s->img_y; if (comp) *comp = s->img_n; - if (!stbi__mad4sizes_valid(s->img_n, s->img_x, s->img_y, - ri->bits_per_channel / 8, 0)) + if (!stbi__mad4sizes_valid(s->img_n, s->img_x, s->img_y, ri->bits_per_channel / 8, 0)) return stbi__errpuc("too large", "PNM too large"); - out = (stbi_uc *) stbi__malloc_mad4(s->img_n, s->img_x, s->img_y, - ri->bits_per_channel / 8, 0); + out = (stbi_uc *) stbi__malloc_mad4(s->img_n, s->img_x, s->img_y, ri->bits_per_channel / 8, + 0); if (!out) return stbi__errpuc("outofmem", "Out of memory"); - if (!stbi__getn(s, out, - s->img_n * s->img_x * s->img_y - * (ri->bits_per_channel / 8))) { + if (!stbi__getn(s, out, s->img_n * s->img_x * s->img_y * (ri->bits_per_channel / 8))) { STBI_FREE(out); return stbi__errpuc("bad PNM", "PNM file truncated"); } if (req_comp && req_comp != s->img_n) { if (ri->bits_per_channel == 16) { - out = (stbi_uc *) stbi__convert_format16( - (stbi__uint16 *) out, s->img_n, req_comp, s->img_x, s->img_y); + out = (stbi_uc *) stbi__convert_format16((stbi__uint16 *) out, s->img_n, req_comp, + s->img_x, s->img_y); } else { - out = stbi__convert_format(out, s->img_n, req_comp, s->img_x, - s->img_y); + out = stbi__convert_format(out, s->img_n, req_comp, s->img_x, s->img_y); } - if (out == NULL) - return out; // stbi__convert_format frees input on failure + if (out == NULL) return out; // stbi__convert_format frees input on failure } return out; } static int stbi__pnm_isspace(char c) { - return c == ' ' || c == '\t' || c == '\n' || c == '\v' || c == '\f' - || c == '\r'; + return c == ' ' || c == '\t' || c == '\n' || c == '\v' || c == '\f' || c == '\r'; } static void stbi__pnm_skip_whitespace(stbi__context * s, char * c) { for (;;) { - while (!stbi__at_eof(s) && stbi__pnm_isspace(*c)) - *c = (char) stbi__get8(s); + while (!stbi__at_eof(s) && stbi__pnm_isspace(*c)) *c = (char) stbi__get8(s); if (stbi__at_eof(s) || *c != '#') break; - while (!stbi__at_eof(s) && *c != '\n' && *c != '\r') - *c = (char) stbi__get8(s); + while (!stbi__at_eof(s) && *c != '\n' && *c != '\r') *c = (char) stbi__get8(s); } } @@ -8098,9 +7753,8 @@ static int stbi__pnm_getinteger(stbi__context * s, char * c) { value = value * 10 + (*c - '0'); *c = (char) stbi__get8(s); if ((value > 214748364) || (value == 214748364 && *c > '7')) - return stbi__err( - "integer parse overflow", - "Parsing an integer in the PPM header overflowed a 32-bit int"); + return stbi__err("integer parse overflow", + "Parsing an integer in the PPM header overflowed a 32-bit int"); } return value; @@ -8124,22 +7778,19 @@ static int stbi__pnm_info(stbi__context * s, int * x, int * y, int * comp) { return 0; } - *comp = (t == '6') ? 3 - : 1; // '5' is 1-component .pgm; '6' is 3-component .ppm + *comp = (t == '6') ? 3 : 1; // '5' is 1-component .pgm; '6' is 3-component .ppm c = (char) stbi__get8(s); stbi__pnm_skip_whitespace(s, &c); *x = stbi__pnm_getinteger(s, &c); // read width if (*x == 0) - return stbi__err("invalid width", - "PPM image header had zero or overflowing width"); + return stbi__err("invalid width", "PPM image header had zero or overflowing width"); stbi__pnm_skip_whitespace(s, &c); *y = stbi__pnm_getinteger(s, &c); // read height if (*y == 0) - return stbi__err("invalid width", - "PPM image header had zero or overflowing width"); + return stbi__err("invalid width", "PPM image header had zero or overflowing width"); stbi__pnm_skip_whitespace(s, &c); maxv = stbi__pnm_getinteger(s, &c); // read max value @@ -8193,8 +7844,7 @@ static int stbi__info_main(stbi__context * s, int * x, int * y, int * comp) { #ifndef STBI_NO_TGA if (stbi__tga_info(s, x, y, comp)) return 1; #endif - return stbi__err("unknown image type", - "Image not of any known type, or corrupt"); + return stbi__err("unknown image type", "Image not of any known type, or corrupt"); } static int stbi__is_16_main(stbi__context * s) { @@ -8252,15 +7902,15 @@ STBIDEF int stbi_is_16_bit_from_file(FILE * f) { } #endif // !STBI_NO_STDIO -STBIDEF int stbi_info_from_memory(stbi_uc const * buffer, int len, int * x, - int * y, int * comp) { +STBIDEF int stbi_info_from_memory(stbi_uc const * buffer, int len, int * x, int * y, + int * comp) { stbi__context s; stbi__start_mem(&s, buffer, len); return stbi__info_main(&s, x, y, comp); } -STBIDEF int stbi_info_from_callbacks(stbi_io_callbacks const * c, void * user, - int * x, int * y, int * comp) { +STBIDEF int stbi_info_from_callbacks(stbi_io_callbacks const * c, void * user, int * x, + int * y, int * comp) { stbi__context s; stbi__start_callbacks(&s, (stbi_io_callbacks *) c, user); return stbi__info_main(&s, x, y, comp); @@ -8272,8 +7922,7 @@ STBIDEF int stbi_is_16_bit_from_memory(stbi_uc const * buffer, int len) { return stbi__is_16_main(&s); } -STBIDEF int stbi_is_16_bit_from_callbacks(stbi_io_callbacks const * c, - void * user) { +STBIDEF int stbi_is_16_bit_from_callbacks(stbi_io_callbacks const * c, void * user) { stbi__context s; stbi__start_callbacks(&s, (stbi_io_callbacks *) c, user); return stbi__is_16_main(&s); diff --git a/mwe/resource-manager/tiledMap.cpp b/mwe/resource-manager/tiledMap.cpp index 836929c..85fc30e 100644 --- a/mwe/resource-manager/tiledMap.cpp +++ b/mwe/resource-manager/tiledMap.cpp @@ -49,8 +49,7 @@ void TiledMap::SetMapTextures() { for (const auto & ts : tileSets) { m_MapTextures.emplace_back(new TextureMap); - if (!m_MapTextures.back()->loadFromFile(ts.getImagePath(), - m_Renderer)) { + if (!m_MapTextures.back()->loadFromFile(ts.getImagePath(), m_Renderer)) { std::cerr << "Failed opening " << ts.getImagePath() << "\n"; } } @@ -63,8 +62,7 @@ void TiledMap::SetMapLayers() { for (auto i = 0u; i < mapLayers.size(); ++i) { if (mapLayers[i]->getType() == tmx::Layer::Type::Tile) { m_RenderLayers.emplace_back(new MapLayer); - m_RenderLayers.back()->create(this->m_TmxMap, i, - this->m_MapTextures); + m_RenderLayers.back()->create(this->m_TmxMap, i, this->m_MapTextures); } } } diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index e4922df..445a8b2 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -38,6 +38,5 @@ install( target_link_libraries(test_main PRIVATE gtest - PRIVATE gtest_main PUBLIC crepe ) diff --git a/src/crepe/Asset.cpp b/src/crepe/Asset.cpp index 8a2a11c..9c41ecb 100644 --- a/src/crepe/Asset.cpp +++ b/src/crepe/Asset.cpp @@ -3,14 +3,14 @@ #include "Asset.h" using namespace crepe; +using namespace std; -Asset::Asset(const std::string & src) { - // FIXME: restore this - // this->src = std::filesystem::canonical(src); - this->src = src; +// FIXME: restore this +// src(std::filesystem::canonical(src)) +Asset::Asset(const std::string & src) : src(src) { this->file = std::ifstream(this->src, std::ios::in | std::ios::binary); } -const std::istream & Asset::read() { return this->file; } +istream & Asset::get_stream() { return this->file; } -const char * Asset::canonical() { return this->src.c_str(); } +const string & Asset::get_canonical() const { return this->src; } diff --git a/src/crepe/Asset.h b/src/crepe/Asset.h index 0cb5834..9051c5e 100644 --- a/src/crepe/Asset.h +++ b/src/crepe/Asset.h @@ -9,8 +9,8 @@ namespace crepe { /** * \brief Asset location helper * - * This class is used to locate and canonicalize paths to game asset files, and - * should *always* be used when retrieving files from disk. + * This class is used to locate and canonicalize paths to game asset files, and should *always* + * be used when retrieving files from disk. */ class Asset { public: @@ -20,13 +20,21 @@ public: Asset(const std::string & src); public: - //! Get an input stream to the contents of this resource - const std::istream & read(); - //! Get the canonical path to this resource - const char * canonical(); + /** + * \brief Get an input stream to the contents of this asset + * \return Input stream with file contents + */ + std::istream & get_stream(); + /** + * \brief Get the canonical path to this asset + * \return Canonical path to this asset + */ + const std::string & get_canonical() const; private: - std::string src; + //! Canonical path to asset + const std::string src; + //! File handle (stream) std::ifstream file; }; diff --git a/src/crepe/CMakeLists.txt b/src/crepe/CMakeLists.txt index fc95bd3..3b05742 100644 --- a/src/crepe/CMakeLists.txt +++ b/src/crepe/CMakeLists.txt @@ -4,7 +4,6 @@ target_sources(crepe PUBLIC ComponentManager.cpp Component.cpp Collider.cpp - Exception.cpp ) target_sources(crepe PUBLIC FILE_SET HEADERS FILES @@ -15,7 +14,6 @@ target_sources(crepe PUBLIC FILE_SET HEADERS FILES Collider.h ValueBroker.h ValueBroker.hpp - Exception.h ) add_subdirectory(api) diff --git a/src/crepe/Component.cpp b/src/crepe/Component.cpp index 73c2d07..acfd35c 100644 --- a/src/crepe/Component.cpp +++ b/src/crepe/Component.cpp @@ -1,5 +1,4 @@ #include "Component.h" -#include "types.h" using namespace crepe; diff --git a/src/crepe/Component.h b/src/crepe/Component.h index 0fe60b2..5279fb3 100644 --- a/src/crepe/Component.h +++ b/src/crepe/Component.h @@ -2,8 +2,6 @@ #include "types.h" -#include <cstdint> - namespace crepe { class ComponentManager; @@ -11,36 +9,37 @@ class ComponentManager; /** * \brief Base class for all components * - * This class is the base class for all components. It provides a common - * interface for all components. + * This class is the base class for all components. It provides a common interface for all + * components. */ class Component { +public: + //! Whether the component is active + bool active = true; + //! The id of the GameObject this component belongs to + const game_object_id_t game_object_id; + protected: - //! Only the ComponentManager can create components - friend class crepe::ComponentManager; /** * \param id The id of the GameObject this component belongs to */ Component(game_object_id_t id); + //! Only the ComponentManager can create components + friend class ComponentManager; public: virtual ~Component() = default; + +public: /** * \brief Get the maximum number of instances for this component * - * This method returns -1 by default, which means that there is no limit - * for the number of instances. Concrete components can override this method - * to set a limit. + * This method returns -1 by default, which means that there is no limit for the number of + * instances. Concrete components can override this method to set a limit. * * \return The maximum number of instances for this component */ virtual int get_instances_max() const { return -1; } - -public: - //! The id of the GameObject this component belongs to - const game_object_id_t game_object_id; - //! Whether the component is active - bool active = true; }; } // namespace crepe diff --git a/src/crepe/ComponentManager.cpp b/src/crepe/ComponentManager.cpp index 85149c8..e310577 100644 --- a/src/crepe/ComponentManager.cpp +++ b/src/crepe/ComponentManager.cpp @@ -1,13 +1,13 @@ -#include "util/log.h" +#include "api/GameObject.h" +#include "util/Log.h" #include "ComponentManager.h" using namespace crepe; +using namespace std; -ComponentManager & ComponentManager::get_instance() { - static ComponentManager instance; - return instance; -} +ComponentManager::ComponentManager() { dbg_trace(); } +ComponentManager::~ComponentManager() { dbg_trace(); } void ComponentManager::delete_all_components_of_id(game_object_id_t id) { // Loop through all the types (in the unordered_map<>) @@ -21,10 +21,14 @@ void ComponentManager::delete_all_components_of_id(game_object_id_t id) { } void ComponentManager::delete_all_components() { - // Clear the whole unordered_map<> this->components.clear(); + this->next_id = 0; } -ComponentManager::ComponentManager() { dbg_trace(); } - -ComponentManager::~ComponentManager() { dbg_trace(); } +GameObject ComponentManager::new_object(const string & name, const string & tag, + const Vector2 & position, double rotation, + double scale) { + GameObject object{*this, this->next_id, name, tag, position, rotation, scale}; + this->next_id++; + return object; +} diff --git a/src/crepe/ComponentManager.h b/src/crepe/ComponentManager.h index c8c196c..2107453 100644 --- a/src/crepe/ComponentManager.h +++ b/src/crepe/ComponentManager.h @@ -1,40 +1,63 @@ #pragma once -#include <cstdint> #include <memory> #include <typeindex> #include <unordered_map> #include <vector> +#include "api/Vector2.h" + #include "Component.h" namespace crepe { +class GameObject; + /** * \brief Manages all components * - * This class manages all components. It provides methods to add, delete and get - * components. + * This class manages all components. It provides methods to add, delete and get components. */ class ComponentManager { + // TODO: This relation should be removed! I (loek) believe that the scene manager should + // create/destroy components because the GameObject's are stored in concrete Scene classes, + // which will in turn call GameObject's destructor, which will in turn call + // ComponentManager::delete_components_by_id or something. This is a pretty major change, so + // here is a comment and temporary fix instead :tada: + friend class SceneManager; + public: + ComponentManager(); // dbg_trace + ~ComponentManager(); // dbg_trace + /** - * \brief Get the instance of the ComponentManager - * - * \return The instance of the ComponentManager + * \brief Create a new game object using the component manager + * + * \param name Metadata::name (required) + * \param tag Metadata::tag (optional, empty by default) + * \param position Transform::position (optional, origin by default) + * \param rotation Transform::rotation (optional, 0 by default) + * \param scale Transform::scale (optional, 1 by default) + * + * \returns GameObject interface + * + * \note This method automatically assigns a new entity ID */ - static ComponentManager & get_instance(); - ComponentManager(const ComponentManager &) = delete; - ComponentManager(ComponentManager &&) = delete; - ComponentManager & operator=(const ComponentManager &) = delete; - ComponentManager & operator=(ComponentManager &&) = delete; - ~ComponentManager(); + GameObject new_object(const std::string & name, const std::string & tag = "", + const Vector2 & position = {0, 0}, double rotation = 0, + double scale = 1); +protected: + /** + * GameObject is used as an interface to add/remove components, and the game programmer is + * supposed to use it instead of interfacing with the component manager directly. + */ + friend class GameObject; /** * \brief Add a component to the ComponentManager * - * This method adds a component to the ComponentManager. The component is - * created with the given arguments and added to the ComponentManager. + * This method adds a component to the ComponentManager. The component is created with the + * given arguments and added to the ComponentManager. * * \tparam T The type of the component * \tparam Args The types of the arguments @@ -77,6 +100,8 @@ public: * This method deletes all components. */ void delete_all_components(); + +public: /** * \brief Get all components of a specific type and id * @@ -87,8 +112,7 @@ public: * \return A vector of all components of the specific type and id */ template <typename T> - std::vector<std::reference_wrapper<T>> - get_components_by_id(game_object_id_t id) const; + std::vector<std::reference_wrapper<T>> get_components_by_id(game_object_id_t id) const; /** * \brief Get all components of a specific type * @@ -101,23 +125,21 @@ public: std::vector<std::reference_wrapper<T>> get_components_by_type() const; private: - ComponentManager(); - -private: /** * \brief The components * - * This unordered_map stores all components. The key is the type of the - * component and the value is a vector of vectors of unique pointers to the - * components. - * Every component type has its own vector of vectors of unique pointers to - * the components. The first vector is for the ids of the GameObjects and the - * second vector is for the components (because a GameObject might have multiple - * components). + * This unordered_map stores all components. The key is the type of the component and the + * value is a vector of vectors of unique pointers to the components. + * + * Every component type has its own vector of vectors of unique pointers to the components. + * The first vector is for the ids of the GameObjects and the second vector is for the + * components (because a GameObject might have multiple components). */ - std::unordered_map<std::type_index, - std::vector<std::vector<std::unique_ptr<Component>>>> + std::unordered_map<std::type_index, std::vector<std::vector<std::unique_ptr<Component>>>> components; + + //! ID of next GameObject allocated by \c ComponentManager::new_object + game_object_id_t next_id = 0; }; } // namespace crepe diff --git a/src/crepe/ComponentManager.hpp b/src/crepe/ComponentManager.hpp index 98efb49..be99cac 100644 --- a/src/crepe/ComponentManager.hpp +++ b/src/crepe/ComponentManager.hpp @@ -40,7 +40,6 @@ T & ComponentManager::add_component(game_object_id_t id, Args &&... args) { // Check if the vector size is not greater than get_instances_max int max_instances = instance->get_instances_max(); if (max_instances != -1 && components[type][id].size() >= max_instances) { - // TODO: Exception throw std::runtime_error( "Exceeded maximum number of instances for this component type"); } @@ -61,8 +60,7 @@ void ComponentManager::delete_components_by_id(game_object_id_t id) { // Find the type (in the unordered_map<>) if (this->components.find(type) != this->components.end()) { // Get the correct vector<> - vector<vector<unique_ptr<Component>>> & component_array - = this->components[type]; + vector<vector<unique_ptr<Component>>> & component_array = this->components[type]; // Make sure that the id (that we are looking for) is within the boundaries of the vector<> if (id < component_array.size()) { @@ -93,12 +91,10 @@ ComponentManager::get_components_by_id(game_object_id_t id) const { // Create an empty vector<> vector<reference_wrapper<T>> component_vector; - if (this->components.find(type) == this->components.end()) - return component_vector; + if (this->components.find(type) == this->components.end()) return component_vector; // Get the correct vector<> - const vector<vector<unique_ptr<Component>>> & component_array - = this->components.at(type); + const vector<vector<unique_ptr<Component>>> & component_array = this->components.at(type); // Make sure that the id (that we are looking for) is within the boundaries of the vector<> if (id >= component_array.size()) return component_vector; @@ -118,8 +114,7 @@ ComponentManager::get_components_by_id(game_object_id_t id) const { } template <typename T> -std::vector<std::reference_wrapper<T>> -ComponentManager::get_components_by_type() const { +std::vector<std::reference_wrapper<T>> ComponentManager::get_components_by_type() const { using namespace std; // Determine the type of T (this is used as the key of the unordered_map<>) @@ -129,12 +124,10 @@ ComponentManager::get_components_by_type() const { vector<reference_wrapper<T>> component_vector; // Find the type (in the unordered_map<>) - if (this->components.find(type) == this->components.end()) - return component_vector; + if (this->components.find(type) == this->components.end()) return component_vector; // Get the correct vector<> - const vector<vector<unique_ptr<Component>>> & component_array - = this->components.at(type); + const vector<vector<unique_ptr<Component>>> & component_array = this->components.at(type); // Loop through the whole vector<> for (const vector<unique_ptr<Component>> & component : component_array) { diff --git a/src/crepe/Exception.cpp b/src/crepe/Exception.cpp deleted file mode 100644 index dab8f2e..0000000 --- a/src/crepe/Exception.cpp +++ /dev/null @@ -1,16 +0,0 @@ -#include <cstdarg> - -#include "Exception.h" -#include "util/fmt.h" - -using namespace std; -using namespace crepe; - -const char * Exception::what() { return error.c_str(); } - -Exception::Exception(const char * fmt, ...) { - va_list args; - va_start(args, fmt); - this->error = va_stringf(args, fmt); - va_end(args); -} diff --git a/src/crepe/Exception.h b/src/crepe/Exception.h deleted file mode 100644 index 6473043..0000000 --- a/src/crepe/Exception.h +++ /dev/null @@ -1,22 +0,0 @@ -#pragma once - -#include <exception> -#include <string> - -namespace crepe { - -//! Exception class with printf-style constructor -class Exception : public std::exception { -public: - //! printf - Exception(const char * fmt, ...); - //! Get formatted error message - const char * what(); - -protected: - Exception() = default; - //! Formatted error message - std::string error; -}; - -} // namespace crepe diff --git a/src/crepe/Particle.cpp b/src/crepe/Particle.cpp index 582edf4..1068cbf 100644 --- a/src/crepe/Particle.cpp +++ b/src/crepe/Particle.cpp @@ -2,8 +2,8 @@ using namespace crepe; -void Particle::reset(uint32_t lifespan, const Vector2 & position, - const Vector2 & velocity, double angle) { +void Particle::reset(uint32_t lifespan, const Vector2 & position, const Vector2 & velocity, + double angle) { // Initialize the particle state this->time_in_life = 0; this->lifespan = lifespan; diff --git a/src/crepe/Particle.h b/src/crepe/Particle.h index 3eaebc3..19859fe 100644 --- a/src/crepe/Particle.h +++ b/src/crepe/Particle.h @@ -9,9 +9,9 @@ namespace crepe { /** * \brief Represents a particle in the particle emitter. * - * This class stores information about a single particle, including its position, - * velocity, lifespan, and other properties. Particles can be updated over time - * to simulate movement and can also be reset or stopped. + * This class stores information about a single particle, including its position, velocity, + * lifespan, and other properties. Particles can be updated over time to simulate movement and + * can also be reset or stopped. */ class Particle { // TODO: add friend particleSsytem and rendersystem. Unit test will fail. @@ -35,20 +35,20 @@ public: /** * \brief Resets the particle with new properties. * - * This method initializes the particle with a specific lifespan, position, - * velocity, and angle, marking it as active and resetting its life counter. + * This method initializes the particle with a specific lifespan, position, velocity, and + * angle, marking it as active and resetting its life counter. * * \param lifespan The lifespan of the particle in amount of updates. * \param position The starting position of the particle. * \param velocity The initial velocity of the particle. * \param angle The angle of the particle's trajectory or orientation. */ - void reset(uint32_t lifespan, const Vector2 & position, - const Vector2 & velocity, double angle); + void reset(uint32_t lifespan, const Vector2 & position, const Vector2 & velocity, + double angle); /** * \brief Updates the particle's state. * - * Advances the particle's position based on its velocity and applies accumulated forces. + * Advances the particle's position based on its velocity and applies accumulated forces. * Deactivates the particle if its lifespan has expired. */ void update(); diff --git a/src/crepe/ValueBroker.h b/src/crepe/ValueBroker.h index d844d6a..673b660 100644 --- a/src/crepe/ValueBroker.h +++ b/src/crepe/ValueBroker.h @@ -7,10 +7,9 @@ namespace crepe { /** * \brief Give reference to value through custom set/get functions * - * This class can be used to abstract direct access to any arbitrary value - * through a custom get and set function passed to its constructor. Consumers - * of this type may want to wrap it in a \c Proxy so it behaves like a regular - * variable. + * This class can be used to abstract direct access to any arbitrary value through a custom get + * and set function passed to its constructor. Consumers of this type may want to wrap it in a + * \c Proxy so it behaves like a regular variable. * * \tparam T Type of the underlying variable */ diff --git a/src/crepe/api/Animator.cpp b/src/crepe/api/Animator.cpp index 58fee2a..464b0fd 100644 --- a/src/crepe/api/Animator.cpp +++ b/src/crepe/api/Animator.cpp @@ -1,7 +1,5 @@ -#include <cstdint> - -#include "util/log.h" +#include "util/Log.h" #include "Animator.h" #include "Component.h" @@ -9,7 +7,7 @@ using namespace crepe; -Animator::Animator(uint32_t id, Sprite & ss, int row, int col, int col_animator) +Animator::Animator(game_object_id_t id, Sprite & ss, int row, int col, int col_animator) : Component(id), spritesheet(ss), row(row), diff --git a/src/crepe/api/Animator.h b/src/crepe/api/Animator.h index def0240..53f4b91 100644 --- a/src/crepe/api/Animator.h +++ b/src/crepe/api/Animator.h @@ -1,20 +1,19 @@ #pragma once -#include <cstdint> - #include "Component.h" #include "Sprite.h" namespace crepe { + class AnimatorSystem; class SDLContext; /** - * \brief The Animator component is used to animate sprites by managing the movement - * and frame changes within a sprite sheet. + * \brief The Animator component is used to animate sprites by managing the movement and frame + * changes within a sprite sheet. * - * This component allows for controlling sprite animation through rows and columns of a sprite sheet. - * It can be used to play animations, loop them, or stop them. + * This component allows for controlling sprite animation through rows and columns of a sprite + * sheet. It can be used to play animations, loop them, or stop them. */ class Animator : public Component { @@ -28,15 +27,17 @@ public: * \brief Constructs an Animator object that will control animations for a sprite sheet. * * \param id The unique identifier for the component, typically assigned automatically. - * \param spritesheet A reference to the Sprite object which holds the sprite sheet for animation. + * \param spritesheet A reference to the Sprite object which holds the sprite sheet for + * animation. * \param row The maximum number of rows in the sprite sheet. * \param col The maximum number of columns in the sprite sheet. - * \param col__animate The specific col index of the sprite sheet to animate. This allows selecting which col to animate from multiple col in the sheet. + * \param col_animate The specific col index of the sprite sheet to animate. This allows + * selecting which col to animate from multiple col in the sheet. * - * This constructor sets up the Animator with the given parameters, and initializes the animation system. + * This constructor sets up the Animator with the given parameters, and initializes the + * animation system. */ - Animator(uint32_t id, Sprite & spritesheet, int row, int col, - int col_animate); + Animator(uint32_t id, Sprite & spritesheet, int row, int col, int col_animate); ~Animator(); // dbg_trace Animator(const Animator &) = delete; diff --git a/src/crepe/api/AssetManager.cpp b/src/crepe/api/AssetManager.cpp index b891760..3925758 100644 --- a/src/crepe/api/AssetManager.cpp +++ b/src/crepe/api/AssetManager.cpp @@ -1,4 +1,4 @@ -#include "util/log.h" +#include "util/Log.h" #include "AssetManager.h" diff --git a/src/crepe/api/AssetManager.h b/src/crepe/api/AssetManager.h index 86a9902..fee6780 100644 --- a/src/crepe/api/AssetManager.h +++ b/src/crepe/api/AssetManager.h @@ -8,13 +8,12 @@ namespace crepe { /** - * \brief The AssetManager is responsible for storing and managing assets over - * multiple scenes. + * \brief The AssetManager is responsible for storing and managing assets over multiple scenes. * - * The AssetManager ensures that assets are loaded once and can be accessed - * across different scenes. It caches assets to avoid reloading them every time - * a scene is loaded. Assets are retained in memory until the AssetManager is - * destroyed, at which point the cached assets are cleared. + * The AssetManager ensures that assets are loaded once and can be accessed across different + * scenes. It caches assets to avoid reloading them every time a scene is loaded. Assets are + * retained in memory until the AssetManager is destroyed, at which point the cached assets are + * cleared. */ class AssetManager { @@ -44,20 +43,18 @@ public: * \brief Caches an asset by loading it from the given file path. * * \param file_path The path to the asset file to load. - * \param reload If true, the asset will be reloaded from the file, even if - * it is already cached. + * \param reload If true, the asset will be reloaded from the file, even if it is already + * cached. * \tparam T The type of asset to cache (e.g., texture, sound, etc.). * * \return A shared pointer to the cached asset. * - * This template function caches the asset at the given file path. If the - * asset is already cached and `reload` is false, the existing cached version - * will be returned. Otherwise, the asset will be reloaded and added to the - * cache. + * This template function caches the asset at the given file path. If the asset is already + * cached and `reload` is false, the existing cached version will be returned. Otherwise, the + * asset will be reloaded and added to the cache. */ template <typename T> - std::shared_ptr<T> cache(const std::string & file_path, - bool reload = false); + std::shared_ptr<T> cache(const std::string & file_path, bool reload = false); }; } // namespace crepe diff --git a/src/crepe/api/AssetManager.hpp b/src/crepe/api/AssetManager.hpp index 977b4e1..1c0e978 100644 --- a/src/crepe/api/AssetManager.hpp +++ b/src/crepe/api/AssetManager.hpp @@ -5,16 +5,14 @@ namespace crepe { template <typename asset> -std::shared_ptr<asset> AssetManager::cache(const std::string & file_path, - bool reload) { +std::shared_ptr<asset> AssetManager::cache(const std::string & file_path, bool reload) { auto it = asset_cache.find(file_path); if (!reload && it != asset_cache.end()) { return std::any_cast<std::shared_ptr<asset>>(it->second); } - std::shared_ptr<asset> new_asset - = std::make_shared<asset>(file_path.c_str()); + std::shared_ptr<asset> new_asset = std::make_shared<asset>(file_path.c_str()); asset_cache[file_path] = new_asset; diff --git a/src/crepe/api/AudioSource.cpp b/src/crepe/api/AudioSource.cpp deleted file mode 100644 index 63fd0d7..0000000 --- a/src/crepe/api/AudioSource.cpp +++ /dev/null @@ -1,23 +0,0 @@ -#include <memory> - -#include "../facade/Sound.h" - -#include "AudioSource.h" - -using namespace crepe; - -AudioSource::AudioSource(std::unique_ptr<Asset> audio_clip) { - this->sound = std::make_unique<crepe::Sound>(std::move(audio_clip)); -} - -void AudioSource::play() { return this->play(false); } - -void AudioSource::play(bool looping) { - this->sound->set_looping(looping); - this->sound->play(); -} - -void AudioSource::stop() { - this->sound->pause(); - this->sound->rewind(); -} diff --git a/src/crepe/api/AudioSource.h b/src/crepe/api/AudioSource.h deleted file mode 100644 index 1e24ae8..0000000 --- a/src/crepe/api/AudioSource.h +++ /dev/null @@ -1,39 +0,0 @@ -#pragma once - -#include <memory> - -#include "../Asset.h" -#include "../Component.h" - -namespace crepe { - -class Sound; - -//! Audio source component -class AudioSource : public Component { -public: - AudioSource(std::unique_ptr<Asset> audio_clip); - virtual ~AudioSource() = default; - -public: - //! Start or resume this audio source - void play(); - void play(bool looping); - //! Stop this audio source - void stop(); - -public: - //! Sample file location - std::unique_ptr<Asset> audio_clip; - //! TODO: ????? - bool play_on_awake; - //! Repeat the current audio clip during playback - bool loop; - //! Normalized volume (0.0 - 1.0) - float volume; - -private: - std::unique_ptr<Sound> sound; -}; - -} // namespace crepe diff --git a/src/crepe/api/BehaviorScript.cpp b/src/crepe/api/BehaviorScript.cpp index e69de29..7bbace0 100644 --- a/src/crepe/api/BehaviorScript.cpp +++ b/src/crepe/api/BehaviorScript.cpp @@ -0,0 +1,15 @@ +#include "BehaviorScript.h" +#include "Component.h" +#include "GameObject.h" + +using namespace crepe; + +BehaviorScript::BehaviorScript(game_object_id_t id, ComponentManager & mgr) + : Component(id), + component_manager(mgr) {} + +template <> +BehaviorScript & GameObject::add_component<BehaviorScript>() { + ComponentManager & mgr = this->component_manager; + return mgr.add_component<BehaviorScript>(this->id, mgr); +} diff --git a/src/crepe/api/BehaviorScript.h b/src/crepe/api/BehaviorScript.h index 6b1fec7..9d85d4c 100644 --- a/src/crepe/api/BehaviorScript.h +++ b/src/crepe/api/BehaviorScript.h @@ -4,29 +4,69 @@ #include "../Component.h" +#include "GameObject.h" + namespace crepe { class ScriptSystem; class ComponentManager; class Script; +/** + * \brief Script component + * + * This class acts as a (component) wrapper around an instance of (a class derivatived from) \c + * Script. \c BehaviorScript is the only ECS component that stores member function + * implementations as data. + */ class BehaviorScript : public Component { protected: - friend class crepe::ComponentManager; - using Component::Component; - -public: - virtual ~BehaviorScript() = default; + /** + * \param id Parent \c GameObject id + * \param component_manager Reference to component manager (passed through to \c Script + * instance) + * + * \note Calls to this constructor (should) always pass through \c GameObject::add_component, + * which has an exception for this specific component type. This was done so the user does + * not have to pass references used within \c Script to each \c BehaviorScript instance. + */ + BehaviorScript(game_object_id_t id, ComponentManager & component_manager); + //! Only ComponentManager is allowed to instantiate BehaviorScript + friend class ComponentManager; public: + /** + * \brief Set the concrete script of this component + * + * \tparam T Concrete script type (derived from \c crepe::Script) + * + * \returns Reference to BehaviorScript component (`*this`) + */ template <class T> BehaviorScript & set_script(); protected: - friend class crepe::ScriptSystem; + //! Script instance std::unique_ptr<Script> script = nullptr; + //! ScriptSystem needs direct access to the script instance + friend class ScriptSystem; + +protected: + //! Reference to component manager (passed to Script) + ComponentManager & component_manager; }; +/** + * \brief Add a BehaviorScript component to this game object + * + * The \c BehaviorScript class is the only exception to the ECS harmony, and requires a + * reference to the component manager passed to its constructor in order to function normally. + * This is because the \c BehaviorScript (and \c Script) classes are the only component-related + * classes that store implemented member functions as data. + */ +template <> +BehaviorScript & GameObject::add_component<BehaviorScript>(); + } // namespace crepe #include "BehaviorScript.hpp" diff --git a/src/crepe/api/BehaviorScript.hpp b/src/crepe/api/BehaviorScript.hpp index 4751607..d80321d 100644 --- a/src/crepe/api/BehaviorScript.hpp +++ b/src/crepe/api/BehaviorScript.hpp @@ -2,7 +2,7 @@ #include <type_traits> -#include "../util/log.h" +#include "../util/Log.h" #include "BehaviorScript.h" #include "Script.h" @@ -11,10 +11,11 @@ namespace crepe { template <class T> BehaviorScript & BehaviorScript::set_script() { - static_assert(std::is_base_of<Script, T>::value); dbg_trace(); + static_assert(std::is_base_of<Script, T>::value); Script * s = new T(); - s->parent = this; + s->game_object_id = this->game_object_id; + s->component_manager_ref = &this->component_manager; this->script = std::unique_ptr<Script>(s); return *this; } diff --git a/src/crepe/api/CMakeLists.txt b/src/crepe/api/CMakeLists.txt index 85696c4..f9b370f 100644 --- a/src/crepe/api/CMakeLists.txt +++ b/src/crepe/api/CMakeLists.txt @@ -1,7 +1,6 @@ target_sources(crepe PUBLIC # AudioSource.cpp BehaviorScript.cpp - Script.cpp GameObject.cpp Rigidbody.cpp ParticleEmitter.cpp diff --git a/src/crepe/api/Camera.cpp b/src/crepe/api/Camera.cpp index 6355a03..5835bdd 100644 --- a/src/crepe/api/Camera.cpp +++ b/src/crepe/api/Camera.cpp @@ -1,7 +1,4 @@ - -#include <cstdint> - -#include "util/log.h" +#include "util/Log.h" #include "Camera.h" #include "Color.h" @@ -9,7 +6,7 @@ using namespace crepe; -Camera::Camera(uint32_t id, const Color & bg_color) +Camera::Camera(game_object_id_t id, const Color & bg_color) : Component(id), bg_color(bg_color) { dbg_trace(); diff --git a/src/crepe/api/Camera.h b/src/crepe/api/Camera.h index ba3a9ef..e0cda34 100644 --- a/src/crepe/api/Camera.h +++ b/src/crepe/api/Camera.h @@ -1,7 +1,5 @@ #pragma once -#include <cstdint> - #include "Color.h" #include "Component.h" @@ -11,9 +9,8 @@ namespace crepe { * \class Camera * \brief Represents a camera component for rendering in the game. * - * The Camera class defines the view parameters, including background color, - * aspect ratio, position, and zoom level. It controls what part of the game - * world is visible on the screen. + * The Camera class defines the view parameters, including background color, aspect ratio, + * position, and zoom level. It controls what part of the game world is visible on the screen. */ class Camera : public Component { @@ -23,7 +20,7 @@ public: * \param id Unique identifier for the camera component. * \param bg_color Background color for the camera view. */ - Camera(uint32_t id, const Color & bg_color); + Camera(game_object_id_t id, const Color & bg_color); ~Camera(); // dbg_trace only public: diff --git a/src/crepe/api/Config.h b/src/crepe/api/Config.h index 8c9e643..3ab877a 100644 --- a/src/crepe/api/Config.h +++ b/src/crepe/api/Config.h @@ -1,19 +1,24 @@ #pragma once -#include "../util/log.h" +#include "../util/Log.h" namespace crepe { +/** + * \brief Global configuration interface + * + * This class stores engine default settings. Properties on this class are only supposed to be + * modified *before* execution is handed over from the game programmer to the engine (i.e. the + * main loop is started). + */ class Config { -private: - Config() = default; - -public: - ~Config() = default; - public: //! Retrieve handle to global Config instance static Config & get_instance(); + +private: + Config() = default; + // singleton Config(const Config &) = delete; Config(Config &&) = delete; @@ -26,10 +31,9 @@ public: /** * \brief Log level * - * Only messages with equal or higher priority than this value will be - * logged. + * Only messages with equal or higher priority than this value will be logged. */ - LogLevel level = LogLevel::INFO; + Log::Level level = Log::Level::INFO; /** * \brief Colored log output * @@ -43,8 +47,8 @@ public: /** * \brief Save file location * - * This location is used by the constructor of SaveManager, and should be - * set before save manager functionality is attempted to be used. + * This location is used by the constructor of SaveManager, and should be set before save + * manager functionality is attempted to be used. */ std::string location = "save.crepe.db"; } savemgr; diff --git a/src/crepe/api/GameObject.cpp b/src/crepe/api/GameObject.cpp index d252e77..287e81d 100644 --- a/src/crepe/api/GameObject.cpp +++ b/src/crepe/api/GameObject.cpp @@ -1,23 +1,26 @@ #include "api/Transform.h" +#include "BehaviorScript.h" #include "GameObject.h" #include "Metadata.h" using namespace crepe; using namespace std; -GameObject::GameObject(game_object_id_t id, const std::string & name, - const std::string & tag, const Vector2 & position, - double rotation, double scale) - : id(id) { +GameObject::GameObject(ComponentManager & component_manager, game_object_id_t id, + const std::string & name, const std::string & tag, + const Vector2 & position, double rotation, double scale) + : id(id), + component_manager(component_manager) { + // Add Transform and Metadata components - ComponentManager & mgr = ComponentManager::get_instance(); + ComponentManager & mgr = this->component_manager; mgr.add_component<Transform>(this->id, position, rotation, scale); mgr.add_component<Metadata>(this->id, name, tag); } void GameObject::set_parent(const GameObject & parent) { - ComponentManager & mgr = ComponentManager::get_instance(); + ComponentManager & mgr = this->component_manager; // Set parent on own Metadata component vector<reference_wrapper<Metadata>> this_metadata diff --git a/src/crepe/api/GameObject.h b/src/crepe/api/GameObject.h index d703730..34ef8bb 100644 --- a/src/crepe/api/GameObject.h +++ b/src/crepe/api/GameObject.h @@ -2,25 +2,26 @@ #include <string> +#include "Vector2.h" #include "types.h" namespace crepe { -class Vector2; +class ComponentManager; /** * \brief Represents a GameObject * - * This class represents a GameObject. The GameObject class is only used - * as an interface for the game programmer. The actual implementation is - * done in the ComponentManager. + * This class represents a GameObject. The GameObject class is only used as an interface for + * the game programmer. The actual implementation is done in the ComponentManager. */ class GameObject { -public: +private: /** - * This constructor creates a new GameObject. It creates a new - * Transform and Metadata component and adds them to the ComponentManager. + * This constructor creates a new GameObject. It creates a new Transform and Metadata + * component and adds them to the ComponentManager. * + * \param component_manager Reference to component_manager * \param id The id of the GameObject * \param name The name of the GameObject * \param tag The tag of the GameObject @@ -28,15 +29,19 @@ public: * \param rotation The rotation of the GameObject * \param scale The scale of the GameObject */ - GameObject(game_object_id_t id, const std::string & name, - const std::string & tag, const Vector2 & position, + GameObject(ComponentManager & component_manager, game_object_id_t id, + const std::string & name, const std::string & tag, const Vector2 & position, double rotation, double scale); + //! ComponentManager instances GameObject + friend class ComponentManager; + +public: /** * \brief Set the parent of this GameObject * - * This method sets the parent of this GameObject. It sets the parent - * in the Metadata component of this GameObject and adds this GameObject - * to the children list of the parent GameObject. + * This method sets the parent of this GameObject. It sets the parent in the Metadata + * component of this GameObject and adds this GameObject to the children list of the parent + * GameObject. * * \param parent The parent GameObject */ @@ -44,8 +49,8 @@ public: /** * \brief Add a component to the GameObject * - * This method adds a component to the GameObject. It forwards the - * arguments to the ComponentManager. + * This method adds a component to the GameObject. It forwards the arguments to the + * ComponentManager. * * \tparam T The type of the component * \tparam Args The types of the arguments @@ -58,6 +63,9 @@ public: public: //! The id of the GameObject const game_object_id_t id; + +protected: + ComponentManager & component_manager; }; } // namespace crepe diff --git a/src/crepe/api/GameObject.hpp b/src/crepe/api/GameObject.hpp index bfba7fe..17b17d7 100644 --- a/src/crepe/api/GameObject.hpp +++ b/src/crepe/api/GameObject.hpp @@ -8,7 +8,7 @@ namespace crepe { template <typename T, typename... Args> T & GameObject::add_component(Args &&... args) { - ComponentManager & mgr = ComponentManager::get_instance(); + ComponentManager & mgr = this->component_manager; return mgr.add_component<T>(this->id, std::forward<Args>(args)...); } diff --git a/src/crepe/api/LoopManager.cpp b/src/crepe/api/LoopManager.cpp index 2e9823f..a64366f 100644 --- a/src/crepe/api/LoopManager.cpp +++ b/src/crepe/api/LoopManager.cpp @@ -1,5 +1,9 @@ - #include "../facade/SDLContext.h" + +#include "../system/AnimatorSystem.h" +#include "../system/CollisionSystem.h" +#include "../system/ParticleSystem.h" +#include "../system/PhysicsSystem.h" #include "../system/RenderSystem.h" #include "../system/ScriptSystem.h" @@ -7,11 +11,21 @@ #include "LoopTimer.h" using namespace crepe; +using namespace std; + +LoopManager::LoopManager() { + this->load_system<AnimatorSystem>(); + this->load_system<CollisionSystem>(); + this->load_system<ParticleSystem>(); + this->load_system<PhysicsSystem>(); + this->load_system<RenderSystem>(); + this->load_system<ScriptSystem>(); +} -LoopManager::LoopManager() {} void LoopManager::process_input() { SDLContext::get_instance().handle_events(this->game_running); } + void LoopManager::start() { this->setup(); this->loop(); @@ -48,7 +62,7 @@ void LoopManager::setup() { void LoopManager::render() { if (this->game_running) { - RenderSystem::get_instance().update(); + this->get_system<RenderSystem>().update(); } } diff --git a/src/crepe/api/LoopManager.h b/src/crepe/api/LoopManager.h index 2f03193..f6904be 100644 --- a/src/crepe/api/LoopManager.h +++ b/src/crepe/api/LoopManager.h @@ -2,15 +2,9 @@ #include <memory> -class RenderSystem; -class SDLContext; -class LoopTimer; -class ScriptSystem; -class SoundSystem; -class ParticleSystem; -class PhysicsSystem; -class AnimatorSystem; -class CollisionSystem; +#include "../ComponentManager.h" +#include "../system/System.h" + namespace crepe { class LoopManager { @@ -73,7 +67,35 @@ private: void render(); bool game_running = false; - //#TODO add system instances + +private: + //! Component manager instance + ComponentManager component_manager{}; + +private: + /** + * \brief Collection of System instances + * + * This map holds System instances indexed by the system's class typeid. It is filled in the + * constructor of \c LoopManager using LoopManager::load_system. + */ + std::unordered_map<std::type_index, std::unique_ptr<System>> systems; + /** + * \brief Initialize a system + * \tparam T System type (must be derivative of \c System) + */ + template <class T> + void load_system(); + /** + * \brief Retrieve a reference to ECS system + * \tparam T System type + * \returns Reference to system instance + * \throws std::runtime_error if the System is not initialized + */ + template <class T> + T & get_system(); }; } // namespace crepe + +#include "LoopManager.hpp" diff --git a/src/crepe/api/LoopManager.hpp b/src/crepe/api/LoopManager.hpp new file mode 100644 index 0000000..0b14fdb --- /dev/null +++ b/src/crepe/api/LoopManager.hpp @@ -0,0 +1,40 @@ +#pragma once + +#include <cassert> +#include <format> +#include <memory> + +#include "../system/System.h" + +#include "LoopManager.h" + +namespace crepe { + +template <class T> +T & LoopManager::get_system() { + using namespace std; + static_assert(is_base_of<System, T>::value, + "get_system must recieve a derivative class of System"); + + const type_info & type = typeid(T); + if (!this->systems.contains(type)) + throw runtime_error(format("LoopManager: {} is not initialized", type.name())); + + System * system = this->systems.at(type).get(); + T * concrete_system = dynamic_cast<T *>(system); + assert(concrete_system != nullptr); + + return *concrete_system; +} + +template <class T> +void LoopManager::load_system() { + using namespace std; + static_assert(is_base_of<System, T>::value, + "load_system must recieve a derivative class of System"); + + System * system = new T(this->component_manager); + this->systems[typeid(T)] = unique_ptr<System>(system); +} + +} // namespace crepe diff --git a/src/crepe/api/LoopTimer.cpp b/src/crepe/api/LoopTimer.cpp index 8f09e41..a9800b7 100644 --- a/src/crepe/api/LoopTimer.cpp +++ b/src/crepe/api/LoopTimer.cpp @@ -1,7 +1,7 @@ #include <chrono> #include "../facade/SDLContext.h" -#include "../util/log.h" +#include "../util/Log.h" #include "LoopTimer.h" @@ -24,9 +24,8 @@ void LoopTimer::start() { void LoopTimer::update() { auto current_frame_time = std::chrono::steady_clock::now(); // Convert to duration in seconds for delta time - this->delta_time - = std::chrono::duration_cast<std::chrono::duration<double>>( - current_frame_time - last_frame_time); + this->delta_time = std::chrono::duration_cast<std::chrono::duration<double>>( + current_frame_time - last_frame_time); if (this->delta_time > this->maximum_delta_time) { this->delta_time = this->maximum_delta_time; @@ -39,17 +38,11 @@ void LoopTimer::update() { double LoopTimer::get_delta_time() const { return this->delta_time.count(); } -double LoopTimer::get_current_time() const { - return this->elapsed_time.count(); -} +double LoopTimer::get_current_time() const { return this->elapsed_time.count(); } -void LoopTimer::advance_fixed_update() { - this->elapsed_fixed_time += this->fixed_delta_time; -} +void LoopTimer::advance_fixed_update() { this->elapsed_fixed_time += this->fixed_delta_time; } -double LoopTimer::get_fixed_delta_time() const { - return this->fixed_delta_time.count(); -} +double LoopTimer::get_fixed_delta_time() const { return this->fixed_delta_time.count(); } void LoopTimer::set_fps(int fps) { this->fps = fps; @@ -66,13 +59,13 @@ void LoopTimer::enforce_frame_rate() { std::chrono::steady_clock::time_point current_frame_time = std::chrono::steady_clock::now(); std::chrono::milliseconds frame_duration - = std::chrono::duration_cast<std::chrono::milliseconds>( - current_frame_time - this->last_frame_time); + = std::chrono::duration_cast<std::chrono::milliseconds>(current_frame_time + - this->last_frame_time); if (frame_duration < this->frame_target_time) { std::chrono::milliseconds delay_time - = std::chrono::duration_cast<std::chrono::milliseconds>( - this->frame_target_time - frame_duration); + = std::chrono::duration_cast<std::chrono::milliseconds>(this->frame_target_time + - frame_duration); if (delay_time.count() > 0) { SDLContext::get_instance().delay(delay_time.count()); } diff --git a/src/crepe/api/LoopTimer.h b/src/crepe/api/LoopTimer.h index 85687be..f277d7b 100644 --- a/src/crepe/api/LoopTimer.h +++ b/src/crepe/api/LoopTimer.h @@ -1,124 +1,123 @@ #pragma once #include <chrono> -#include <cstdint> namespace crepe { class LoopTimer { public: /** - * \brief Get the singleton instance of LoopTimer. - * - * \return A reference to the LoopTimer instance. - */ + * \brief Get the singleton instance of LoopTimer. + * + * \return A reference to the LoopTimer instance. + */ static LoopTimer & get_instance(); /** - * \brief Get the current delta time for the current frame. - * - * \return Delta time in seconds since the last frame. - */ + * \brief Get the current delta time for the current frame. + * + * \return Delta time in seconds since the last frame. + */ double get_delta_time() const; /** - * \brief Get the current game time. - * - * \note The current game time may vary from real-world elapsed time. - * It is the cumulative sum of each frame's delta time. - * - * \return Elapsed game time in seconds. - */ + * \brief Get the current game time. + * + * \note The current game time may vary from real-world elapsed time. It is the cumulative + * sum of each frame's delta time. + * + * \return Elapsed game time in seconds. + */ double get_current_time() const; /** - * \brief Set the target frames per second (FPS). - * - * \param fps The desired frames rendered per second. - */ + * \brief Set the target frames per second (FPS). + * + * \param fps The desired frames rendered per second. + */ void set_fps(int fps); /** - * \brief Get the current frames per second (FPS). - * - * \return Current FPS. - */ + * \brief Get the current frames per second (FPS). + * + * \return Current FPS. + */ int get_fps() const; /** - * \brief Get the current game scale. - * - * \return The current game scale, where 0 = paused, 1 = normal speed, and values > 1 speed up the game. - */ + * \brief Get the current game scale. + * + * \return The current game scale, where 0 = paused, 1 = normal speed, and values > 1 speed + * up the game. + */ double get_game_scale() const; /** - * \brief Set the game scale. - * - * \param game_scale The desired game scale (0 = pause, 1 = normal speed, > 1 = speed up). - */ + * \brief Set the game scale. + * + * \param game_scale The desired game scale (0 = pause, 1 = normal speed, > 1 = speed up). + */ void set_game_scale(double game_scale); private: friend class LoopManager; /** - * \brief Start the loop timer. - * - * Initializes the timer to begin tracking frame times. - */ + * \brief Start the loop timer. + * + * Initializes the timer to begin tracking frame times. + */ void start(); /** - * \brief Enforce the frame rate limit. - * - * Ensures that the game loop does not exceed the target FPS by delaying - * frame updates as necessary. - */ + * \brief Enforce the frame rate limit. + * + * Ensures that the game loop does not exceed the target FPS by delaying frame updates as + * necessary. + */ void enforce_frame_rate(); /** - * \brief Get the fixed delta time for consistent updates. - * - * Fixed delta time is used for operations that require uniform time steps, - * such as physics calculations. - * - * \return Fixed delta time in seconds. - */ + * \brief Get the fixed delta time for consistent updates. + * + * Fixed delta time is used for operations that require uniform time steps, such as physics + * calculations. + * + * \return Fixed delta time in seconds. + */ double get_fixed_delta_time() const; /** - * \brief Get the accumulated lag in the game loop. - * - * Lag represents the difference between the target frame time and the - * actual frame time, useful for managing fixed update intervals. - * - * \return Accumulated lag in seconds. - */ + * \brief Get the accumulated lag in the game loop. + * + * Lag represents the difference between the target frame time and the actual frame time, + * useful for managing fixed update intervals. + * + * \return Accumulated lag in seconds. + */ double get_lag() const; /** - * \brief Construct a new LoopTimer object. - * - * Private constructor for singleton pattern to restrict instantiation - * outside the class. - */ + * \brief Construct a new LoopTimer object. + * + * Private constructor for singleton pattern to restrict instantiation outside the class. + */ LoopTimer(); /** - * \brief Update the timer to the current frame. - * - * Calculates and updates the delta time for the current frame and adds it to - * the cumulative game time. - */ + * \brief Update the timer to the current frame. + * + * Calculates and updates the delta time for the current frame and adds it to the cumulative + * game time. + */ void update(); /** - * \brief Advance the game loop by a fixed update interval. - * - * This method progresses the game state by a consistent, fixed time step, - * allowing for stable updates independent of frame rate fluctuations. - */ + * \brief Advance the game loop by a fixed update interval. + * + * This method progresses the game state by a consistent, fixed time step, allowing for + * stable updates independent of frame rate fluctuations. + */ void advance_fixed_update(); private: @@ -131,11 +130,9 @@ private: //! Delta time for the current frame in seconds std::chrono::duration<double> delta_time{0.0}; //! Target time per frame in seconds - std::chrono::duration<double> frame_target_time - = std::chrono::seconds(1) / fps; + std::chrono::duration<double> frame_target_time = std::chrono::seconds(1) / fps; //! Fixed delta time for fixed updates in seconds - std::chrono::duration<double> fixed_delta_time - = std::chrono::seconds(1) / 50; + std::chrono::duration<double> fixed_delta_time = std::chrono::seconds(1) / 50; //! Total elapsed game time in seconds std::chrono::duration<double> elapsed_time{0.0}; //! Total elapsed time for fixed updates in seconds diff --git a/src/crepe/api/Metadata.h b/src/crepe/api/Metadata.h index c61e006..235d42f 100644 --- a/src/crepe/api/Metadata.h +++ b/src/crepe/api/Metadata.h @@ -10,8 +10,8 @@ namespace crepe { /** * \brief Metadata component * - * This class represents the Metadata component. It stores the name, tag, parent - * and children of a GameObject. + * This class represents the Metadata component. It stores the name, tag, parent and children + * of a GameObject. */ class Metadata : public Component { public: @@ -20,8 +20,7 @@ public: * \param name The name of the GameObject * \param tag The tag of the GameObject */ - Metadata(game_object_id_t id, const std::string & name, - const std::string & tag); + Metadata(game_object_id_t id, const std::string & name, const std::string & tag); /** * \brief Get the maximum number of instances for this component * diff --git a/src/crepe/api/ParticleEmitter.cpp b/src/crepe/api/ParticleEmitter.cpp index 35f960d..90b77a0 100644 --- a/src/crepe/api/ParticleEmitter.cpp +++ b/src/crepe/api/ParticleEmitter.cpp @@ -2,8 +2,7 @@ using namespace crepe; -ParticleEmitter::ParticleEmitter(game_object_id_t game_object_id, - const Data & data) +ParticleEmitter::ParticleEmitter(game_object_id_t game_object_id, const Data & data) : Component(game_object_id), data(data) { for (size_t i = 0; i < this->data.max_particles; i++) { diff --git a/src/crepe/api/ParticleEmitter.h b/src/crepe/api/ParticleEmitter.h index a9e872f..33112e1 100644 --- a/src/crepe/api/ParticleEmitter.h +++ b/src/crepe/api/ParticleEmitter.h @@ -13,16 +13,16 @@ class Sprite; /** * \brief Data holder for particle emission parameters. * - * The ParticleEmitter class stores configuration data for particle properties, - * defining the characteristics and boundaries of particle emissions. + * The ParticleEmitter class stores configuration data for particle properties, defining the + * characteristics and boundaries of particle emissions. */ class ParticleEmitter : public Component { public: /** * \brief Defines the boundary within which particles are constrained. * - * This structure specifies the boundary's size and offset, as well as the - * behavior of particles upon reaching the boundary limits. + * This structure specifies the boundary's size and offset, as well as the behavior of + * particles upon reaching the boundary limits. */ struct Boundary { //! boundary width (midpoint is emitter location) @@ -38,8 +38,8 @@ public: /** * \brief Holds parameters that control particle emission. * - * Contains settings for the emitter’s position, particle speed, angle, lifespan, - * boundary, and the sprite used for rendering particles. + * Contains settings for the emitter’s position, particle speed, angle, lifespan, boundary, + * and the sprite used for rendering particles. */ struct Data { //! position of the emitter diff --git a/src/crepe/api/Rigidbody.cpp b/src/crepe/api/Rigidbody.cpp index 3bf1c5b..6b87695 100644 --- a/src/crepe/api/Rigidbody.cpp +++ b/src/crepe/api/Rigidbody.cpp @@ -2,8 +2,8 @@ using namespace crepe; -crepe::Rigidbody::Rigidbody(uint32_t game_object_id, const Data & data) - : Component(game_object_id), +crepe::Rigidbody::Rigidbody(game_object_id_t id, const Data & data) + : Component(id), data(data) {} void crepe::Rigidbody::add_force_linear(const Vector2 & force) { diff --git a/src/crepe/api/Rigidbody.h b/src/crepe/api/Rigidbody.h index 68481f4..3e5c7a3 100644 --- a/src/crepe/api/Rigidbody.h +++ b/src/crepe/api/Rigidbody.h @@ -1,7 +1,5 @@ #pragma once -#include <cstdint> - #include "../Component.h" #include "Vector2.h" @@ -11,8 +9,8 @@ namespace crepe { /** * \brief Rigidbody class * - * This class is used by the physics sytem and collision system. - * It configures how to system interact with the gameobject for movement and collisions. + * This class is used by the physics sytem and collision system. It configures how to system + * interact with the gameobject for movement and collisions. */ class Rigidbody : public Component { public: @@ -32,8 +30,8 @@ public: /** * \brief PhysicsConstraints to constrain movement * - * This struct configures the movement constraint for this object. - * If a constraint is enabled the systems will not move the object. + * This struct configures the movement constraint for this object. If a constraint is enabled + * the systems will not move the object. */ struct PhysicsConstraints { //! X constraint @@ -82,7 +80,7 @@ public: * \param game_object_id id of the gameobject the rigibody is added to. * \param data struct to configure the rigidbody. */ - Rigidbody(uint32_t game_object_id, const Data & data); + Rigidbody(game_object_id_t id, const Data & data); //! struct to hold data of rigidbody Data data; diff --git a/src/crepe/api/SaveManager.cpp b/src/crepe/api/SaveManager.cpp index 43276c5..c5f43ea 100644 --- a/src/crepe/api/SaveManager.cpp +++ b/src/crepe/api/SaveManager.cpp @@ -1,5 +1,5 @@ #include "../facade/DB.h" -#include "../util/log.h" +#include "../util/Log.h" #include "Config.h" #include "SaveManager.h" @@ -139,14 +139,11 @@ ValueBroker<T> SaveManager::get(const string & key, const T & default_value) { } template ValueBroker<uint8_t> SaveManager::get(const string &, const uint8_t &); template ValueBroker<int8_t> SaveManager::get(const string &, const int8_t &); -template ValueBroker<uint16_t> SaveManager::get(const string &, - const uint16_t &); +template ValueBroker<uint16_t> SaveManager::get(const string &, const uint16_t &); template ValueBroker<int16_t> SaveManager::get(const string &, const int16_t &); -template ValueBroker<uint32_t> SaveManager::get(const string &, - const uint32_t &); +template ValueBroker<uint32_t> SaveManager::get(const string &, const uint32_t &); template ValueBroker<int32_t> SaveManager::get(const string &, const int32_t &); -template ValueBroker<uint64_t> SaveManager::get(const string &, - const uint64_t &); +template ValueBroker<uint64_t> SaveManager::get(const string &, const uint64_t &); template ValueBroker<int64_t> SaveManager::get(const string &, const int64_t &); template ValueBroker<float> SaveManager::get(const string &, const float &); template ValueBroker<double> SaveManager::get(const string &, const double &); diff --git a/src/crepe/api/SaveManager.h b/src/crepe/api/SaveManager.h index 4be85fb..3d8c852 100644 --- a/src/crepe/api/SaveManager.h +++ b/src/crepe/api/SaveManager.h @@ -24,7 +24,8 @@ public: * \brief Get a read/write reference to a value and initialize it if it does not yet exist * * \param key The value key - * \param default_value Value to initialize \c key with if it does not already exist in the database + * \param default_value Value to initialize \c key with if it does not already exist in the + * database * * \return Read/write reference to the value */ @@ -38,8 +39,8 @@ public: * * \return Read/write reference to the value * - * \note Attempting to read this value before it is initialized (i.e. set) - * will result in an exception + * \note Attempting to read this value before it is initialized (i.e. set) will result in an + * exception */ template <typename T> ValueBroker<T> get(const std::string & key); @@ -102,8 +103,8 @@ private: * * \returns DB instance * - * This function exists because DB is a facade class, which can't directly be - * used in the API without workarounds + * This function exists because DB is a facade class, which can't directly be used in the API + * without workarounds * * TODO: better solution */ diff --git a/src/crepe/api/Scene.cpp b/src/crepe/api/Scene.cpp index 933edf4..88aa82d 100644 --- a/src/crepe/api/Scene.cpp +++ b/src/crepe/api/Scene.cpp @@ -2,4 +2,6 @@ using namespace crepe; -Scene::Scene(const std::string & name) : name(name) {} +Scene::Scene(ComponentManager & mgr, const std::string & name) + : component_manager(mgr), + name(name) {} diff --git a/src/crepe/api/Scene.h b/src/crepe/api/Scene.h index f8bcc3d..0e516b6 100644 --- a/src/crepe/api/Scene.h +++ b/src/crepe/api/Scene.h @@ -4,14 +4,23 @@ namespace crepe { +class SceneManager; +class ComponentManager; + class Scene { +protected: + Scene(ComponentManager & mgr, const std::string & name); + friend class SceneManager; + public: - Scene(const std::string & name); virtual ~Scene() = default; - virtual void load_scene() = 0; public: - std::string name; + virtual void load_scene() = 0; + const std::string name; + +protected: + ComponentManager & component_manager; }; } // namespace crepe diff --git a/src/crepe/api/SceneManager.cpp b/src/crepe/api/SceneManager.cpp index dfed6ee..7fb5cb0 100644 --- a/src/crepe/api/SceneManager.cpp +++ b/src/crepe/api/SceneManager.cpp @@ -8,10 +8,7 @@ using namespace crepe; using namespace std; -SceneManager & SceneManager::get_instance() { - static SceneManager instance; - return instance; -} +SceneManager::SceneManager(ComponentManager & mgr) : component_manager(mgr) {} void SceneManager::set_next_scene(const string & name) { next_scene = name; } @@ -19,18 +16,17 @@ void SceneManager::load_next_scene() { // next scene not set if (this->next_scene.empty()) return; - auto it - = find_if(this->scenes.begin(), this->scenes.end(), - [&next_scene = this->next_scene](unique_ptr<Scene> & scene) { - return scene->name == next_scene; - }); + auto it = find_if(this->scenes.begin(), this->scenes.end(), + [&next_scene = this->next_scene](unique_ptr<Scene> & scene) { + return scene->name == next_scene; + }); // next scene not found if (it == this->scenes.end()) return; unique_ptr<Scene> & scene = *it; // Delete all components of the current scene - ComponentManager & mgr = ComponentManager::get_instance(); + ComponentManager & mgr = this->component_manager; mgr.delete_all_components(); // Load the new scene diff --git a/src/crepe/api/SceneManager.h b/src/crepe/api/SceneManager.h index 1e0e670..e854794 100644 --- a/src/crepe/api/SceneManager.h +++ b/src/crepe/api/SceneManager.h @@ -8,14 +8,11 @@ namespace crepe { +class ComponentManager; + class SceneManager { public: - // Singleton - static SceneManager & get_instance(); - SceneManager(const SceneManager &) = delete; - SceneManager(SceneManager &&) = delete; - SceneManager & operator=(const SceneManager &) = delete; - SceneManager & operator=(SceneManager &&) = delete; + SceneManager(ComponentManager & mgr); public: /** @@ -38,11 +35,9 @@ public: void load_next_scene(); private: - SceneManager() = default; - -private: std::vector<std::unique_ptr<Scene>> scenes; std::string next_scene; + ComponentManager & component_manager; }; } // namespace crepe diff --git a/src/crepe/api/SceneManager.hpp b/src/crepe/api/SceneManager.hpp index 8bad7b2..714f690 100644 --- a/src/crepe/api/SceneManager.hpp +++ b/src/crepe/api/SceneManager.hpp @@ -1,13 +1,16 @@ +#pragma once + #include "SceneManager.h" namespace crepe { template <typename T> void SceneManager::add_scene(const std::string & name) { - static_assert(std::is_base_of<Scene, T>::value, - "T must be derived from Scene"); + using namespace std; + static_assert(is_base_of<Scene, T>::value, "T must be derived from Scene"); - scenes.emplace_back(make_unique<T>(name)); + Scene * scene = new T(this->component_manager, name); + this->scenes.emplace_back(unique_ptr<Scene>(scene)); // The first scene added, is the one that will be loaded at the beginning if (next_scene.empty()) { diff --git a/src/crepe/api/Script.cpp b/src/crepe/api/Script.cpp deleted file mode 100644 index 390cec7..0000000 --- a/src/crepe/api/Script.cpp +++ /dev/null @@ -1,3 +0,0 @@ -#include "Script.h" - -using namespace crepe; diff --git a/src/crepe/api/Script.h b/src/crepe/api/Script.h index 49e625f..2b70379 100644 --- a/src/crepe/api/Script.h +++ b/src/crepe/api/Script.h @@ -2,35 +2,85 @@ #include <vector> -namespace crepe { -class ScriptSystem; -} +#include "../types.h" namespace crepe { +class ScriptSystem; class BehaviorScript; +class ComponentManager; +/** + * \brief Script interface + * + * This class is used as a base class for user-defined scripts that can be added to game + * objects using the \c BehaviorScript component. + * + * \note Additional *events* (like Unity's OnDisable and OnEnable) should be implemented as + * member or lambda methods in derivative user script classes and registered in \c init(). + */ class Script { - friend class crepe::ScriptSystem; - protected: + /** + * \brief Script initialization function + * + * This function is called during the ScriptSystem::update() routine *before* + * Script::update() if it (a) has not yet been called and (b) the \c BehaviorScript component + * holding this script instance is active. + */ virtual void init() {} + /** + * \brief Script update function + * + * This function is called during the ScriptSystem::update() routine if the \c BehaviorScript + * component holding this script instance is active. + */ virtual void update() {} - // NOTE: additional *events* (like unity's OnDisable and OnEnable) should be - // implemented as member methods in derivative user script classes and - // registered in init(), otherwise this class will balloon in size with each - // added event. + //! ScriptSystem calls \c init() and \c update() + friend class crepe::ScriptSystem; protected: + /** + * \brief Get single component of type \c T on this game object (utility) + * + * \tparam T Type of component + * + * \returns Reference to component + * + * \throws nullptr if this game object does not have a component matching type \c T + */ template <typename T> - T & get_component(); + T & get_component() const; + // TODO: make get_component calls for component types that can have more than 1 instance + // cause compile-time errors + /** + * \brief Get all components of type \c T on this game object (utility) + * + * \tparam T Type of component + * + * \returns List of component references + */ template <typename T> - std::vector<std::reference_wrapper<T>> get_components(); + std::vector<std::reference_wrapper<T>> get_components() const; + +protected: + // NOTE: Script must have a constructor without arguments so the game programmer doesn't need + // to manually add `using Script::Script` to their concrete script class. + Script() = default; + //! Only \c BehaviorScript instantiates Script + friend class BehaviorScript; + +private: + // These references are set by BehaviorScript immediately after calling the constructor of + // Script. + game_object_id_t game_object_id = -1; + ComponentManager * component_manager_ref = nullptr; + // TODO: use OptionalRef instead of pointer private: - friend class crepe::BehaviorScript; - BehaviorScript * parent = nullptr; + //! Flag to indicate if \c init() has been called already + bool initialized = false; }; } // namespace crepe diff --git a/src/crepe/api/Script.hpp b/src/crepe/api/Script.hpp index d96c0e8..a064a90 100644 --- a/src/crepe/api/Script.hpp +++ b/src/crepe/api/Script.hpp @@ -8,18 +8,21 @@ namespace crepe { template <typename T> -T & Script::get_component() { - std::vector<std::reference_wrapper<T>> all_components - = this->get_components<T>(); - if (all_components.size() < 1) throw nullptr; // TODO +T & Script::get_component() const { + using namespace std; + vector<reference_wrapper<T>> all_components = this->get_components<T>(); + if (all_components.size() < 1) + throw runtime_error( + format("Script: no component found with type = {}", typeid(T).name())); return all_components.back().get(); } template <typename T> -std::vector<std::reference_wrapper<T>> Script::get_components() { - ComponentManager & mgr = ComponentManager::get_instance(); - return mgr.get_components_by_id<T>(this->parent->game_object_id); +std::vector<std::reference_wrapper<T>> Script::get_components() const { + auto & mgr = *this->component_manager_ref; + + return mgr.get_components_by_id<T>(this->game_object_id); } } // namespace crepe diff --git a/src/crepe/api/Sprite.cpp b/src/crepe/api/Sprite.cpp index 6f0433f..bd2d5cf 100644 --- a/src/crepe/api/Sprite.cpp +++ b/src/crepe/api/Sprite.cpp @@ -1,6 +1,6 @@ #include <memory> -#include "../util/log.h" +#include "../util/Log.h" #include "facade/SDLContext.h" #include "Component.h" @@ -10,8 +10,8 @@ using namespace std; using namespace crepe; -Sprite::Sprite(game_object_id_t id, const shared_ptr<Texture> image, - const Color & color, const FlipSettings & flip) +Sprite::Sprite(game_object_id_t id, const shared_ptr<Texture> image, const Color & color, + const FlipSettings & flip) : Component(id), color(color), flip(flip), diff --git a/src/crepe/api/Sprite.h b/src/crepe/api/Sprite.h index deb3f93..0192793 100644 --- a/src/crepe/api/Sprite.h +++ b/src/crepe/api/Sprite.h @@ -1,6 +1,5 @@ #pragma once -#include <cstdint> #include <memory> #include "Color.h" @@ -28,8 +27,8 @@ class AnimatorSystem; /** * \brief Represents a renderable sprite component. * - * A renderable sprite that can be displayed in the game. It includes a texture, - * color, and flip settings, and is managed in layers with defined sorting orders. + * A renderable sprite that can be displayed in the game. It includes a texture, color, and + * flip settings, and is managed in layers with defined sorting orders. */ class Sprite : public Component { @@ -43,8 +42,8 @@ public: * \param color Color tint applied to the sprite. * \param flip Flip settings for horizontal and vertical orientation. */ - Sprite(game_object_id_t id, const std::shared_ptr<Texture> image, - const Color & color, const FlipSettings & flip); + Sprite(game_object_id_t id, const std::shared_ptr<Texture> image, const Color & color, + const FlipSettings & flip); /** * \brief Destroys the Sprite instance. @@ -81,7 +80,8 @@ private: //! Reads the all the variables plus the sprite_rect friend class AnimatorSystem; - //! Render area of the sprite this will also be adjusted by the AnimatorSystem if an Animator object is present in GameObject + //! Render area of the sprite this will also be adjusted by the AnimatorSystem if an Animator + // object is present in GameObject Rect sprite_rect; }; diff --git a/src/crepe/api/Texture.cpp b/src/crepe/api/Texture.cpp index 8ce65c2..734a5bb 100644 --- a/src/crepe/api/Texture.cpp +++ b/src/crepe/api/Texture.cpp @@ -1,7 +1,7 @@ #include <SDL2/SDL_render.h> #include "../facade/SDLContext.h" -#include "../util/log.h" +#include "../util/Log.h" #include "Asset.h" #include "Texture.h" @@ -26,7 +26,7 @@ Texture::~Texture() { void Texture::load(unique_ptr<Asset> res) { SDLContext & ctx = SDLContext::get_instance(); - this->texture = std::move(ctx.texture_from_path(res->canonical())); + this->texture = std::move(ctx.texture_from_path(res->get_canonical())); } int Texture::get_width() const { diff --git a/src/crepe/api/Texture.h b/src/crepe/api/Texture.h index b89bc17..6965223 100644 --- a/src/crepe/api/Texture.h +++ b/src/crepe/api/Texture.h @@ -1,8 +1,7 @@ #pragma once -// FIXME: this header can't be included because this is an API header, and SDL2 -// development headers won't be bundled with crepe. Why is this facade in the -// API namespace? +// FIXME: this header can't be included because this is an API header, and SDL2 development +// headers won't be bundled with crepe. Why is this facade in the API namespace? #include <SDL2/SDL_render.h> #include <functional> @@ -19,8 +18,8 @@ class Animator; * \class Texture * \brief Manages texture loading and properties. * - * The Texture class is responsible for loading an image from a source - * and providing access to its dimensions. Textures can be used for rendering. + * The Texture class is responsible for loading an image from a source and providing access to + * its dimensions. Textures can be used for rendering. */ class Texture { @@ -41,8 +40,7 @@ public: * \brief Destroys the Texture instance, freeing associated resources. */ ~Texture(); - // FIXME: this constructor shouldn't be necessary because this class doesn't - // manage memory + // FIXME: this constructor shouldn't be necessary because this class doesn't manage memory /** * \brief Gets the width of the texture. diff --git a/src/crepe/api/Transform.cpp b/src/crepe/api/Transform.cpp index e401120..cd944bd 100644 --- a/src/crepe/api/Transform.cpp +++ b/src/crepe/api/Transform.cpp @@ -1,11 +1,10 @@ -#include "util/log.h" +#include "../util/Log.h" #include "Transform.h" using namespace crepe; -Transform::Transform(game_object_id_t id, const Vector2 & point, - double rotation, double scale) +Transform::Transform(game_object_id_t id, const Vector2 & point, double rotation, double scale) : Component(id), position(point), rotation(rotation), diff --git a/src/crepe/api/Transform.h b/src/crepe/api/Transform.h index 756e45b..18aa293 100644 --- a/src/crepe/api/Transform.h +++ b/src/crepe/api/Transform.h @@ -9,33 +9,33 @@ namespace crepe { /** * \brief Transform component * - * This class represents the Transform component. It stores the position, - * rotation and scale of a GameObject. + * This class represents the Transform component. It stores the position, rotation and scale of + * a GameObject. */ class Transform : public Component { public: + //! Translation (shift) + Vector2 position = {0, 0}; + //! Rotation, in degrees + double rotation = 0; + //! Multiplication factor + double scale = 0; + +protected: /** * \param id The id of the GameObject this component belongs to * \param point The position of the GameObject * \param rotation The rotation of the GameObject * \param scale The scale of the GameObject */ - Transform(game_object_id_t id, const Vector2 & point, double rotation, - double scale); + Transform(game_object_id_t id, const Vector2 & point, double rotation, double scale); /** - * \brief Get the maximum number of instances for this component - * - * \return The maximum number of instances for this component + * There is always exactly one transform component per entity + * \return 1 */ virtual int get_instances_max() const { return 1; } - -public: - //! Translation (shift) - Vector2 position; - //! Rotation, in degrees - double rotation; - //! Multiplication factor - double scale; + //! ComponentManager instantiates all components + friend class ComponentManager; }; } // namespace crepe diff --git a/src/crepe/api/Vector2.cpp b/src/crepe/api/Vector2.cpp index 09b3fa3..30b968e 100644 --- a/src/crepe/api/Vector2.cpp +++ b/src/crepe/api/Vector2.cpp @@ -1,57 +1,33 @@ #include "Vector2.h" -namespace crepe { +using namespace crepe; -// Constructor with initial values -Vector2::Vector2(double x, double y) : x(x), y(y) {} +Vector2 Vector2::operator-(const Vector2 & other) const { return {x - other.x, y - other.y}; } -// Subtracts another vector from this vector and returns the result. -Vector2 Vector2::operator-(const Vector2 & other) const { - return {x - other.x, y - other.y}; -} - -// Adds another vector to this vector and returns the result. -Vector2 Vector2::operator+(const Vector2 & other) const { - return {x + other.x, y + other.y}; -} +Vector2 Vector2::operator+(const Vector2 & other) const { return {x + other.x, y + other.y}; } -// Multiplies this vector by a scalar and returns the result. -Vector2 Vector2::operator*(double scalar) const { - return {x * scalar, y * scalar}; -} +Vector2 Vector2::operator*(double scalar) const { return {x * scalar, y * scalar}; } -// Multiplies this vector by another vector element-wise and updates this vector. Vector2 & Vector2::operator*=(const Vector2 & other) { x *= other.x; y *= other.y; return *this; } -// Adds another vector to this vector and updates this vector. Vector2 & Vector2::operator+=(const Vector2 & other) { x += other.x; y += other.y; return *this; } -// Adds a scalar value to both components of this vector and updates this vector. Vector2 & Vector2::operator+=(double other) { x += other; y += other; return *this; } -// Returns the negation of this vector. Vector2 Vector2::operator-() const { return {-x, -y}; } -// Checks if this vector is equal to another vector. -bool Vector2::operator==(const Vector2 & other) const { - return x == other.x && y == other.y; -} - -// Checks if this vector is not equal to another vector. -bool Vector2::operator!=(const Vector2 & other) const { - return !(*this == other); -} +bool Vector2::operator==(const Vector2 & other) const { return x == other.x && y == other.y; } -} // namespace crepe +bool Vector2::operator!=(const Vector2 & other) const { return !(*this == other); } diff --git a/src/crepe/api/Vector2.h b/src/crepe/api/Vector2.h index 5a57484..2fb6136 100644 --- a/src/crepe/api/Vector2.h +++ b/src/crepe/api/Vector2.h @@ -2,19 +2,12 @@ namespace crepe { -//! Vector2 class -class Vector2 { -public: +//! 2D vector +struct Vector2 { //! X component of the vector - double x; + double x = 0; //! Y component of the vector - double y; - - //! Default constructor - Vector2() = default; - - //! Constructor with initial values - Vector2(double x, double y); + double y = 0; //! Subtracts another vector from this vector and returns the result. Vector2 operator-(const Vector2 & other) const; diff --git a/src/crepe/facade/DB.cpp b/src/crepe/facade/DB.cpp index 0a2f455..d5d19dc 100644 --- a/src/crepe/facade/DB.cpp +++ b/src/crepe/facade/DB.cpp @@ -1,7 +1,6 @@ #include <cstring> -#include "Exception.h" -#include "util/log.h" +#include "util/Log.h" #include "DB.h" @@ -15,19 +14,18 @@ DB::DB(const string & path) { // init database struct libdb::DB * db; if ((ret = libdb::db_create(&db, NULL, 0)) != 0) - throw Exception("db_create: %s", libdb::db_strerror(ret)); + throw runtime_error(format("db_create: {}", libdb::db_strerror(ret))); this->db = {db, [](libdb::DB * db) { db->close(db, 0); }}; // load or create database file - if ((ret = this->db->open(this->db.get(), NULL, path.c_str(), NULL, - libdb::DB_BTREE, DB_CREATE, 0)) - != 0) - throw Exception("db->open: %s", libdb::db_strerror(ret)); + ret = this->db->open(this->db.get(), NULL, path.c_str(), NULL, libdb::DB_BTREE, DB_CREATE, + 0); + if (ret != 0) throw runtime_error(format("db->open: {}", libdb::db_strerror(ret))); // create cursor libdb::DBC * cursor; - if ((ret = this->db->cursor(this->db.get(), NULL, &cursor, 0)) != 0) - throw Exception("db->cursor: %s", libdb::db_strerror(ret)); + ret = this->db->cursor(this->db.get(), NULL, &cursor, 0); + if (ret != 0) throw runtime_error(format("db->cursor: {}", libdb::db_strerror(ret))); this->cursor = {cursor, [](libdb::DBC * cursor) { cursor->close(cursor); }}; } @@ -45,21 +43,24 @@ string DB::get(const string & key) { memset(&db_val, 0, sizeof(libdb::DBT)); int ret = this->cursor->get(this->cursor.get(), &db_key, &db_val, DB_FIRST); - if (ret != 0) throw Exception("cursor->get: %s", libdb::db_strerror(ret)); - return {static_cast<char *>(db_val.data), db_val.size}; + if (ret == 0) return {static_cast<char *>(db_val.data), db_val.size}; + + string err = format("cursor->get: {}", libdb::db_strerror(ret)); + if (ret == DB_NOTFOUND) throw out_of_range(err); + else throw runtime_error(err); } void DB::set(const string & key, const string & value) { libdb::DBT db_key = this->to_thing(key); libdb::DBT db_val = this->to_thing(value); int ret = this->db->put(this->db.get(), NULL, &db_key, &db_val, 0); - if (ret != 0) throw Exception("cursor->get: %s", libdb::db_strerror(ret)); + if (ret != 0) throw runtime_error(format("cursor->get: {}", libdb::db_strerror(ret))); } -bool DB::has(const std::string & key) noexcept { +bool DB::has(const std::string & key) { try { this->get(key); - } catch (...) { + } catch (std::out_of_range &) { return false; } return true; diff --git a/src/crepe/facade/DB.h b/src/crepe/facade/DB.h index 7c757a2..629b0eb 100644 --- a/src/crepe/facade/DB.h +++ b/src/crepe/facade/DB.h @@ -15,8 +15,8 @@ namespace crepe { /** * \brief Berkeley DB facade * - * Berkeley DB is a simple key-value database that stores arbitrary data as - * both key and value. This facade uses STL strings as keys/values. + * Berkeley DB is a simple key-value database that stores arbitrary data as both key and value. + * This facade uses STL strings as keys/values. */ class DB { public: @@ -34,7 +34,8 @@ public: * * \return The value * - * \throws Exception if value is not found in DB or other error occurs + * \throws std::out_of_range if value is not found in DB + * \throws std::runtime_error if other error occurs */ std::string get(const std::string & key); /** @@ -43,7 +44,7 @@ public: * \param key The value key * \param value The value to store * - * \throws Exception if an error occurs + * \throws std::runtime_error if an error occurs */ void set(const std::string & key, const std::string & value); /** @@ -53,7 +54,7 @@ public: * * \returns True if the key exists, or false if it does not */ - bool has(const std::string & key) noexcept; + bool has(const std::string & key); private: //! RAII wrapper around \c DB struct diff --git a/src/crepe/facade/SDLContext.cpp b/src/crepe/facade/SDLContext.cpp index febbe4b..40189f6 100644 --- a/src/crepe/facade/SDLContext.cpp +++ b/src/crepe/facade/SDLContext.cpp @@ -14,12 +14,12 @@ #include "../api/Sprite.h" #include "../api/Texture.h" #include "../api/Transform.h" -#include "../util/log.h" -#include "Exception.h" +#include "../util/Log.h" #include "SDLContext.h" using namespace crepe; +using namespace std; SDLContext & SDLContext::get_instance() { static SDLContext instance; @@ -33,26 +33,22 @@ SDLContext::SDLContext() { if (SDL_Init(SDL_INIT_VIDEO) < 0) { throw std::runtime_error("SDL could not initialize!"); } - - SDL_Window * tmp_window = SDL_CreateWindow( - "Crepe Game Engine", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, - this->viewport.w, this->viewport.h, 0); + SDL_Window * tmp_window + = SDL_CreateWindow("Crepe Game Engine", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, + this->viewport.w, this->viewport.h, 0); if (!tmp_window) { throw std::runtime_error("Window could not be created!"); } + this->game_window = {tmp_window, [](SDL_Window * window) { SDL_DestroyWindow(window); }}; - this->game_window - = {tmp_window, [](SDL_Window * window) { SDL_DestroyWindow(window); }}; - - SDL_Renderer * tmp_renderer = SDL_CreateRenderer( - this->game_window.get(), -1, SDL_RENDERER_ACCELERATED); + SDL_Renderer * tmp_renderer + = SDL_CreateRenderer(this->game_window.get(), -1, SDL_RENDERER_ACCELERATED); if (!tmp_renderer) { throw std::runtime_error("Renderer could not be created!"); } - this->game_renderer = {tmp_renderer, [](SDL_Renderer * renderer) { - SDL_DestroyRenderer(renderer); - }}; + this->game_renderer + = {tmp_renderer, [](SDL_Renderer * renderer) { SDL_DestroyRenderer(renderer); }}; int img_flags = IMG_INIT_PNG; if (!(IMG_Init(img_flags) & img_flags)) { @@ -95,12 +91,9 @@ void SDLContext::handle_events(bool & running) { } void SDLContext::clear_screen() { SDL_RenderClear(this->game_renderer.get()); } -void SDLContext::present_screen() { - SDL_RenderPresent(this->game_renderer.get()); -} +void SDLContext::present_screen() { SDL_RenderPresent(this->game_renderer.get()); } -void SDLContext::draw(const Sprite & sprite, const Transform & transform, - const Camera & cam) { +void SDLContext::draw(const Sprite & sprite, const Transform & transform, const Camera & cam) { SDL_RendererFlip render_flip = (SDL_RendererFlip) ((SDL_FLIP_HORIZONTAL * sprite.flip.flip_x) @@ -125,9 +118,7 @@ void SDLContext::draw(const Sprite & sprite, const Transform & transform, .h = static_cast<int>(adjusted_h), }; - SDL_RenderCopyEx(this->game_renderer.get(), - sprite.sprite_image->texture.get(), &srcrect, - + SDL_RenderCopyEx(this->game_renderer.get(), sprite.sprite_image->texture.get(), &srcrect, &dstrect, transform.rotation, NULL, render_flip); } @@ -137,8 +128,8 @@ void SDLContext::camera(const Camera & cam) { this->viewport.x = static_cast<int>(cam.x) - (this->viewport.w / 2); this->viewport.y = static_cast<int>(cam.y) - (this->viewport.h / 2); - SDL_SetRenderDrawColor(this->game_renderer.get(), cam.bg_color.r, - cam.bg_color.g, cam.bg_color.b, cam.bg_color.a); + SDL_SetRenderDrawColor(this->game_renderer.get(), cam.bg_color.r, cam.bg_color.g, + cam.bg_color.b, cam.bg_color.a); } uint64_t SDLContext::get_ticks() const { return SDL_GetTicks64(); } @@ -151,22 +142,18 @@ SDLContext::texture_from_path(const std::string & path) { tmp = IMG_Load("../asset/texture/ERROR.png"); } - std::unique_ptr<SDL_Surface, std::function<void(SDL_Surface *)>> - img_surface; - img_surface - = {tmp, [](SDL_Surface * surface) { SDL_FreeSurface(surface); }}; + std::unique_ptr<SDL_Surface, std::function<void(SDL_Surface *)>> img_surface; + img_surface = {tmp, [](SDL_Surface * surface) { SDL_FreeSurface(surface); }}; - SDL_Texture * tmp_texture = SDL_CreateTextureFromSurface( - this->game_renderer.get(), img_surface.get()); + SDL_Texture * tmp_texture + = SDL_CreateTextureFromSurface(this->game_renderer.get(), img_surface.get()); if (tmp_texture == nullptr) { - throw Exception("Texture cannot be load from %s", path.c_str()); + throw runtime_error(format("Texture cannot be load from {}", path)); } - std::unique_ptr<SDL_Texture, std::function<void(SDL_Texture *)>> - img_texture; - img_texture = {tmp_texture, - [](SDL_Texture * texture) { SDL_DestroyTexture(texture); }}; + std::unique_ptr<SDL_Texture, std::function<void(SDL_Texture *)>> img_texture; + img_texture = {tmp_texture, [](SDL_Texture * texture) { SDL_DestroyTexture(texture); }}; return img_texture; } diff --git a/src/crepe/facade/SDLContext.h b/src/crepe/facade/SDLContext.h index 0614036..78ac56b 100644 --- a/src/crepe/facade/SDLContext.h +++ b/src/crepe/facade/SDLContext.h @@ -13,9 +13,8 @@ namespace crepe { -// TODO: SDL_Keycode is defined in a header not distributed with crepe, which -// means this typedef is unusable when crepe is packaged. Wouter will fix this -// later. +// TODO: SDL_Keycode is defined in a header not distributed with crepe, which means this +// typedef is unusable when crepe is packaged. Wouter will fix this later. typedef SDL_Keycode CREPE_KEYCODES; class Texture; @@ -25,8 +24,8 @@ class LoopManager; * \class SDLContext * \brief Facade for the SDL library * - * SDLContext is a singleton that handles the SDL window and renderer, provides methods - * for event handling, and rendering to the screen. It is never used directly by the user + * SDLContext is a singleton that handles the SDL window and renderer, provides methods for + * event handling, and rendering to the screen. It is never used directly by the user */ class SDLContext { @@ -64,9 +63,8 @@ private: /** * \brief Pauses the execution for a specified duration. * - * This function uses SDL's delay function to halt the program execution - * for a given number of milliseconds, allowing for frame rate control - * or other timing-related functionality. + * This function uses SDL's delay function to halt the program execution for a given number + * of milliseconds, allowing for frame rate control or other timing-related functionality. * * \param ms Duration of the delay in milliseconds. */ @@ -123,8 +121,7 @@ private: * \param transform Reference to the Transform for positioning. * \param camera Reference to the Camera for view adjustments. */ - void draw(const Sprite & sprite, const Transform & transform, - const Camera & camera); + void draw(const Sprite & sprite, const Transform & transform, const Camera & camera); void draw_particle(const Vector2 & pos, const Camera & camera); @@ -145,8 +142,7 @@ private: std::unique_ptr<SDL_Window, std::function<void(SDL_Window *)>> game_window; //! renderer for the crepe engine - std::unique_ptr<SDL_Renderer, std::function<void(SDL_Renderer *)>> - game_renderer; + std::unique_ptr<SDL_Renderer, std::function<void(SDL_Renderer *)>> game_renderer; //! viewport for the camera window SDL_Rect viewport = {0, 0, 640, 480}; diff --git a/src/crepe/facade/Sound.cpp b/src/crepe/facade/Sound.cpp index 648ec81..7aa89a9 100644 --- a/src/crepe/facade/Sound.cpp +++ b/src/crepe/facade/Sound.cpp @@ -1,23 +1,22 @@ -#include "../util/log.h" +#include "../util/Log.h" #include "Sound.h" #include "SoundContext.h" using namespace crepe; +using namespace std; -Sound::Sound(std::unique_ptr<Asset> res) { +Sound::Sound(unique_ptr<Asset> res) { dbg_trace(); this->load(std::move(res)); } Sound::Sound(const char * src) { dbg_trace(); - this->load(std::make_unique<Asset>(src)); + this->load(make_unique<Asset>(src)); } -void Sound::load(std::unique_ptr<Asset> res) { - this->sample.load(res->canonical()); -} +void Sound::load(unique_ptr<Asset> res) { this->sample.load(res->get_canonical().c_str()); } void Sound::play() { SoundContext & ctx = SoundContext::get_instance(); diff --git a/src/crepe/facade/Sound.h b/src/crepe/facade/Sound.h index 183bd7c..32b6478 100644 --- a/src/crepe/facade/Sound.h +++ b/src/crepe/facade/Sound.h @@ -8,34 +8,37 @@ namespace crepe { +/** + * \brief Sound resource facade + * + * This class is a wrapper around a \c SoLoud::Wav instance, which holds a + * single sample. It is part of the sound facade. + */ class Sound { public: /** * \brief Pause this sample * - * Pauses this sound if it is playing, or does nothing if it is already - * paused. The playhead position is saved, such that calling \c play() after - * this function makes the sound resume. + * Pauses this sound if it is playing, or does nothing if it is already paused. The playhead + * position is saved, such that calling \c play() after this function makes the sound resume. */ void pause(); /** * \brief Play this sample * - * Resume playback if this sound is paused, or start from the beginning of - * the sample. + * Resume playback if this sound is paused, or start from the beginning of the sample. * - * \note This class only saves a reference to the most recent 'voice' of this - * sound. Calling \c play() while the sound is already playing causes - * multiple instances of the sample to play simultaniously. The sample - * started last is the one that is controlled afterwards. + * \note This class only saves a reference to the most recent 'voice' of this sound. Calling + * \c play() while the sound is already playing causes multiple instances of the sample to + * play simultaniously. The sample started last is the one that is controlled afterwards. */ void play(); /** * \brief Reset playhead position * - * Resets the playhead position so that calling \c play() after this function - * makes it play from the start of the sample. If the sound is not paused - * before calling this function, this function will stop playback. + * Resets the playhead position so that calling \c play() after this function makes it play + * from the start of the sample. If the sound is not paused before calling this function, + * this function will stop playback. */ void rewind(); /** diff --git a/src/crepe/facade/SoundContext.cpp b/src/crepe/facade/SoundContext.cpp index 5e5a3a9..deb2b62 100644 --- a/src/crepe/facade/SoundContext.cpp +++ b/src/crepe/facade/SoundContext.cpp @@ -1,4 +1,4 @@ -#include "../util/log.h" +#include "../util/Log.h" #include "SoundContext.h" diff --git a/src/crepe/facade/SoundContext.h b/src/crepe/facade/SoundContext.h index d3123d2..d703c16 100644 --- a/src/crepe/facade/SoundContext.h +++ b/src/crepe/facade/SoundContext.h @@ -6,19 +6,24 @@ namespace crepe { +/** + * \brief Sound engine facade + * + * This class is a wrapper around a \c SoLoud::Soloud instance, which provides + * the methods for playing \c Sound instances. It is part of the sound facade. + */ class SoundContext { private: + // singleton SoundContext(); virtual ~SoundContext(); - - // singleton - static SoundContext & get_instance(); SoundContext(const SoundContext &) = delete; SoundContext(SoundContext &&) = delete; SoundContext & operator=(const SoundContext &) = delete; SoundContext & operator=(SoundContext &&) = delete; private: + static SoundContext & get_instance(); SoLoud::Soloud engine; friend class Sound; }; diff --git a/src/crepe/system/AnimatorSystem.cpp b/src/crepe/system/AnimatorSystem.cpp index bf45362..9d18873 100644 --- a/src/crepe/system/AnimatorSystem.cpp +++ b/src/crepe/system/AnimatorSystem.cpp @@ -1,27 +1,17 @@ - #include <cstdint> #include <functional> #include <vector> #include "api/Animator.h" #include "facade/SDLContext.h" -#include "util/log.h" #include "AnimatorSystem.h" #include "ComponentManager.h" using namespace crepe; -AnimatorSystem::AnimatorSystem() { dbg_trace(); } -AnimatorSystem::~AnimatorSystem() { dbg_trace(); } - -AnimatorSystem & AnimatorSystem::get_instance() { - static AnimatorSystem instance; - return instance; -} - void AnimatorSystem::update() { - ComponentManager & mgr = ComponentManager::get_instance(); + ComponentManager & mgr = this->component_manager; std::vector<std::reference_wrapper<Animator>> animations = mgr.get_components_by_type<Animator>(); diff --git a/src/crepe/system/AnimatorSystem.h b/src/crepe/system/AnimatorSystem.h index 969e9d1..56cc7b3 100644 --- a/src/crepe/system/AnimatorSystem.h +++ b/src/crepe/system/AnimatorSystem.h @@ -17,28 +17,16 @@ namespace crepe { class AnimatorSystem : public System { public: - /** - * \brief Retrieves the singleton instance of the AnimatorSystem. - * - * \return A reference to the single instance of the AnimatorSystem. - * - * This method ensures that there is only one instance of the AnimatorSystem, following the - * singleton design pattern. It can be used to access the system globally. - */ - static AnimatorSystem & get_instance(); - + using System::System; /** * \brief Updates the Animator components. * * This method is called periodically (likely every frame) to update the state of all - * Animator components, moving the animations forward and managing their behavior (e.g., looping). + * Animator components, moving the animations forward and managing their behavior (e.g., + * looping). */ void update() override; - -private: - // private because singleton - AnimatorSystem(); // dbg_trace - ~AnimatorSystem(); // dbg_trace + // FIXME: never say "likely" in the documentation lmao }; } // namespace crepe diff --git a/src/crepe/system/CMakeLists.txt b/src/crepe/system/CMakeLists.txt index 4c18b87..d658b25 100644 --- a/src/crepe/system/CMakeLists.txt +++ b/src/crepe/system/CMakeLists.txt @@ -1,4 +1,5 @@ target_sources(crepe PUBLIC + System.cpp ParticleSystem.cpp ScriptSystem.cpp PhysicsSystem.cpp diff --git a/src/crepe/system/CollisionSystem.cpp b/src/crepe/system/CollisionSystem.cpp index 55e0fdc..c74ca1d 100644 --- a/src/crepe/system/CollisionSystem.cpp +++ b/src/crepe/system/CollisionSystem.cpp @@ -2,6 +2,4 @@ using namespace crepe; -CollisionSystem::CollisionSystem() {} - void CollisionSystem::update() {} diff --git a/src/crepe/system/CollisionSystem.h b/src/crepe/system/CollisionSystem.h index 1e9f1aa..c1a70d8 100644 --- a/src/crepe/system/CollisionSystem.h +++ b/src/crepe/system/CollisionSystem.h @@ -1,11 +1,13 @@ #pragma once +#include "System.h" + namespace crepe { -class CollisionSystem { +class CollisionSystem : public System { public: - CollisionSystem(); - void update(); + using System::System; + void update() override; }; } // namespace crepe diff --git a/src/crepe/system/ParticleSystem.cpp b/src/crepe/system/ParticleSystem.cpp index e7a3bec..7316309 100644 --- a/src/crepe/system/ParticleSystem.cpp +++ b/src/crepe/system/ParticleSystem.cpp @@ -13,20 +13,17 @@ using namespace crepe; void ParticleSystem::update() { // Get all emitters - ComponentManager & mgr = ComponentManager::get_instance(); + ComponentManager & mgr = this->component_manager; std::vector<std::reference_wrapper<ParticleEmitter>> emitters = mgr.get_components_by_type<ParticleEmitter>(); for (ParticleEmitter & emitter : emitters) { // Get transform linked to emitter const Transform & transform - = mgr.get_components_by_id<Transform>(emitter.game_object_id) - .front() - .get(); + = mgr.get_components_by_id<Transform>(emitter.game_object_id).front().get(); // Emit particles based on emission_rate - int updates - = calculate_update(this->update_count, emitter.data.emission_rate); + int updates = calculate_update(this->update_count, emitter.data.emission_rate); for (size_t i = 0; i < updates; i++) { emit_particle(emitter, transform); } @@ -45,8 +42,7 @@ void ParticleSystem::update() { this->update_count = (this->update_count + 1) % this->MAX_UPDATE_COUNT; } -void ParticleSystem::emit_particle(ParticleEmitter & emitter, - const Transform & transform) { +void ParticleSystem::emit_particle(ParticleEmitter & emitter, const Transform & transform) { constexpr double DEG_TO_RAD = M_PI / 180.0; Vector2 initial_position = emitter.data.position + transform.position; @@ -57,13 +53,13 @@ void ParticleSystem::emit_particle(ParticleEmitter & emitter, = generate_random_speed(emitter.data.min_speed, emitter.data.max_speed); double angle_radians = random_angle * DEG_TO_RAD; - Vector2 velocity = {random_speed * std::cos(angle_radians), - random_speed * std::sin(angle_radians)}; + Vector2 velocity + = {random_speed * std::cos(angle_radians), random_speed * std::sin(angle_radians)}; for (Particle & particle : emitter.data.particles) { if (!particle.active) { - particle.reset(emitter.data.end_lifespan, initial_position, - velocity, random_angle); + particle.reset(emitter.data.end_lifespan, initial_position, velocity, + random_angle); break; } } @@ -81,10 +77,8 @@ int ParticleSystem::calculate_update(int count, double emission) const { return static_cast<int>(emission); } -void ParticleSystem::check_bounds(ParticleEmitter & emitter, - const Transform & transform) { - Vector2 offset = emitter.data.boundary.offset + transform.position - + emitter.data.position; +void ParticleSystem::check_bounds(ParticleEmitter & emitter, const Transform & transform) { + Vector2 offset = emitter.data.boundary.offset + transform.position + emitter.data.position; double half_width = emitter.data.boundary.width / 2.0; double half_height = emitter.data.boundary.height / 2.0; @@ -95,8 +89,8 @@ void ParticleSystem::check_bounds(ParticleEmitter & emitter, for (Particle & particle : emitter.data.particles) { const Vector2 & position = particle.position; - bool within_bounds = (position.x >= LEFT && position.x <= RIGHT - && position.y >= TOP && position.y <= BOTTOM); + bool within_bounds = (position.x >= LEFT && position.x <= RIGHT && position.y >= TOP + && position.y <= BOTTOM); if (!within_bounds) { if (emitter.data.boundary.reset_on_exit) { @@ -112,30 +106,25 @@ void ParticleSystem::check_bounds(ParticleEmitter & emitter, } } -double ParticleSystem::generate_random_angle(double min_angle, - double max_angle) const { +double ParticleSystem::generate_random_angle(double min_angle, double max_angle) const { if (min_angle == max_angle) { return min_angle; } else if (min_angle < max_angle) { return min_angle - + static_cast<double>(std::rand() - % static_cast<int>(max_angle - min_angle)); + + static_cast<double>(std::rand() % static_cast<int>(max_angle - min_angle)); } else { double angle_offset = (360 - min_angle) + max_angle; - double random_angle = min_angle - + static_cast<double>( - std::rand() % static_cast<int>(angle_offset)); + double random_angle + = min_angle + static_cast<double>(std::rand() % static_cast<int>(angle_offset)); return (random_angle >= 360) ? random_angle - 360 : random_angle; } } -double ParticleSystem::generate_random_speed(double min_speed, - double max_speed) const { +double ParticleSystem::generate_random_speed(double min_speed, double max_speed) const { if (min_speed == max_speed) { return min_speed; } else { return min_speed - + static_cast<double>(std::rand() - % static_cast<int>(max_speed - min_speed)); + + static_cast<double>(std::rand() % static_cast<int>(max_speed - min_speed)); } } diff --git a/src/crepe/system/ParticleSystem.h b/src/crepe/system/ParticleSystem.h index d7ca148..c647284 100644 --- a/src/crepe/system/ParticleSystem.h +++ b/src/crepe/system/ParticleSystem.h @@ -5,66 +5,75 @@ #include "System.h" namespace crepe { + class ParticleEmitter; class Transform; + /** - * \brief ParticleSystem class responsible for managing particle emission, updates, and bounds checking. - */ + * \brief ParticleSystem class responsible for managing particle emission, updates, and bounds + * checking. + */ class ParticleSystem : public System { public: + using System::System; /** - * \brief Updates all particle emitters by emitting particles, updating particle states, and checking bounds. - */ + * \brief Updates all particle emitters by emitting particles, updating particle states, and + * checking bounds. + */ void update() override; private: /** - * \brief Emits a particle from the specified emitter based on its emission properties. - * - * \param emitter Reference to the ParticleEmitter. - * \param transform Const reference to the Transform component associated with the emitter. - */ + * \brief Emits a particle from the specified emitter based on its emission properties. + * + * \param emitter Reference to the ParticleEmitter. + * \param transform Const reference to the Transform component associated with the emitter. + */ void emit_particle(ParticleEmitter & emitter, const Transform & transform); /** - * \brief Calculates the number of times particles should be emitted based on emission rate and update count. - * - * \param count Current update count. - * \param emission Emission rate. - * \return The number of particles to emit. - */ + * \brief Calculates the number of times particles should be emitted based on emission rate + * and update count. + * + * \param count Current update count. + * \param emission Emission rate. + * \return The number of particles to emit. + */ int calculate_update(int count, double emission) const; /** - * \brief Checks whether particles are within the emitter’s boundary, resets or stops particles if they exit. - * - * \param emitter Reference to the ParticleEmitter. - * \param transform Const reference to the Transform component associated with the emitter. - */ + * \brief Checks whether particles are within the emitter’s boundary, resets or stops + * particles if they exit. + * + * \param emitter Reference to the ParticleEmitter. + * \param transform Const reference to the Transform component associated with the emitter. + */ void check_bounds(ParticleEmitter & emitter, const Transform & transform); /** - * \brief Generates a random angle for particle emission within the specified range. - * - * \param min_angle Minimum emission angle in degrees. - * \param max_angle Maximum emission angle in degrees. - * \return Random angle in degrees. - */ + * \brief Generates a random angle for particle emission within the specified range. + * + * \param min_angle Minimum emission angle in degrees. + * \param max_angle Maximum emission angle in degrees. + * \return Random angle in degrees. + */ double generate_random_angle(double min_angle, double max_angle) const; /** - * \brief Generates a random speed for particle emission within the specified range. - * - * \param min_speed Minimum emission speed. - * \param max_speed Maximum emission speed. - * \return Random speed. - */ + * \brief Generates a random speed for particle emission within the specified range. + * + * \param min_speed Minimum emission speed. + * \param max_speed Maximum emission speed. + * \return Random speed. + */ double generate_random_speed(double min_speed, double max_speed) const; private: - //! Counter to count updates to determine how many times emit_particle is called. + //! Counter to count updates to determine how many times emit_particle is + // called. unsigned int update_count = 0; - //! Determines the lowest amount of emission rate (1000 = 0.001 = 1 particle per 1000 updates). + //! Determines the lowest amount of emission rate (1000 = 0.001 = 1 particle per 1000 + // updates). static constexpr unsigned int MAX_UPDATE_COUNT = 100; }; diff --git a/src/crepe/system/PhysicsSystem.cpp b/src/crepe/system/PhysicsSystem.cpp index eb54ad3..4a7dbfb 100644 --- a/src/crepe/system/PhysicsSystem.cpp +++ b/src/crepe/system/PhysicsSystem.cpp @@ -11,7 +11,7 @@ using namespace crepe; void PhysicsSystem::update() { - ComponentManager & mgr = ComponentManager::get_instance(); + ComponentManager & mgr = this->component_manager; std::vector<std::reference_wrapper<Rigidbody>> rigidbodies = mgr.get_components_by_type<Rigidbody>(); std::vector<std::reference_wrapper<Transform>> transforms @@ -29,17 +29,15 @@ void PhysicsSystem::update() { // Add gravity if (rigidbody.data.use_gravity) { rigidbody.data.linear_velocity.y - += (rigidbody.data.mass - * rigidbody.data.gravity_scale * gravity); + += (rigidbody.data.mass * rigidbody.data.gravity_scale + * gravity); } // Add damping if (rigidbody.data.angular_damping != 0) { - rigidbody.data.angular_velocity - *= rigidbody.data.angular_damping; + rigidbody.data.angular_velocity *= rigidbody.data.angular_damping; } if (rigidbody.data.linear_damping != Vector2{0, 0}) { - rigidbody.data.linear_velocity - *= rigidbody.data.linear_damping; + rigidbody.data.linear_velocity *= rigidbody.data.linear_damping; } // Max velocity check @@ -75,21 +73,17 @@ void PhysicsSystem::update() { // Move object if (!rigidbody.data.constraints.rotation) { - transform.rotation - += rigidbody.data.angular_velocity; - transform.rotation - = std::fmod(transform.rotation, 360.0); + transform.rotation += rigidbody.data.angular_velocity; + transform.rotation = std::fmod(transform.rotation, 360.0); if (transform.rotation < 0) { transform.rotation += 360.0; } } if (!rigidbody.data.constraints.x) { - transform.position.x - += rigidbody.data.linear_velocity.x; + transform.position.x += rigidbody.data.linear_velocity.x; } if (!rigidbody.data.constraints.y) { - transform.position.y - += rigidbody.data.linear_velocity.y; + transform.position.y += rigidbody.data.linear_velocity.y; } } } diff --git a/src/crepe/system/PhysicsSystem.h b/src/crepe/system/PhysicsSystem.h index 038c120..227ab69 100644 --- a/src/crepe/system/PhysicsSystem.h +++ b/src/crepe/system/PhysicsSystem.h @@ -3,14 +3,16 @@ #include "System.h" namespace crepe { + /** * \brief System that controls all physics * - * This class is a physics system that uses a rigidbody and transform - * to add physics to a game object. + * This class is a physics system that uses a rigidbody and transform to add physics to a game + * object. */ class PhysicsSystem : public System { public: + using System::System; /** * \brief updates the physics system. * diff --git a/src/crepe/system/RenderSystem.cpp b/src/crepe/system/RenderSystem.cpp index 6ecd604..23ab738 100644 --- a/src/crepe/system/RenderSystem.cpp +++ b/src/crepe/system/RenderSystem.cpp @@ -15,27 +15,13 @@ using namespace crepe; -RenderSystem::RenderSystem() { dbg_trace(); } +void RenderSystem::clear_screen() const { SDLContext::get_instance().clear_screen(); } -RenderSystem::~RenderSystem() { dbg_trace(); } - -RenderSystem & RenderSystem::get_instance() { - static RenderSystem instance; - return instance; -} - -void RenderSystem::clear_screen() const { - SDLContext::get_instance().clear_screen(); -} - -void RenderSystem::present_screen() const { - SDLContext::get_instance().present_screen(); -} +void RenderSystem::present_screen() const { SDLContext::get_instance().present_screen(); } void RenderSystem::update_camera() { - ComponentManager & mgr = ComponentManager::get_instance(); + ComponentManager & mgr = this->component_manager; - std::vector<std::reference_wrapper<Camera>> cameras - = mgr.get_components_by_type<Camera>(); + std::vector<std::reference_wrapper<Camera>> cameras = mgr.get_components_by_type<Camera>(); for (Camera & cam : cameras) { SDLContext::get_instance().camera(cam); diff --git a/src/crepe/system/RenderSystem.h b/src/crepe/system/RenderSystem.h index 3d6286f..ad44716 100644 --- a/src/crepe/system/RenderSystem.h +++ b/src/crepe/system/RenderSystem.h @@ -12,19 +12,13 @@ namespace crepe { * \class RenderSystem * \brief Manages rendering operations for all game objects. * - * RenderSystem is responsible for rendering sprites, clearing and presenting the screen, - * and managing the active camera. It functions as a singleton, providing centralized - * rendering services for the application. + * RenderSystem is responsible for rendering sprites, clearing and presenting the screen, and + * managing the active camera. It functions as a singleton, providing centralized rendering + * services for the application. */ class RenderSystem : public System { - public: - /** - * \brief Gets the singleton instance of RenderSystem. - * \return Reference to the RenderSystem instance. - */ - static RenderSystem & get_instance(); - + using System::System; /** * \brief Updates the RenderSystem for the current frame. * This method is called to perform all rendering operations for the current game frame. @@ -38,10 +32,6 @@ public: RenderSystem & operator=(RenderSystem &&) = delete; private: - // Private constructor to enforce singleton pattern. - RenderSystem(); - ~RenderSystem(); - //! Clears the screen in preparation for rendering. void clear_screen() const; @@ -85,4 +75,5 @@ private: Camera * curr_cam = nullptr; // TODO: needs a better solution }; + } // namespace crepe diff --git a/src/crepe/system/ScriptSystem.cpp b/src/crepe/system/ScriptSystem.cpp index f2673e7..c4d724c 100644 --- a/src/crepe/system/ScriptSystem.cpp +++ b/src/crepe/system/ScriptSystem.cpp @@ -5,7 +5,6 @@ #include "../ComponentManager.h" #include "../api/BehaviorScript.h" #include "../api/Script.h" -#include "../util/log.h" #include "ScriptSystem.h" @@ -13,16 +12,23 @@ using namespace std; using namespace crepe; void ScriptSystem::update() { - using namespace std; dbg_trace(); - forward_list<Script *> scripts = this->get_scripts(); - for (Script * script : scripts) script->update(); + forward_list<reference_wrapper<Script>> scripts = this->get_scripts(); + + for (auto & script_ref : scripts) { + Script & script = script_ref.get(); + if (!script.initialized) { + script.init(); + script.initialized = true; + } + script.update(); + } } -forward_list<Script *> ScriptSystem::get_scripts() { - forward_list<Script *> scripts = {}; - ComponentManager & mgr = ComponentManager::get_instance(); +forward_list<reference_wrapper<Script>> ScriptSystem::get_scripts() const { + forward_list<reference_wrapper<Script>> scripts = {}; + ComponentManager & mgr = this->component_manager; vector<reference_wrapper<BehaviorScript>> behavior_scripts = mgr.get_components_by_type<BehaviorScript>(); @@ -31,7 +37,7 @@ forward_list<Script *> ScriptSystem::get_scripts() { if (!behavior_script.active) continue; Script * script = behavior_script.script.get(); if (script == nullptr) continue; - scripts.push_front(script); + scripts.push_front(*script); } return scripts; diff --git a/src/crepe/system/ScriptSystem.h b/src/crepe/system/ScriptSystem.h index 4fa6141..deb89cb 100644 --- a/src/crepe/system/ScriptSystem.h +++ b/src/crepe/system/ScriptSystem.h @@ -8,13 +8,32 @@ namespace crepe { class Script; +/** + * \brief Script system + * + * The script system is responsible for all \c BehaviorScript components, and + * calls the methods on classes derived from \c Script. + */ class ScriptSystem : public System { public: - void update(); + using System::System; + /** + * \brief Call Script::update() on all active \c BehaviorScript instances + * + * This routine updates all scripts sequentially using the Script::update() + * method. It also calls Script::init() if this has not been done before on + * the \c BehaviorScript instance. + */ + void update() override; private: - // TODO: to forward_list<reference_wrapper> - std::forward_list<Script *> get_scripts(); + /** + * \brief Aggregate all active \c BehaviorScript components and return a list + * of references to their \c Script instances (utility) + * + * \returns List of active \c Script instances + */ + std::forward_list<std::reference_wrapper<Script>> get_scripts() const; }; } // namespace crepe diff --git a/src/crepe/system/System.cpp b/src/crepe/system/System.cpp new file mode 100644 index 0000000..937a423 --- /dev/null +++ b/src/crepe/system/System.cpp @@ -0,0 +1,7 @@ +#include "../util/Log.h" + +#include "System.h" + +using namespace crepe; + +System::System(ComponentManager & mgr) : component_manager(mgr) { dbg_trace(); } diff --git a/src/crepe/system/System.h b/src/crepe/system/System.h index 3b81bef..28ea20e 100644 --- a/src/crepe/system/System.h +++ b/src/crepe/system/System.h @@ -2,13 +2,28 @@ namespace crepe { +class ComponentManager; + +/** + * \brief Base ECS system class + * + * This class is used as the base for all system classes. Classes derived from + * System must implement the System::update() method and copy Script::Script + * with the `using`-syntax. + */ class System { public: + /** + * \brief Process all components this system is responsible for. + */ virtual void update() = 0; public: - System() = default; + System(ComponentManager &); virtual ~System() = default; + +protected: + ComponentManager & component_manager; }; } // namespace crepe diff --git a/src/crepe/util/CMakeLists.txt b/src/crepe/util/CMakeLists.txt index 0fa4343..4be738a 100644 --- a/src/crepe/util/CMakeLists.txt +++ b/src/crepe/util/CMakeLists.txt @@ -1,13 +1,12 @@ target_sources(crepe PUBLIC LogColor.cpp - log.cpp - fmt.cpp + Log.cpp ) target_sources(crepe PUBLIC FILE_SET HEADERS FILES LogColor.h - log.h - fmt.h + Log.h + Log.hpp Proxy.h Proxy.hpp ) diff --git a/src/crepe/util/Log.cpp b/src/crepe/util/Log.cpp new file mode 100644 index 0000000..84d80a8 --- /dev/null +++ b/src/crepe/util/Log.cpp @@ -0,0 +1,37 @@ +#include <iostream> +#include <string> + +#include "../api/Config.h" + +#include "Log.h" + +using namespace crepe; +using namespace std; + +string Log::prefix(const Level & level) { + switch (level) { + case Level::TRACE: + return LogColor().fg_white().str("[TRACE]") + " "; + case Level::DEBUG: + return LogColor().fg_magenta().str("[DEBUG]") + " "; + case Level::INFO: + return LogColor().fg_blue().str("[INFO]") + " "; + case Level::WARNING: + return LogColor().fg_yellow().str("[WARN]") + " "; + case Level::ERROR: + return LogColor().fg_red().str("[ERROR]") + " "; + } + return ""; +} + +void Log::log(const Level & level, const string & msg) { + auto & cfg = Config::get_instance(); + if (level < cfg.log.level) return; + + string out = Log::prefix(level) + msg; + if (!out.ends_with("\n")) out += "\n"; + + // TODO: also log to file or smth + cout.write(out.data(), out.size()); + cout.flush(); +} diff --git a/src/crepe/util/Log.h b/src/crepe/util/Log.h new file mode 100644 index 0000000..d55b11e --- /dev/null +++ b/src/crepe/util/Log.h @@ -0,0 +1,84 @@ +#pragma once + +#include <format> + +// allow user to disable debug macros +#ifndef CREPE_DISABLE_MACROS + +#include "LogColor.h" + +// utility macros +#define _crepe_logf_here(level, fmt, ...) \ + crepe::Log::logf(level, "{}" fmt, \ + crepe::LogColor().fg_white(false).str(std::format( \ + "{} ({}:{})", __PRETTY_FUNCTION__, __FILE_NAME__, __LINE__)), \ + __VA_ARGS__) + +// very illegal global function-style macros +// NOLINTBEGIN +#define dbg_logf(fmt, ...) _crepe_logf_here(crepe::Log::Level::DEBUG, ": " fmt, __VA_ARGS__) +#define dbg_log(str) _crepe_logf_here(crepe::Log::Level::DEBUG, ": {}", str) +#define dbg_trace() _crepe_logf_here(crepe::Log::Level::TRACE, "", "") +// NOLINTEND + +#endif + +namespace crepe { + +/** + * \brief Logging utility + * + * This class is used to output log messages to the console and/or log files. + */ +class Log { +public: + //! Log message severity + enum Level { + TRACE, //< Include (internal) function calls + DEBUG, //< Include dbg_logf output + INFO, //< General-purpose messages + WARNING, //< Non-fatal errors + ERROR, //< Fatal errors + }; + + /** + * \brief Log a formatted message + * + * \param level Message severity + * \param msg Formatted message + */ + static void log(const Level & level, const std::string & msg); + + /** + * \brief Format a message and log it + * + * \param level Message severity + * \param fmt Message format + * \param args Format arguments + */ + template <class... Args> + static void logf(const Level & level, std::format_string<Args...> fmt, Args &&... args); + + /** + * \brief Format a message and log it (with default severity \c INFO) + * + * \param fmt Message format + * \param args Format arguments + */ + template <class... Args> + static void logf(std::format_string<Args...> fmt, Args &&... args); + +private: + /** + * \brief Output a message prefix depending on the log level + * + * \param level Message severity + * + * \return Colored message severity prefix string + */ + static std::string prefix(const Level & level); +}; + +} // namespace crepe + +#include "Log.hpp" diff --git a/src/crepe/util/Log.hpp b/src/crepe/util/Log.hpp new file mode 100644 index 0000000..c2156cd --- /dev/null +++ b/src/crepe/util/Log.hpp @@ -0,0 +1,17 @@ +#pragma once + +#include "Log.h" + +namespace crepe { + +template <class... Args> +void Log::logf(std::format_string<Args...> fmt, Args &&... args) { + Log::logf(Level::INFO, fmt, std::forward<Args>(args)...); +} + +template <class... Args> +void Log::logf(const Level & level, std::format_string<Args...> fmt, Args &&... args) { + Log::log(level, std::format(fmt, std::forward<Args>(args)...)); +} + +} // namespace crepe diff --git a/src/crepe/util/LogColor.cpp b/src/crepe/util/LogColor.cpp index b5fe3ea..5411898 100644 --- a/src/crepe/util/LogColor.cpp +++ b/src/crepe/util/LogColor.cpp @@ -1,16 +1,15 @@ #include <cstdarg> #include "../api/Config.h" -#include "LogColor.h" -#include "fmt.h" +#include "LogColor.h" using namespace crepe; using namespace std; static constexpr const char * RESET_CODE = "\e[0m"; -const string LogColor::str(const string & content) { +const string LogColor::str(const string & content) const { auto & cfg = Config::get_instance(); string out = content; if (cfg.log.color) out = this->code + out; @@ -19,21 +18,8 @@ const string LogColor::str(const string & content) { return out; } -const char * LogColor::c_str(const char * content) { - this->final = this->str(content == NULL ? "" : content); - return this->final.c_str(); -} - -const char * LogColor::fmt(const char * fmt, ...) { - va_list args; - va_start(args, fmt); - string content = va_stringf(args, fmt); - va_end(args); - return this->c_str(content.c_str()); -} - LogColor & LogColor::add_code(unsigned int code) { - this->code += stringf("\e[%dm", code); + this->code += format("\e[{}m", code); return *this; } @@ -42,51 +28,19 @@ LogColor & LogColor::reset() { return *this; } -LogColor & LogColor::fg_black(bool bright) { - return this->add_code(bright ? 90 : 30); -} -LogColor & LogColor::fg_red(bool bright) { - return this->add_code(bright ? 91 : 31); -} -LogColor & LogColor::fg_green(bool bright) { - return this->add_code(bright ? 92 : 32); -} -LogColor & LogColor::fg_yellow(bool bright) { - return this->add_code(bright ? 93 : 33); -} -LogColor & LogColor::fg_blue(bool bright) { - return this->add_code(bright ? 94 : 34); -} -LogColor & LogColor::fg_magenta(bool bright) { - return this->add_code(bright ? 95 : 35); -} -LogColor & LogColor::fg_cyan(bool bright) { - return this->add_code(bright ? 96 : 36); -} -LogColor & LogColor::fg_white(bool bright) { - return this->add_code(bright ? 97 : 37); -} -LogColor & LogColor::bg_black(bool bright) { - return this->add_code(bright ? 100 : 40); -} -LogColor & LogColor::bg_red(bool bright) { - return this->add_code(bright ? 101 : 41); -} -LogColor & LogColor::bg_green(bool bright) { - return this->add_code(bright ? 102 : 42); -} -LogColor & LogColor::bg_yellow(bool bright) { - return this->add_code(bright ? 103 : 43); -} -LogColor & LogColor::bg_blue(bool bright) { - return this->add_code(bright ? 104 : 44); -} -LogColor & LogColor::bg_magenta(bool bright) { - return this->add_code(bright ? 105 : 45); -} -LogColor & LogColor::bg_cyan(bool bright) { - return this->add_code(bright ? 106 : 46); -} -LogColor & LogColor::bg_white(bool bright) { - return this->add_code(bright ? 107 : 47); -} +LogColor & LogColor::fg_black(bool bright) { return this->add_code(bright ? 90 : 30); } +LogColor & LogColor::fg_red(bool bright) { return this->add_code(bright ? 91 : 31); } +LogColor & LogColor::fg_green(bool bright) { return this->add_code(bright ? 92 : 32); } +LogColor & LogColor::fg_yellow(bool bright) { return this->add_code(bright ? 93 : 33); } +LogColor & LogColor::fg_blue(bool bright) { return this->add_code(bright ? 94 : 34); } +LogColor & LogColor::fg_magenta(bool bright) { return this->add_code(bright ? 95 : 35); } +LogColor & LogColor::fg_cyan(bool bright) { return this->add_code(bright ? 96 : 36); } +LogColor & LogColor::fg_white(bool bright) { return this->add_code(bright ? 97 : 37); } +LogColor & LogColor::bg_black(bool bright) { return this->add_code(bright ? 100 : 40); } +LogColor & LogColor::bg_red(bool bright) { return this->add_code(bright ? 101 : 41); } +LogColor & LogColor::bg_green(bool bright) { return this->add_code(bright ? 102 : 42); } +LogColor & LogColor::bg_yellow(bool bright) { return this->add_code(bright ? 103 : 43); } +LogColor & LogColor::bg_blue(bool bright) { return this->add_code(bright ? 104 : 44); } +LogColor & LogColor::bg_magenta(bool bright) { return this->add_code(bright ? 105 : 45); } +LogColor & LogColor::bg_cyan(bool bright) { return this->add_code(bright ? 106 : 46); } +LogColor & LogColor::bg_white(bool bright) { return this->add_code(bright ? 107 : 47); } diff --git a/src/crepe/util/LogColor.h b/src/crepe/util/LogColor.h index c1170cb..132fb94 100644 --- a/src/crepe/util/LogColor.h +++ b/src/crepe/util/LogColor.h @@ -4,23 +4,35 @@ namespace crepe { +/** + * \brief Utility class for coloring text using ANSI escape codes + * + * \note Most methods in this class return a reference to \c this, which may be + * used to chain multiple display attributes. + */ class LogColor { public: - LogColor() = default; + /** + * \brief Get color code as STL string + * + * \param content If given, color this string and append a color reset escape sequence. + * + * \returns Color escape sequence + */ + const std::string str(const std::string & content = "") const; public: - //! get color code as c-style string (or color content string) - const char * c_str(const char * content = NULL); - //! color printf-style format string - const char * fmt(const char * fmt, ...); - //! get color code as stl string (or color content string) - const std::string str(const std::string & content = ""); - -public: - //! reset color to default foreground and background color + //! Reset color to default foreground and background color LogColor & reset(); public: + /** + * \name Foreground colors + * + * These functions set the foreground (text) color. The \c bright parameter + * makes the color brighter, or bold on some terminals. + * \{ + */ LogColor & fg_black(bool bright = false); LogColor & fg_red(bool bright = false); LogColor & fg_green(bool bright = false); @@ -29,8 +41,16 @@ public: LogColor & fg_magenta(bool bright = false); LogColor & fg_cyan(bool bright = false); LogColor & fg_white(bool bright = false); + /// \} public: + /** + * \name Background colors + * + * These functions set the background color. The \c bright parameter makes + * the color brighter. + * \{ + */ LogColor & bg_black(bool bright = false); LogColor & bg_red(bool bright = false); LogColor & bg_green(bool bright = false); @@ -39,13 +59,22 @@ public: LogColor & bg_magenta(bool bright = false); LogColor & bg_cyan(bool bright = false); LogColor & bg_white(bool bright = false); + /// \} private: + /** + * \brief Append SGR escape sequence to \c this->code + * + * \param code SGR attribute number + * + * See <https://en.wikipedia.org/wiki/ANSI_escape_code> for magic number + * reference. + */ LogColor & add_code(unsigned int code); private: + //! Color escape sequence std::string code = ""; - std::string final = ""; }; } // namespace crepe diff --git a/src/crepe/util/Proxy.h b/src/crepe/util/Proxy.h index f84e462..b34f7c6 100644 --- a/src/crepe/util/Proxy.h +++ b/src/crepe/util/Proxy.h @@ -7,8 +7,8 @@ namespace crepe { /** * \brief Utility wrapper for \c ValueBroker * - * This class can be used to to wrap a ValueBroker instance so it behaves like - * a regular variable. + * This class can be used to to wrap a ValueBroker instance so it behaves like a regular + * variable. * * \tparam T Type of the underlying variable */ diff --git a/src/crepe/util/fmt.cpp b/src/crepe/util/fmt.cpp deleted file mode 100644 index 4b50da8..0000000 --- a/src/crepe/util/fmt.cpp +++ /dev/null @@ -1,35 +0,0 @@ -#include <cstdarg> -#include <cstdio> -#include <string> - -#include "fmt.h" - -using namespace std; - -string crepe::va_stringf(va_list args, const char * fmt) { - string out; - - va_list args_copy; - va_copy(args_copy, args); - size_t length = vsnprintf(NULL, 0, fmt, args_copy); - // resize to include terminating null byte - out.resize(length + 1); - va_end(args_copy); - - // vsnprintf adds terminating null byte - vsnprintf(out.data(), out.size(), fmt, args); - // resize to actual length - out.resize(length); - - va_end(args); - - return out; -} - -string crepe::stringf(const char * fmt, ...) { - va_list args; - va_start(args, fmt); - string out = va_stringf(args, fmt); - va_end(args); - return out; -} diff --git a/src/crepe/util/fmt.h b/src/crepe/util/fmt.h deleted file mode 100644 index e319e6e..0000000 --- a/src/crepe/util/fmt.h +++ /dev/null @@ -1,10 +0,0 @@ -#pragma once - -#include <string> - -namespace crepe { - -std::string va_stringf(va_list args, const char * fmt); -std::string stringf(const char * fmt, ...); - -} // namespace crepe diff --git a/src/crepe/util/log.cpp b/src/crepe/util/log.cpp deleted file mode 100644 index 4a8f8e8..0000000 --- a/src/crepe/util/log.cpp +++ /dev/null @@ -1,53 +0,0 @@ -#include <cstdarg> -#include <cstdio> -#include <cstdlib> -#include <string> - -#include "../api/Config.h" -#include "fmt.h" -#include "log.h" - -using namespace crepe; -using namespace std; - -string log_prefix(LogLevel level) { - switch (level) { - case LogLevel::TRACE: - return LogColor().fg_white().str("[TRACE]") + " "; - case LogLevel::DEBUG: - return LogColor().fg_magenta().str("[DEBUG]") + " "; - case LogLevel::INFO: - return LogColor().fg_blue().str("[INFO]") + " "; - case LogLevel::WARNING: - return LogColor().fg_yellow().str("[WARN]") + " "; - case LogLevel::ERROR: - return LogColor().fg_red().str("[ERROR]") + " "; - } - return ""; -} - -static void log(LogLevel level, const string msg) { - auto & cfg = Config::get_instance(); - if (level < cfg.log.level) return; - - string out = log_prefix(level) + msg; - if (!out.ends_with("\n")) out += "\n"; - - // TODO: also log to file or smth - fwrite(out.c_str(), 1, out.size(), stdout); - fflush(stdout); -} - -void crepe::logf(const char * fmt, ...) { - va_list args; - va_start(args, fmt); - log(LogLevel::DEBUG, va_stringf(args, fmt)); - va_end(args); -} - -void crepe::logf(LogLevel level, const char * fmt, ...) { - va_list args; - va_start(args, fmt); - log(level, va_stringf(args, fmt)); - va_end(args); -} diff --git a/src/crepe/util/log.h b/src/crepe/util/log.h deleted file mode 100644 index 5a1cf00..0000000 --- a/src/crepe/util/log.h +++ /dev/null @@ -1,39 +0,0 @@ -#pragma once - -// allow user to disable debug macros -#ifndef CREPE_DISABLE_MACROS - -#include "LogColor.h" - -// utility macros -#define _crepe_logf_here(level, format, ...) \ - crepe::logf( \ - level, "%s" format, \ - crepe::LogColor().fg_white(false).fmt( \ - "%s (%s:%d)", __PRETTY_FUNCTION__, __FILE_NAME__, __LINE__), \ - __VA_ARGS__) - -// very illegal global function-style macros -// NOLINTBEGIN -#define dbg_logf(fmt, ...) \ - _crepe_logf_here(crepe::LogLevel::DEBUG, ": " fmt, __VA_ARGS__) -#define dbg_log(str) _crepe_logf_here(crepe::LogLevel::DEBUG, "%s: " str, "") -#define dbg_trace() _crepe_logf_here(crepe::LogLevel::TRACE, "%s", "") -// NOLINTEND - -#endif - -namespace crepe { - -enum LogLevel { - TRACE, - DEBUG, - INFO, - WARNING, - ERROR, -}; - -void logf(const char * fmt, ...); -void logf(enum LogLevel level, const char * fmt, ...); - -} // namespace crepe diff --git a/src/example/asset_manager.cpp b/src/example/asset_manager.cpp index cf64f89..917b547 100644 --- a/src/example/asset_manager.cpp +++ b/src/example/asset_manager.cpp @@ -6,18 +6,17 @@ using namespace crepe; int main() { - // this needs to be called before the asset manager otherwise the destructor - // of sdl is not in the right order + // this needs to be called before the asset manager otherwise the destructor of sdl is not in + // the right order { Texture test("../asset/texture/img.png"); } - // FIXME: make it so the issue described by the above comment is not possible - // (i.e. the order in which internal classes are instantiated should not - // impact the way the engine works). + // FIXME: make it so the issue described by the above comment is not possible (i.e. the order + // in which internal classes are instantiated should not impact the way the engine works). auto & mgr = AssetManager::get_instance(); { - // TODO: [design] the Sound class can't be directly included by the user as - // it includes SoLoud headers. + // TODO: [design] the Sound class can't be directly included by the user as it includes + // SoLoud headers. auto bgm = mgr.cache<Sound>("../mwe/audio/bgm.ogg"); auto sfx1 = mgr.cache<Sound>("../mwe/audio/sfx1.wav"); auto sfx2 = mgr.cache<Sound>("../mwe/audio/sfx2.wav"); diff --git a/src/example/audio_internal.cpp b/src/example/audio_internal.cpp index 1ea839d..661161a 100644 --- a/src/example/audio_internal.cpp +++ b/src/example/audio_internal.cpp @@ -5,7 +5,7 @@ #include <crepe/api/Config.h> #include <crepe/facade/Sound.h> -#include <crepe/util/log.h> +#include <crepe/util/Log.h> #include <thread> @@ -18,7 +18,7 @@ using std::make_unique; int _ = []() { // Show dbg_trace() output auto & cfg = Config::get_instance(); - cfg.log.level = LogLevel::TRACE; + cfg.log.level = Log::Level::TRACE; return 0; // satisfy compiler }(); @@ -34,8 +34,7 @@ int main() { // Start the background track bgm.play(); - // Play each sample sequentially while pausing and resuming the background - // track + // Play each sample sequentially while pausing and resuming the background track this_thread::sleep_for(500ms); sfx1.play(); this_thread::sleep_for(500ms); diff --git a/src/example/components_internal.cpp b/src/example/components_internal.cpp index ea1eaad..2a232a9 100644 --- a/src/example/components_internal.cpp +++ b/src/example/components_internal.cpp @@ -13,7 +13,7 @@ #include <crepe/api/Rigidbody.h> #include <crepe/api/Sprite.h> -#include <crepe/util/log.h> +#include <crepe/util/Log.h> using namespace crepe; using namespace std; @@ -23,17 +23,14 @@ using namespace std; int main() { dbg_trace(); - auto & mgr = ComponentManager::get_instance(); + ComponentManager mgr{}; auto start_adding = chrono::high_resolution_clock::now(); - GameObject * game_object[OBJ_COUNT]; - for (int i = 0; i < OBJ_COUNT; ++i) { - game_object[i] = new GameObject(i, "Name", "Tag", 0); - - game_object[i]->add_component<Sprite>("test"); - game_object[i]->add_component<Rigidbody>(0, 0, i); + GameObject obj = mgr.new_object("Name", "Tag"); + obj.add_component<Sprite>("test"); + obj.add_component<Rigidbody>(0, 0, i); } auto stop_adding = chrono::high_resolution_clock::now(); @@ -45,14 +42,8 @@ int main() { auto stop_looping = chrono::high_resolution_clock::now(); - for (int i = 0; i < OBJ_COUNT; ++i) { - delete game_object[i]; - } - - auto add_time = chrono::duration_cast<chrono::microseconds>(stop_adding - - start_adding); - auto loop_time = chrono::duration_cast<chrono::microseconds>(stop_looping - - stop_adding); + auto add_time = chrono::duration_cast<chrono::microseconds>(stop_adding - start_adding); + auto loop_time = chrono::duration_cast<chrono::microseconds>(stop_looping - stop_adding); printf("add time: %ldus\n", add_time.count()); printf("loop time: %ldus\n", loop_time.count()); diff --git a/src/example/db.cpp b/src/example/db.cpp index 8c06a84..ee4e8fc 100644 --- a/src/example/db.cpp +++ b/src/example/db.cpp @@ -1,6 +1,6 @@ #include <crepe/api/Config.h> #include <crepe/facade/DB.h> -#include <crepe/util/log.h> +#include <crepe/util/Log.h> using namespace crepe; using namespace std; @@ -8,7 +8,7 @@ using namespace std; // run before main static auto _ = []() { auto & cfg = Config::get_instance(); - cfg.log.level = LogLevel::TRACE; + cfg.log.level = Log::Level::TRACE; return 0; }(); @@ -20,11 +20,11 @@ int main() { const char * test_key = "test-key"; string test_data = "Hello world!"; - dbg_logf("DB has key = %d", db.has(test_key)); + dbg_logf("DB has key = {}", db.has(test_key)); db.set(test_key, test_data); - dbg_logf("key = \"%s\"", db.get(test_key).c_str()); + dbg_logf("key = \"{}\"", db.get(test_key)); return 0; } diff --git a/src/example/ecs.cpp b/src/example/ecs.cpp index e61c398..d5ba51b 100644 --- a/src/example/ecs.cpp +++ b/src/example/ecs.cpp @@ -9,13 +9,15 @@ using namespace crepe; using namespace std; int main() { + ComponentManager mgr{}; + // Create a few GameObjects try { - GameObject body(0, "body", "person", Vector2{0, 0}, 0, 1); - GameObject right_leg(1, "rightLeg", "person", Vector2{1, 1}, 0, 1); - GameObject left_leg(2, "leftLeg", "person", Vector2{1, 1}, 0, 1); - GameObject right_foot(3, "rightFoot", "person", Vector2{2, 2}, 0, 1); - GameObject left_foot(4, "leftFoot", "person", Vector2{2, 2}, 0, 1); + GameObject body = mgr.new_object("body", "person", Vector2{0, 0}, 0, 1); + GameObject right_leg = mgr.new_object("rightLeg", "person", Vector2{1, 1}, 0, 1); + GameObject left_leg = mgr.new_object("leftLeg", "person", Vector2{1, 1}, 0, 1); + GameObject right_foot = mgr.new_object("rightFoot", "person", Vector2{2, 2}, 0, 1); + GameObject left_foot = mgr.new_object("leftFoot", "person", Vector2{2, 2}, 0, 1); // Set the parent of each GameObject right_foot.set_parent(right_leg); @@ -30,25 +32,21 @@ int main() { } // Get the Metadata and Transform components of each GameObject - ComponentManager & mgr = ComponentManager::get_instance(); - vector<reference_wrapper<Metadata>> metadata - = mgr.get_components_by_type<Metadata>(); - vector<reference_wrapper<Transform>> transform - = mgr.get_components_by_type<Transform>(); + vector<reference_wrapper<Metadata>> metadata = mgr.get_components_by_type<Metadata>(); + vector<reference_wrapper<Transform>> transform = mgr.get_components_by_type<Transform>(); // Print the Metadata and Transform components for (auto & m : metadata) { cout << "Id: " << m.get().game_object_id << " Name: " << m.get().name - << " Tag: " << m.get().tag << " Parent: " << m.get().parent - << " Children: "; + << " Tag: " << m.get().tag << " Parent: " << m.get().parent << " Children: "; for (auto & c : m.get().children) { cout << c << " "; } cout << endl; } for (auto & t : transform) { - cout << "Id: " << t.get().game_object_id << " Position: [" - << t.get().position.x << ", " << t.get().position.y << "]" << endl; + cout << "Id: " << t.get().game_object_id << " Position: [" << t.get().position.x + << ", " << t.get().position.y << "]" << endl; } return 0; diff --git a/src/example/log.cpp b/src/example/log.cpp index db8aa48..5baa021 100644 --- a/src/example/log.cpp +++ b/src/example/log.cpp @@ -4,7 +4,7 @@ */ #include <crepe/api/Config.h> -#include <crepe/util/log.h> +#include <crepe/util/Log.h> using namespace crepe; @@ -12,17 +12,17 @@ using namespace crepe; int _ = []() { // make sure all log messages get printed auto & cfg = Config::get_instance(); - cfg.log.level = LogLevel::TRACE; + cfg.log.level = Log::Level::TRACE; return 0; // satisfy compiler }(); int main() { dbg_trace(); - dbg_logf("test printf parameters: %d", 3); - logf(LogLevel::INFO, "info message"); - logf(LogLevel::WARNING, "warning"); - logf(LogLevel::ERROR, "error"); + dbg_log("debug message"); + Log::logf("info message with variable: {}", 3); + Log::logf(Log::Level::WARNING, "warning"); + Log::logf(Log::Level::ERROR, "error"); return 0; } diff --git a/src/example/particles.cpp b/src/example/particles.cpp index 6eab046..3d5f676 100644 --- a/src/example/particles.cpp +++ b/src/example/particles.cpp @@ -14,11 +14,11 @@ using namespace crepe; using namespace std; int main(int argc, char * argv[]) { - GameObject game_object(0, "", "", Vector2{0, 0}, 0, 0); + ComponentManager mgr{}; + GameObject game_object = mgr.new_object("", "", Vector2{0, 0}, 0, 0); Color color(0, 0, 0, 0); Sprite test_sprite = game_object.add_component<Sprite>( - make_shared<Texture>("../asset/texture/img.png"), color, - FlipSettings{true, true}); + make_shared<Texture>("../asset/texture/img.png"), color, FlipSettings{true, true}); game_object.add_component<ParticleEmitter>(ParticleEmitter::Data{ .position = {0, 0}, .max_particles = 100, diff --git a/src/example/physics.cpp b/src/example/physics.cpp index 848f857..ad663a0 100644 --- a/src/example/physics.cpp +++ b/src/example/physics.cpp @@ -9,9 +9,10 @@ using namespace crepe; using namespace std; int main(int argc, char * argv[]) { - GameObject * game_object; - game_object = new GameObject(0, "Name", "Tag", Vector2{0, 0}, 0, 0); - game_object->add_component<Rigidbody>(Rigidbody::Data{ + ComponentManager mgr{}; + + GameObject game_object = mgr.new_object("Name", "Tag", Vector2{0, 0}, 0, 0); + game_object.add_component<Rigidbody>(Rigidbody::Data{ .mass = 1, .gravity_scale = 1, .body_type = Rigidbody::BodyType::DYNAMIC, @@ -19,6 +20,5 @@ int main(int argc, char * argv[]) { .use_gravity = true, .bounce = false, }); - delete game_object; return 0; } diff --git a/src/example/proxy.cpp b/src/example/proxy.cpp index 0afff41..69451f8 100644 --- a/src/example/proxy.cpp +++ b/src/example/proxy.cpp @@ -5,8 +5,8 @@ #include <crepe/ValueBroker.h> #include <crepe/api/Config.h> +#include <crepe/util/Log.h> #include <crepe/util/Proxy.h> -#include <crepe/util/log.h> using namespace std; using namespace crepe; @@ -17,18 +17,17 @@ void test_ro_val(int val) {} int main() { auto & cfg = Config::get_instance(); - cfg.log.level = LogLevel::DEBUG; + cfg.log.level = Log::Level::DEBUG; int real_value = 0; ValueBroker<int> broker{ [&real_value](const int & target) { - dbg_logf("set %s to %s", to_string(real_value).c_str(), - to_string(target).c_str()); + dbg_logf("set {} to {}", real_value, target); real_value = target; }, [&real_value]() -> const int & { - dbg_logf("get %s", to_string(real_value).c_str()); + dbg_logf("get {}", real_value); return real_value; }, }; diff --git a/src/example/rendering.cpp b/src/example/rendering.cpp index 827ad07..c9e62f1 100644 --- a/src/example/rendering.cpp +++ b/src/example/rendering.cpp @@ -2,7 +2,7 @@ #include <crepe/ComponentManager.h> #include <crepe/api/GameObject.h> #include <crepe/system/RenderSystem.h> -#include <crepe/util/log.h> +#include <crepe/util/Log.h> #include <crepe/api/AssetManager.h> #include <crepe/api/Color.h> @@ -20,23 +20,24 @@ using namespace crepe; int main() { dbg_trace(); - auto obj = GameObject(0, "name", "tag", Vector2{0, 0}, 1, 1); - auto obj1 = GameObject(1, "name", "tag", Vector2{500, 0}, 1, 0.1); - auto obj2 = GameObject(2, "name", "tag", Vector2{800, 0}, 1, 0.1); + ComponentManager mgr{}; + RenderSystem sys{mgr}; + + GameObject obj = mgr.new_object("name", "tag", Vector2{0, 0}, 1, 1); + GameObject obj1 = mgr.new_object("name", "tag", Vector2{500, 0}, 1, 0.1); + GameObject obj2 = mgr.new_object("name", "tag", Vector2{800, 0}, 1, 0.1); // Normal adding components { Color color(0, 0, 0, 0); - obj.add_component<Sprite>( - make_shared<Texture>("../asset/texture/img.png"), color, - FlipSettings{false, false}); + obj.add_component<Sprite>(make_shared<Texture>("../asset/texture/img.png"), color, + FlipSettings{false, false}); obj.add_component<Camera>(Color::get_red()); } { Color color(0, 0, 0, 0); - obj1.add_component<Sprite>( - make_shared<Texture>("../asset/texture/second.png"), color, - FlipSettings{true, true}); + obj1.add_component<Sprite>(make_shared<Texture>("../asset/texture/second.png"), color, + FlipSettings{true, true}); } /* @@ -47,7 +48,6 @@ int main() { } */ - auto & sys = crepe::RenderSystem::get_instance(); auto start = std::chrono::steady_clock::now(); while (std::chrono::steady_clock::now() - start < std::chrono::seconds(5)) { sys.update(); diff --git a/src/example/savemgr.cpp b/src/example/savemgr.cpp index 436fb5a..65c4a34 100644 --- a/src/example/savemgr.cpp +++ b/src/example/savemgr.cpp @@ -6,8 +6,8 @@ #include <cassert> #include <crepe/api/Config.h> #include <crepe/api/SaveManager.h> +#include <crepe/util/Log.h> #include <crepe/util/Proxy.h> -#include <crepe/util/log.h> using namespace crepe; @@ -15,7 +15,7 @@ using namespace crepe; int _ = []() { // make sure all log messages get printed auto & cfg = Config::get_instance(); - cfg.log.level = LogLevel::TRACE; + cfg.log.level = Log::Level::TRACE; return 0; // satisfy compiler }(); @@ -25,19 +25,19 @@ int main() { SaveManager & mgr = SaveManager::get_instance(); - dbg_logf("has key = %s", mgr.has(key) ? "true" : "false"); + dbg_logf("has key = {}", mgr.has(key)); ValueBroker<int> prop = mgr.get<int>(key, 0); Proxy<int> val = mgr.get<int>(key, 0); - dbg_logf("val = %d", mgr.get<int>(key).get()); + dbg_logf("val = {}", mgr.get<int>(key).get()); prop.set(1); - dbg_logf("val = %d", mgr.get<int>(key).get()); + dbg_logf("val = {}", mgr.get<int>(key).get()); val = 2; - dbg_logf("val = %d", mgr.get<int>(key).get()); + dbg_logf("val = {}", mgr.get<int>(key).get()); mgr.set<int>(key, 3); - dbg_logf("val = %d", mgr.get<int>(key).get()); + dbg_logf("val = {}", mgr.get<int>(key).get()); - dbg_logf("has key = %s", mgr.has(key) ? "true" : "false"); + dbg_logf("has key = {}", mgr.has(key)); assert(true == mgr.has(key)); return 0; diff --git a/src/example/scene_manager.cpp b/src/example/scene_manager.cpp index f46dc36..accec7d 100644 --- a/src/example/scene_manager.cpp +++ b/src/example/scene_manager.cpp @@ -12,40 +12,44 @@ using namespace std; class ConcreteScene1 : public Scene { public: - ConcreteScene1(string name) : Scene(name) {} + using Scene::Scene; void load_scene() { - GameObject object1(0, "scene_1", "tag_scene_1", Vector2{0, 0}, 0, 1); - GameObject object2(1, "scene_1", "tag_scene_1", Vector2{1, 0}, 0, 1); - GameObject object3(2, "scene_1", "tag_scene_1", Vector2{2, 0}, 0, 1); + auto & mgr = this->component_manager; + GameObject object1 = mgr.new_object("scene_1", "tag_scene_1", Vector2{0, 0}, 0, 1); + GameObject object2 = mgr.new_object("scene_1", "tag_scene_1", Vector2{1, 0}, 0, 1); + GameObject object3 = mgr.new_object("scene_1", "tag_scene_1", Vector2{2, 0}, 0, 1); } }; class ConcreteScene2 : public Scene { public: - ConcreteScene2(string name) : Scene(name) {} + using Scene::Scene; void load_scene() { - GameObject object1(0, "scene_2", "tag_scene_2", Vector2{0, 0}, 0, 1); - GameObject object2(1, "scene_2", "tag_scene_2", Vector2{0, 1}, 0, 1); - GameObject object3(2, "scene_2", "tag_scene_2", Vector2{0, 2}, 0, 1); - GameObject object4(3, "scene_2", "tag_scene_2", Vector2{0, 3}, 0, 1); + auto & mgr = this->component_manager; + GameObject object1 = mgr.new_object("scene_2", "tag_scene_2", Vector2{0, 0}, 0, 1); + GameObject object2 = mgr.new_object("scene_2", "tag_scene_2", Vector2{0, 1}, 0, 1); + GameObject object3 = mgr.new_object("scene_2", "tag_scene_2", Vector2{0, 2}, 0, 1); + GameObject object4 = mgr.new_object("scene_2", "tag_scene_2", Vector2{0, 3}, 0, 1); } }; int main() { - SceneManager & scene_mgr = SceneManager::get_instance(); + ComponentManager component_mgr{}; + SceneManager scene_mgr{component_mgr}; // Add the scenes to the scene manager scene_mgr.add_scene<ConcreteScene1>("scene1"); scene_mgr.add_scene<ConcreteScene2>("scene2"); - // There is no need to call set_next_scene() at the beginnen, because the first scene will be automatically set as the next scene + // There is no need to call set_next_scene() at the beginnen, because the first scene will be + // automatically set as the next scene + // Load scene1 (the first scene added) scene_mgr.load_next_scene(); // Get the Metadata components of each GameObject of Scene1 - ComponentManager & component_mgr = ComponentManager::get_instance(); vector<reference_wrapper<Metadata>> metadata = component_mgr.get_components_by_type<Metadata>(); diff --git a/src/example/script.cpp b/src/example/script.cpp index 9e8b147..a23295b 100644 --- a/src/example/script.cpp +++ b/src/example/script.cpp @@ -5,7 +5,7 @@ #include <crepe/ComponentManager.h> #include <crepe/system/ScriptSystem.h> -#include <crepe/util/log.h> +#include <crepe/util/Log.h> #include <crepe/api/BehaviorScript.h> #include <crepe/api/Config.h> @@ -20,7 +20,7 @@ using namespace std; int _ = []() { // Show dbg_trace() output auto & cfg = Config::get_instance(); - cfg.log.level = LogLevel::TRACE; + cfg.log.level = Log::Level::TRACE; return 0; // satisfy compiler }(); @@ -30,20 +30,20 @@ class MyScript : public Script { void update() { // Retrieve component from the same GameObject this script is on Transform & test = get_component<Transform>(); - dbg_logf("Transform(%.2f, %.2f)", test.position.x, test.position.y); + dbg_logf("Transform({:.2f}, {:.2f})", test.position.x, test.position.y); } }; int main() { + ComponentManager component_manager{}; + ScriptSystem system{component_manager}; + // Create game object with Transform and BehaviorScript components - auto obj = GameObject(0, "name", "tag", Vector2{1.2, 3.4}, 0, 1); + GameObject obj = component_manager.new_object("name"); obj.add_component<BehaviorScript>().set_script<MyScript>(); - // Get ScriptSystem singleton instance (this would normally be done from the - // game loop) - ScriptSystem sys; // Update all scripts. This should result in MyScript::update being called - sys.update(); + system.update(); return EXIT_SUCCESS; } diff --git a/src/test/CMakeLists.txt b/src/test/CMakeLists.txt index acab388..49c8151 100644 --- a/src/test/CMakeLists.txt +++ b/src/test/CMakeLists.txt @@ -1,7 +1,7 @@ target_sources(test_main PUBLIC - dummy.cpp - # audio.cpp - # PhysicsTest.cpp + main.cpp + PhysicsTest.cpp + ScriptTest.cpp ParticleTest.cpp ) diff --git a/src/test/ParticleTest.cpp b/src/test/ParticleTest.cpp index 6fe3133..4e655a9 100644 --- a/src/test/ParticleTest.cpp +++ b/src/test/ParticleTest.cpp @@ -16,15 +16,16 @@ using namespace std::chrono_literals; using namespace crepe; class ParticlesTest : public ::testing::Test { -protected: - ParticleSystem particle_system; +public: + ComponentManager component_manager; + ParticleSystem particle_system{component_manager}; + void SetUp() override { - ComponentManager & mgr = ComponentManager::get_instance(); + ComponentManager & mgr = this->component_manager; std::vector<std::reference_wrapper<Transform>> transforms = mgr.get_components_by_id<Transform>(0); if (transforms.empty()) { - - GameObject game_object(0, "", "", Vector2{0, 0}, 0, 0); + GameObject game_object = mgr.new_object("", "", Vector2{0, 0}, 0, 0); Color color(0, 0, 0, 0); Sprite test_sprite = game_object.add_component<Sprite>( @@ -77,9 +78,8 @@ protected: TEST_F(ParticlesTest, spawnParticle) { Config::get_instance().physics.gravity = 1; - ComponentManager & mgr = ComponentManager::get_instance(); - ParticleEmitter & emitter - = mgr.get_components_by_id<ParticleEmitter>(0).front().get(); + ComponentManager & mgr = this->component_manager; + ParticleEmitter & emitter = mgr.get_components_by_id<ParticleEmitter>(0).front().get(); emitter.data.end_lifespan = 5; emitter.data.boundary.height = 100; emitter.data.boundary.width = 100; @@ -122,9 +122,8 @@ TEST_F(ParticlesTest, spawnParticle) { TEST_F(ParticlesTest, moveParticleHorizontal) { Config::get_instance().physics.gravity = 1; - ComponentManager & mgr = ComponentManager::get_instance(); - ParticleEmitter & emitter - = mgr.get_components_by_id<ParticleEmitter>(0).front().get(); + ComponentManager & mgr = this->component_manager; + ParticleEmitter & emitter = mgr.get_components_by_id<ParticleEmitter>(0).front().get(); emitter.data.end_lifespan = 100; emitter.data.boundary.height = 100; emitter.data.boundary.width = 100; @@ -140,9 +139,8 @@ TEST_F(ParticlesTest, moveParticleHorizontal) { TEST_F(ParticlesTest, moveParticleVertical) { Config::get_instance().physics.gravity = 1; - ComponentManager & mgr = ComponentManager::get_instance(); - ParticleEmitter & emitter - = mgr.get_components_by_id<ParticleEmitter>(0).front().get(); + ComponentManager & mgr = this->component_manager; + ParticleEmitter & emitter = mgr.get_components_by_id<ParticleEmitter>(0).front().get(); emitter.data.end_lifespan = 100; emitter.data.boundary.height = 100; emitter.data.boundary.width = 100; @@ -159,9 +157,8 @@ TEST_F(ParticlesTest, moveParticleVertical) { TEST_F(ParticlesTest, boundaryParticleReset) { Config::get_instance().physics.gravity = 1; - ComponentManager & mgr = ComponentManager::get_instance(); - ParticleEmitter & emitter - = mgr.get_components_by_id<ParticleEmitter>(0).front().get(); + ComponentManager & mgr = this->component_manager; + ParticleEmitter & emitter = mgr.get_components_by_id<ParticleEmitter>(0).front().get(); emitter.data.end_lifespan = 100; emitter.data.boundary.height = 10; emitter.data.boundary.width = 10; @@ -179,9 +176,8 @@ TEST_F(ParticlesTest, boundaryParticleReset) { TEST_F(ParticlesTest, boundaryParticleStop) { Config::get_instance().physics.gravity = 1; - ComponentManager & mgr = ComponentManager::get_instance(); - ParticleEmitter & emitter - = mgr.get_components_by_id<ParticleEmitter>(0).front().get(); + ComponentManager & mgr = this->component_manager; + ParticleEmitter & emitter = mgr.get_components_by_id<ParticleEmitter>(0).front().get(); emitter.data.end_lifespan = 100; emitter.data.boundary.height = 10; emitter.data.boundary.width = 10; diff --git a/src/test/PhysicsTest.cpp b/src/test/PhysicsTest.cpp index 5385962..1e37c26 100644 --- a/src/test/PhysicsTest.cpp +++ b/src/test/PhysicsTest.cpp @@ -11,16 +11,17 @@ using namespace std::chrono_literals; using namespace crepe; class PhysicsTest : public ::testing::Test { -protected: - GameObject * game_object; - PhysicsSystem physics_system; +public: + ComponentManager component_manager; + PhysicsSystem system{component_manager}; + void SetUp() override { - ComponentManager & mgr = ComponentManager::get_instance(); - std::vector<std::reference_wrapper<Transform>> transforms + ComponentManager & mgr = this->component_manager; + vector<reference_wrapper<Transform>> transforms = mgr.get_components_by_id<Transform>(0); if (transforms.empty()) { - game_object = new GameObject(0, "", "", Vector2{0, 0}, 0, 0); - game_object->add_component<Rigidbody>(Rigidbody::Data{ + auto entity = mgr.new_object("", "", Vector2{0, 0}, 0, 0); + entity.add_component<Rigidbody>(Rigidbody::Data{ .mass = 1, .gravity_scale = 1, .body_type = Rigidbody::BodyType::DYNAMIC, @@ -36,7 +37,7 @@ protected: transform.position.x = 0.0; transform.position.y = 0.0; transform.rotation = 0.0; - std::vector<std::reference_wrapper<Rigidbody>> rigidbodies + vector<reference_wrapper<Rigidbody>> rigidbodies = mgr.get_components_by_id<Rigidbody>(0); Rigidbody & rigidbody = rigidbodies.front().get(); rigidbody.data.angular_velocity = 0; @@ -47,34 +48,36 @@ protected: TEST_F(PhysicsTest, gravity) { Config::get_instance().physics.gravity = 1; - ComponentManager & mgr = ComponentManager::get_instance(); - std::vector<std::reference_wrapper<Transform>> transforms - = mgr.get_components_by_id<Transform>(0); + ComponentManager & mgr = this->component_manager; + vector<reference_wrapper<Transform>> transforms = mgr.get_components_by_id<Transform>(0); const Transform & transform = transforms.front().get(); ASSERT_FALSE(transforms.empty()); EXPECT_EQ(transform.position.y, 0); - physics_system.update(); + + system.update(); EXPECT_EQ(transform.position.y, 1); - physics_system.update(); + + system.update(); EXPECT_EQ(transform.position.y, 3); } TEST_F(PhysicsTest, max_velocity) { - ComponentManager & mgr = ComponentManager::get_instance(); - std::vector<std::reference_wrapper<Rigidbody>> rigidbodies - = mgr.get_components_by_id<Rigidbody>(0); + ComponentManager & mgr = this->component_manager; + vector<reference_wrapper<Rigidbody>> rigidbodies = mgr.get_components_by_id<Rigidbody>(0); Rigidbody & rigidbody = rigidbodies.front().get(); ASSERT_FALSE(rigidbodies.empty()); EXPECT_EQ(rigidbody.data.linear_velocity.y, 0); + rigidbody.add_force_linear({100, 100}); rigidbody.add_force_angular(100); - physics_system.update(); + system.update(); EXPECT_EQ(rigidbody.data.linear_velocity.y, 10); EXPECT_EQ(rigidbody.data.linear_velocity.x, 10); EXPECT_EQ(rigidbody.data.angular_velocity, 10); + rigidbody.add_force_linear({-100, -100}); rigidbody.add_force_angular(-100); - physics_system.update(); + system.update(); EXPECT_EQ(rigidbody.data.linear_velocity.y, -10); EXPECT_EQ(rigidbody.data.linear_velocity.x, -10); EXPECT_EQ(rigidbody.data.angular_velocity, -10); @@ -82,39 +85,42 @@ TEST_F(PhysicsTest, max_velocity) { TEST_F(PhysicsTest, movement) { Config::get_instance().physics.gravity = 0; - ComponentManager & mgr = ComponentManager::get_instance(); - std::vector<std::reference_wrapper<Rigidbody>> rigidbodies - = mgr.get_components_by_id<Rigidbody>(0); + ComponentManager & mgr = this->component_manager; + vector<reference_wrapper<Rigidbody>> rigidbodies = mgr.get_components_by_id<Rigidbody>(0); Rigidbody & rigidbody = rigidbodies.front().get(); - std::vector<std::reference_wrapper<Transform>> transforms - = mgr.get_components_by_id<Transform>(0); + vector<reference_wrapper<Transform>> transforms = mgr.get_components_by_id<Transform>(0); const Transform & transform = transforms.front().get(); ASSERT_FALSE(rigidbodies.empty()); ASSERT_FALSE(transforms.empty()); + rigidbody.add_force_linear({1, 1}); rigidbody.add_force_angular(1); - physics_system.update(); + system.update(); EXPECT_EQ(transform.position.x, 1); EXPECT_EQ(transform.position.y, 1); EXPECT_EQ(transform.rotation, 1); + rigidbody.data.constraints = {1, 1, 1}; EXPECT_EQ(transform.position.x, 1); EXPECT_EQ(transform.position.y, 1); EXPECT_EQ(transform.rotation, 1); + rigidbody.data.linear_damping.x = 0.5; rigidbody.data.linear_damping.y = 0.5; rigidbody.data.angular_damping = 0.5; - physics_system.update(); + system.update(); EXPECT_EQ(rigidbody.data.linear_velocity.x, 0.5); EXPECT_EQ(rigidbody.data.linear_velocity.y, 0.5); EXPECT_EQ(rigidbody.data.angular_velocity, 0.5); + rigidbody.data.constraints = {1, 1, 0}; rigidbody.data.angular_damping = 0; rigidbody.data.max_angular_velocity = 1000; rigidbody.data.angular_velocity = 360; - physics_system.update(); + system.update(); EXPECT_EQ(transform.rotation, 1); + rigidbody.data.angular_velocity = -360; - physics_system.update(); + system.update(); EXPECT_EQ(transform.rotation, 1); } diff --git a/src/test/ScriptTest.cpp b/src/test/ScriptTest.cpp new file mode 100644 index 0000000..19fef6d --- /dev/null +++ b/src/test/ScriptTest.cpp @@ -0,0 +1,72 @@ +#include <gtest/gtest.h> + +// stupid hack to allow access to private/protected members under test +#define private public +#define protected public + +#include <crepe/ComponentManager.h> +#include <crepe/api/BehaviorScript.h> +#include <crepe/api/GameObject.h> +#include <crepe/api/Script.h> +#include <crepe/api/Vector2.h> +#include <crepe/system/ScriptSystem.h> + +using namespace std; +using namespace crepe; +using namespace testing; + +class ScriptTest : public Test { +public: + ComponentManager component_manager{}; + ScriptSystem system{component_manager}; + + class MyScript : public Script { + // NOTE: default (private) visibility of init and update shouldn't cause + // issues! + void init() { this->init_count++; } + void update() { this->update_count++; } + + public: + unsigned init_count = 0; + unsigned update_count = 0; + }; + + BehaviorScript * behaviorscript_ref = nullptr; + MyScript * script_ref = nullptr; + + void SetUp() override { + auto & mgr = this->component_manager; + GameObject entity = mgr.new_object("name"); + BehaviorScript & component = entity.add_component<BehaviorScript>(); + + this->behaviorscript_ref = &component; + EXPECT_EQ(this->behaviorscript_ref->script.get(), nullptr); + component.set_script<MyScript>(); + ASSERT_NE(this->behaviorscript_ref->script.get(), nullptr); + + this->script_ref = (MyScript *) this->behaviorscript_ref->script.get(); + ASSERT_NE(this->script_ref, nullptr); + } +}; + +TEST_F(ScriptTest, Default) { + EXPECT_EQ(0, this->script_ref->init_count); + EXPECT_EQ(0, this->script_ref->update_count); +} + +TEST_F(ScriptTest, UpdateOnce) { + EXPECT_EQ(0, this->script_ref->init_count); + EXPECT_EQ(0, this->script_ref->update_count); + + this->system.update(); + EXPECT_EQ(1, this->script_ref->init_count); + EXPECT_EQ(1, this->script_ref->update_count); +} + +TEST_F(ScriptTest, ListScripts) { + size_t script_count = 0; + for (auto & _ : this->system.get_scripts()) { + script_count++; + } + ASSERT_EQ(1, script_count); +} diff --git a/src/test/audio.cpp b/src/test/audio.cpp deleted file mode 100644 index d6ff689..0000000 --- a/src/test/audio.cpp +++ /dev/null @@ -1,10 +0,0 @@ -#include <gtest/gtest.h> - -using namespace std; -using namespace std::chrono_literals; - -// using namespace crepe; - -// TODO: mock internal audio class - -TEST(audio, play) { ASSERT_TRUE(true); } diff --git a/src/test/dummy.cpp b/src/test/dummy.cpp deleted file mode 100644 index a00a9c6..0000000 --- a/src/test/dummy.cpp +++ /dev/null @@ -1,3 +0,0 @@ -#include <gtest/gtest.h> - -TEST(dummy, foo) { ASSERT_TRUE(1); } diff --git a/src/test/main.cpp b/src/test/main.cpp new file mode 100644 index 0000000..241015d --- /dev/null +++ b/src/test/main.cpp @@ -0,0 +1,15 @@ +#include <crepe/api/Config.h> + +#include <gtest/gtest.h> + +using namespace crepe; +using namespace testing; + +int main(int argc, char ** argv) { + InitGoogleTest(&argc, argv); + + auto & cfg = Config::get_instance(); + cfg.log.level = Log::Level::ERROR; + + return RUN_ALL_TESTS(); +} |