diff --git a/QtGameMaker.pro b/QtGameMaker.pro index a9568a8..6f80973 100644 --- a/QtGameMaker.pro +++ b/QtGameMaker.pro @@ -54,6 +54,7 @@ HEADERS += \ src/editor/widgets/zoomablescrollarea.h \ src/engine/gameengine.h \ src/engine/glgamewindow.h \ + src/engine/gamescene.h \ src/engine/vulkangamerenderer.h \ src/engine/vulkangamewindow.h \ src/futurecpp.h \ @@ -132,6 +133,7 @@ SOURCES += \ src/editor/widgets/zoomablescrollarea.cpp \ src/engine/gameengine.cpp \ src/engine/glgamewindow.cpp \ + src/engine/gamescene.cpp \ src/engine/vulkangamerenderer.cpp \ src/engine/vulkangamewindow.cpp \ src/main.cpp \ diff --git a/src/engine/gameengine.cpp b/src/engine/gameengine.cpp index 868b283..54b4cea 100644 --- a/src/engine/gameengine.cpp +++ b/src/engine/gameengine.cpp @@ -1,68 +1,96 @@ #include "gameengine.h" -#include +#include + #include -#include #include "closeeventfilter.h" +#include "projectcontainer.h" GameEngine::GameEngine(const ProjectContainer &project, QObject *parent) : QObject{parent}, m_project{project}, - m_glGameWindow{m_project, m_rotation}, - m_vulkanGameWindow{m_project, m_rotation}, - m_timerId(startTimer(1000/60, Qt::PreciseTimer)) + m_scene{project}, + m_glGameWindow{m_project, m_scene}, + m_vulkanGameWindow{m_project, m_scene} { - m_vulkanInstance.setLayers(QByteArrayList { "VK_LAYER_LUNARG_standard_validation" }); - - if (!m_vulkanInstance.create()) - qFatal("Failed to create Vulkan instance: %d", m_vulkanInstance.errorCode()); - - m_vulkanGameWindow.setVulkanInstance(&m_vulkanInstance); + m_vulkanAvailable = m_vulkanInstance.create(); + if (m_vulkanAvailable) + m_vulkanGameWindow.setVulkanInstance(&m_vulkanInstance); + else + qWarning("Could not create Vulkan instance: %d", m_vulkanInstance.errorCode()); m_glGameWindow.setModality(Qt::WindowModal); m_vulkanGameWindow.setModality(Qt::WindowModal); + + m_frameTimer.setTimerType(Qt::PreciseTimer); + m_frameTimer.setSingleShot(true); + connect(&m_frameTimer, &QTimer::timeout, this, [this]() { + constexpr qint64 frameNanoseconds = 1000000000 / 60; + m_scene.advanceTo(m_elapsed.elapsed()); + m_scene.draw(); + m_glGameWindow.requestUpdate(); + if (m_vulkanAvailable) + m_vulkanGameWindow.requestUpdate(); + + const qint64 now = m_elapsed.nsecsElapsed(); + m_nextFrameNanoseconds = std::max(m_nextFrameNanoseconds + frameNanoseconds, + (now / frameNanoseconds + 1) * frameNanoseconds); + const qint64 remaining = m_nextFrameNanoseconds - m_elapsed.nsecsElapsed(); + m_frameTimer.start(int(std::max(1, (remaining + 999999) / 1000000))); + }); } void GameEngine::run() { - m_glGameWindow.setTitle(tr("Game Window - OpenGL")); - m_vulkanGameWindow.setTitle(tr("Game Window - Vulkan")); + if (m_project.rooms.empty()) + return; + + m_scene.start([this](ObjectInstance &target, const Action &action, ObjectInstance *) { + if (target.applyAction(action)) + return; + static constexpr std::array actionNames{ + "MoveFixed", "MoveFree", "MoveTowards", "SpeedHorizontal", + "SpeedVertical", "SetGravity", "ExecuteCode" + }; + const std::size_t type = action.index(); + if (!m_warnedActionTypes[type]) + { + m_warnedActionTypes[type] = true; + qWarning("Game action %s has no runtime implementation yet", actionNames[type]); + } + }); CloseEventFilter closeEventFilter; - m_glGameWindow.installEventFilter(&closeEventFilter); - m_vulkanGameWindow.installEventFilter(&closeEventFilter); + if (m_vulkanAvailable) + m_vulkanGameWindow.installEventFilter(&closeEventFilter); QEventLoop eventLoop; + bool shuttingDown = false; connect(&closeEventFilter, &CloseEventFilter::closeEventReceived, - &eventLoop, &QEventLoop::quit); + &eventLoop, [this, &eventLoop, &shuttingDown]() { + if (shuttingDown) + return; + shuttingDown = true; + m_frameTimer.stop(); + // Finish both QWindow close paths before their Vulkan instance is destroyed. + if (m_vulkanAvailable) + m_vulkanGameWindow.close(); + m_glGameWindow.close(); + QTimer::singleShot(0, &eventLoop, &QEventLoop::quit); + }, Qt::QueuedConnection); + + m_glGameWindow.setTitle(m_glGameWindow.title() + tr(" - OpenGL")); m_glGameWindow.show(); - m_vulkanGameWindow.show(); - - QTimer::singleShot(100, &m_glGameWindow, [this](){ - auto geometry = m_glGameWindow.geometry(); - qDebug() << geometry; - geometry.moveLeft(geometry.left() - (geometry.width() / 2)); - m_glGameWindow.setGeometry(geometry); - }); - QTimer::singleShot(100, &m_vulkanGameWindow, [this](){ - auto geometry = m_vulkanGameWindow.geometry(); - qDebug() << geometry; - geometry.moveLeft(geometry.left() + (geometry.width() / 2)); - m_vulkanGameWindow.setGeometry(geometry); - }); - + if (m_vulkanAvailable) + { + m_vulkanGameWindow.setTitle(m_vulkanGameWindow.title() + tr(" - Vulkan")); + m_vulkanGameWindow.show(); + } + m_elapsed.start(); + m_nextFrameNanoseconds = 1000000000 / 60; + m_frameTimer.start(17); eventLoop.exec(); } - -void GameEngine::timerEvent(QTimerEvent *event) -{ - if (event->timerId() == m_timerId) - { - m_rotation += 1.f; - } - else - QObject::timerEvent(event); -} diff --git a/src/engine/gameengine.h b/src/engine/gameengine.h index 6d031cc..eae0efa 100644 --- a/src/engine/gameengine.h +++ b/src/engine/gameengine.h @@ -1,7 +1,13 @@ #pragma once -#include +#include +#include +#include +#include +#include + +#include "engine/gamescene.h" #include "engine/glgamewindow.h" #include "engine/vulkangamewindow.h" @@ -13,21 +19,17 @@ class GameEngine : public QObject public: explicit GameEngine(const ProjectContainer &project, QObject *parent = nullptr); - void run(); -protected: - void timerEvent(QTimerEvent *event) override; - private: const ProjectContainer &m_project; - + GameScene m_scene; QVulkanInstance m_vulkanInstance; - - float m_rotation{}; - GlGameWindow m_glGameWindow; VulkanGameWindow m_vulkanGameWindow; - - const int m_timerId; + bool m_vulkanAvailable{}; + QTimer m_frameTimer; + QElapsedTimer m_elapsed; + qint64 m_nextFrameNanoseconds{}; + std::array> m_warnedActionTypes{}; }; diff --git a/src/engine/gamescene.cpp b/src/engine/gamescene.cpp new file mode 100644 index 0000000..93dd82d --- /dev/null +++ b/src/engine/gamescene.cpp @@ -0,0 +1,359 @@ +#include "gamescene.h" + +#include +#include +#include +#include +#include + +#include +#include + +namespace { + +std::size_t frameIndex(double imageIndex, std::size_t count) +{ + const auto size = static_cast(count); + qint64 index = static_cast(std::floor(imageIndex)) % size; + if (index < 0) + index += size; + return static_cast(index); +} + +QPointF motion(double degrees, double speed) +{ + const double radians = degrees * std::numbers::pi / 180.0; + return {speed * std::cos(radians), -speed * std::sin(radians)}; +} + +} // namespace + +void ObjectInstance::executeActions(const ActionsContainer &actions, GameScene &scene, + const ActionExecutor &executor, ObjectInstance *other) +{ + if (!executor) + return; + + for (const Action &action : actions) + { + const AppliesTo &appliesTo = std::visit([](const auto &value) -> const AppliesTo & { + return value.appliesTo; + }, action); + std::visit([&](const auto &target) { + using Target = std::decay_t; + if constexpr (std::is_same_v) + executor(*this, action, other); + else if constexpr (std::is_same_v) + { + if (other) + executor(*other, action, this); + } + else + { + for (ObjectInstance &instance : scene.instances) + { + if (instance.definition && instance.definition->name == target.objectName) + executor(instance, action, this); + } + } + }, appliesTo); + } +} + +void ObjectInstance::executeEvent(Object::EventType event, GameScene &scene, + const ActionExecutor &executor, ObjectInstance *other) +{ + if (!definition) + return; + const auto found = definition->events.find(event); + if (found != definition->events.end()) + executeActions(found->second, scene, executor, other); +} + +void ObjectInstance::executeCollisionEvent(const QString &objectName, GameScene &scene, + const ActionExecutor &executor, ObjectInstance &other) +{ + if (!definition) + return; + const auto found = definition->collisionEvents.find(objectName); + if (found != definition->collisionEvents.end()) + executeActions(found->second, scene, executor, &other); +} + +void ObjectInstance::step() +{ + const QPointF gravityMotion = motion(gravityDirection, gravity); + hspeed += gravityMotion.x(); + vspeed += gravityMotion.y(); + position += QPointF{hspeed, vspeed}; + imageIndex += imageSpeed; +} + +bool ObjectInstance::setAlarm(std::size_t index, int steps) +{ + if (index >= alarms.size()) + return false; + alarms[index] = steps > 0 ? steps : -1; + return true; +} + +bool ObjectInstance::applyAction(const Action &action) +{ + return std::visit([this](const auto &value) -> bool { + using T = std::decay_t; + if constexpr (std::is_same_v) + hspeed = value.relative ? hspeed + value.speed : value.speed; + else if constexpr (std::is_same_v) + vspeed = value.relative ? vspeed + value.speed : value.speed; + else if constexpr (std::is_same_v) + { + gravityDirection = value.relative ? gravityDirection + value.direction : value.direction; + gravity = value.relative ? gravity + value.gravity : value.gravity; + } + else if constexpr (std::is_same_v) + { + const QPointF velocity = motion(value.direction, value.speed); + hspeed = value.relative ? hspeed + velocity.x() : velocity.x(); + vspeed = value.relative ? vspeed + velocity.y() : velocity.y(); + } + else if constexpr (std::is_same_v) + { + const QPointF offset{double(value.x), double(value.y)}; + const QPointF goal = value.relative ? position + offset : offset; + const QPointF delta = goal - position; + const double distance = std::hypot(delta.x(), delta.y()); + if (distance > 0) + { + hspeed = value.speed * delta.x() / distance; + vspeed = value.speed * delta.y() / distance; + } + else + hspeed = vspeed = 0; + } + else if constexpr (std::is_same_v) + { + std::array choices{}; + int count = 0; + for (int i = 0; i < int(choices.size()); ++i) + if (value.directions[std::size_t(i)]) + choices[std::size_t(count++)] = i; + if (count == 0) + return true; + const int direction = choices[QRandomGenerator::global()->bounded(count)]; + constexpr std::array angles{135, 90, 45, 180, 0, 0, 225, 270, 315}; + const QPointF velocity = direction == 4 ? QPointF{} : motion(angles[std::size_t(direction)], value.speed); + hspeed = value.relative ? hspeed + velocity.x() : velocity.x(); + vspeed = value.relative ? vspeed + velocity.y() : velocity.y(); + } + else + return false; // ExecuteCode needs a GML interpreter. + return true; + }, action); +} + +GameScene::GameScene(const ProjectContainer &project) +{ + if (project.rooms.empty()) + return; + + const Room &room = project.rooms.front(); + roomSize = QSize{std::max(1, room.width), std::max(1, room.height)}; + caption = room.caption.isEmpty() ? room.name : room.caption; + roomSpeed = std::max(1, room.speed); + + QHash spriteIndices; + for (const ::Sprite &source : project.sprites) + { + Sprite sprite; + sprite.origin = QPoint{source.origin.x, source.origin.y}; + for (const QPixmap &pixmap : source.pixmaps) + { + if (pixmap.isNull()) + continue; + sprite.frames.push_back(textures.size()); + textures.push_back(pixmap.toImage()); + sprite.collisionBounds.push_back(QRect{QPoint{}, textures.back().size()}); + } + spriteIndices.insert(source.name, sprites.size()); + sprites.push_back(std::move(sprite)); + } + + QHash objects; + for (const Object &object : project.objects) + objects.insert(object.name, &object); + + for (const Room::Object &placed : room.objects) + { + const Object *object = objects.value(placed.objectName, nullptr); + if (!object) + continue; + const auto sprite = spriteIndices.constFind(object->spriteName); + Instance instance; + instance.definition = object; + if (sprite != spriteIndices.cend() && !sprites.at(*sprite).frames.empty()) + instance.spriteIndex = *sprite; + const auto mask = spriteIndices.constFind(object->maskSpriteName); + if (!object->maskSpriteName.isEmpty() && mask != spriteIndices.cend() && + !sprites.at(*mask).frames.empty()) + instance.maskSpriteIndex = *mask; + instance.position = QPointF{placed.pos}; + instance.depth = object->depth; + instance.visible = object->visible; + instances.push_back(instance); + } + +} + +std::size_t GameScene::textureFor(const Instance &instance) const +{ + const Sprite &sprite = sprites.at(*instance.spriteIndex); + return sprite.frames.at(frameIndex(instance.imageIndex, sprite.frames.size())); +} + +QRectF GameScene::collisionRect(const Instance &instance) const +{ + const auto index = instance.maskSpriteIndex ? instance.maskSpriteIndex : instance.spriteIndex; + if (!index) + return {}; + const Sprite &sprite = sprites.at(*index); + const QRect &bounds = sprite.collisionBounds.at(frameIndex(instance.imageIndex, sprite.frames.size())); + if (bounds.isEmpty()) + return {}; + return {instance.position.x() - sprite.origin.x() + bounds.x(), + instance.position.y() - sprite.origin.y() + bounds.y(), + double(bounds.width()), double(bounds.height())}; +} + +std::vector GameScene::drawOrder() const +{ + std::vector order; + order.reserve(instances.size()); + for (const Instance &instance : instances) + order.push_back(&instance); + // Larger depths are behind smaller ones; equal depths keep room placement order. + std::stable_sort(order.begin(), order.end(), [](const Instance *left, const Instance *right) { + return left->depth > right->depth; + }); + return order; +} + +void GameScene::start(const ActionExecutor &executor) +{ + m_executor = executor; + m_stepsDone = 0; + for (Instance &instance : instances) + if (!instance.pendingDestroy) + instance.executeEvent(Object::EventType::Create, *this, m_executor); + removeDestroyed(); +} + +void GameScene::destroyInstance(Instance &instance) +{ + if (instance.pendingDestroy) + return; + instance.pendingDestroy = true; + instance.executeEvent(Object::EventType::Destroy, *this, m_executor); +} + +void GameScene::removeDestroyed() +{ + std::erase_if(instances, [](const Instance &instance) { return instance.pendingDestroy; }); +} + +void GameScene::advanceTo(qint64 elapsedMilliseconds) +{ + const qint64 targetStep = elapsedMilliseconds * roomSpeed / 1000; + while (m_stepsDone < targetStep) + { + for (Instance &instance : instances) + if (!instance.pendingDestroy) + instance.executeEvent(Object::EventType::BeginStep, *this, m_executor); + for (Instance &instance : instances) + { + if (instance.pendingDestroy) + continue; + for (std::size_t index = 0; index < instance.alarms.size(); ++index) + { + int &remaining = instance.alarms[index]; + if (remaining <= 0 || --remaining != 0) + continue; + remaining = -1; + const auto event = static_cast(int(Object::EventType::Alarm0) + int(index)); + instance.executeEvent(event, *this, m_executor); + if (instance.pendingDestroy) + break; + } + } + for (Instance &instance : instances) + if (!instance.pendingDestroy) + instance.executeEvent(Object::EventType::Step, *this, m_executor); + + std::vector previousPositions; + previousPositions.reserve(instances.size()); + for (const Instance &instance : instances) + previousPositions.push_back(instance.position); + for (Instance &instance : instances) + if (!instance.pendingDestroy) + instance.step(); + + // Detect every pair at its moved position before collision actions can + // change either instance. A sprite-size rectangle is our first mask. + std::vector> collisions; + for (std::size_t i = 0; i < instances.size(); ++i) + { + if (instances[i].pendingDestroy) + continue; + const QRectF first = collisionRect(instances[i]); + if (first.isEmpty()) + continue; + for (std::size_t j = i + 1; j < instances.size(); ++j) + { + if (instances[j].pendingDestroy) + continue; + const QRectF second = collisionRect(instances[j]); + if (!second.isEmpty() && first.intersects(second)) + collisions.emplace_back(i, j); + } + } + for (const auto &[i, j] : collisions) + { + Instance &first = instances[i]; + Instance &second = instances[j]; + if (first.pendingDestroy || second.pendingDestroy) + continue; + const QString &firstName = first.definition->name; + const QString &secondName = second.definition->name; + const auto firstEvent = first.definition->collisionEvents.find(secondName); + const auto secondEvent = second.definition->collisionEvents.find(firstName); + const bool firstHandles = firstEvent != first.definition->collisionEvents.end() && + !firstEvent->second.empty(); + const bool secondHandles = secondEvent != second.definition->collisionEvents.end() && + !secondEvent->second.empty(); + if (!firstHandles && !secondHandles) + continue; + + if (first.definition->solid || second.definition->solid) + { + first.position = previousPositions[i]; + second.position = previousPositions[j]; + } + if (firstHandles) + first.executeCollisionEvent(secondName, *this, m_executor, second); + if (secondHandles && !second.pendingDestroy && !first.pendingDestroy) + second.executeCollisionEvent(firstName, *this, m_executor, first); + } + for (Instance &instance : instances) + if (!instance.pendingDestroy) + instance.executeEvent(Object::EventType::EndStep, *this, m_executor); + removeDestroyed(); + ++m_stepsDone; + } +} + +void GameScene::draw() +{ + for (Instance &instance : instances) + if (instance.visible && !instance.pendingDestroy) + instance.executeEvent(Object::EventType::Draw, *this, m_executor); + removeDestroyed(); +} diff --git a/src/engine/gamescene.h b/src/engine/gamescene.h new file mode 100644 index 0000000..96db84c --- /dev/null +++ b/src/engine/gamescene.h @@ -0,0 +1,88 @@ +#pragma once + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#include "projectcontainer.h" + +struct GameScene; +struct ObjectInstance; + +// The interpreter supplies action behavior. `other` is the collision counterpart +// for self actions, or the event source when an action targets another instance. +using ActionExecutor = std::function; + +struct ObjectInstance +{ + ObjectInstance() { alarms.fill(-1); } + + const Object *definition{}; + std::optional spriteIndex; + std::optional maskSpriteIndex; + QPointF position; + double hspeed{}; + double vspeed{}; + double gravity{}; + double gravityDirection{270.0}; + double imageIndex{}; + double imageSpeed{1.0}; + int depth{}; + bool visible{true}; + bool pendingDestroy{}; + std::array alarms; + + void step(); + bool setAlarm(std::size_t index, int steps); + bool applyAction(const Action &action); + void executeActions(const ActionsContainer &actions, GameScene &scene, + const ActionExecutor &executor, ObjectInstance *other = nullptr); + void executeEvent(Object::EventType event, GameScene &scene, + const ActionExecutor &executor, ObjectInstance *other = nullptr); + void executeCollisionEvent(const QString &objectName, GameScene &scene, + const ActionExecutor &executor, ObjectInstance &other); +}; + +// Mutable runtime state shared by the OpenGL and Vulkan renderers. +struct GameScene +{ + struct Sprite + { + std::vector frames; + std::vector collisionBounds; + QPoint origin; + }; + + using Instance = ObjectInstance; + + explicit GameScene(const ProjectContainer &project); + + std::size_t textureFor(const Instance &instance) const; + QRectF collisionRect(const Instance &instance) const; + std::vector drawOrder() const; + void start(const ActionExecutor &executor); + void destroyInstance(Instance &instance); + void advanceTo(qint64 elapsedMilliseconds); + void draw(); + + QSize roomSize; + QString caption; + int roomSpeed{30}; + std::vector textures; + std::vector sprites; + std::vector instances; + +private: + qint64 m_stepsDone{}; + ActionExecutor m_executor; + void removeDestroyed(); +}; diff --git a/src/engine/glgamewindow.cpp b/src/engine/glgamewindow.cpp index 7a845cc..866d5c9 100644 --- a/src/engine/glgamewindow.cpp +++ b/src/engine/glgamewindow.cpp @@ -1,160 +1,233 @@ #include "glgamewindow.h" -#include -#include -#include -#include -#include -#include -#include +#include +#include -GlGameWindow::GlGameWindow(const ProjectContainer &project, const float &rotation, QWindow *parent) : +#include +#include +#include +#include +#include + +#include "gamescene.h" +#include "projectcontainer.h" + +namespace { + +struct Vertex +{ + float x, y, z, u, v; +}; + +constexpr std::array quad {{ + {0.f, 0.f, 0.f, 0.f, 0.f}, + {0.f, 1.f, 0.f, 0.f, 1.f}, + {1.f, 0.f, 0.f, 1.f, 0.f}, + {1.f, 1.f, 0.f, 1.f, 1.f} +}}; + +} + +GlGameWindow::GlGameWindow(const ProjectContainer &project, const GameScene &scene, QWindow *parent) : QWindow{parent}, m_project{project}, - m_rotation{rotation} + m_scene{scene} { setSurfaceType(QWindow::OpenGLSurface); - - setMinimumWidth(640); - setMaximumWidth(640); - setMinimumHeight(480); - setMaximumHeight(480); - resize(640, 480); + if (!m_project.rooms.empty()) + { + resize(m_scene.roomSize); + if (!m_project.globalGameSettings.resizable) + { + setMinimumSize(m_scene.roomSize); + setMaximumSize(m_scene.roomSize); + } + setTitle(m_scene.caption); + } } -GlGameWindow::~GlGameWindow() = default; - -void GlGameWindow::initialize() +GlGameWindow::~GlGameWindow() { - m_program = new QOpenGLShaderProgram{this}; - - - if (!m_program->addShaderFromSourceFile(QOpenGLShader::Vertex, QStringLiteral(":/qtgameengine/opengl_shaders/color.vert"))) - qFatal("could not load vertex shader"); - if (!m_program->addShaderFromSourceFile(QOpenGLShader::Fragment, QStringLiteral(":/qtgameengine/opengl_shaders/color.frag"))) - qFatal("could not load fragment shader"); - - - m_program->link(); - m_posAttr = m_program->attributeLocation("posAttr"); - Q_ASSERT(m_posAttr != -1); - m_colAttr = m_program->attributeLocation("colAttr"); - Q_ASSERT(m_colAttr != -1); - m_matrixUniform = m_program->uniformLocation("matrix"); - Q_ASSERT(m_matrixUniform != -1); + releaseResources(); } -void GlGameWindow::render() +bool GlGameWindow::initialize() { - const qreal retinaScale = devicePixelRatio(); - glViewport(0, 0, width() * retinaScale, height() * retinaScale); + initializeOpenGLFunctions(); - glClear(GL_COLOR_BUFFER_BIT); + m_program = new QOpenGLShaderProgram; + if (!m_program->addShaderFromSourceFile(QOpenGLShader::Vertex, + QStringLiteral(":/qtgameengine/opengl_shaders/texture.vert")) || + !m_program->addShaderFromSourceFile(QOpenGLShader::Fragment, + QStringLiteral(":/qtgameengine/opengl_shaders/texture.frag")) || + !m_program->link()) + { + qWarning("Could not compile OpenGL sprite shaders: %s", qPrintable(m_program->log())); + return false; + } + + if (!m_vao.create()) + { + qWarning("Could not create OpenGL vertex array"); + return false; + } + m_vao.bind(); + glGenBuffers(1, &m_vertexBuffer); + glBindBuffer(GL_ARRAY_BUFFER, m_vertexBuffer); + glBufferData(GL_ARRAY_BUFFER, sizeof(quad), quad.data(), GL_STATIC_DRAW); m_program->bind(); - - QMatrix4x4 matrix; - matrix.perspective(60.0f, 4.0f / 3.0f, 0.1f, 100.0f); - matrix.translate(0, 0, -2); - matrix.rotate(m_rotation, 0, 1, 0); - - m_program->setUniformValue(m_matrixUniform, matrix); - - static const GLfloat vertices[] { - 0.0f, 0.707f, - -0.5f, -0.5f, - 0.5f, -0.5f - }; - - static const GLfloat colors[] { - 1.0f, 0.0f, 0.0f, - 0.0f, 1.0f, 0.0f, - 0.0f, 0.0f, 1.0f - }; - - glVertexAttribPointer(m_posAttr, 2, GL_FLOAT, GL_FALSE, 0, vertices); - glVertexAttribPointer(m_colAttr, 3, GL_FLOAT, GL_FALSE, 0, colors); - - glEnableVertexAttribArray(m_posAttr); - glEnableVertexAttribArray(m_colAttr); - - glDrawArrays(GL_TRIANGLES, 0, 3); - - glDisableVertexAttribArray(m_colAttr); - glDisableVertexAttribArray(m_posAttr); - + const int position = m_program->attributeLocation("position"); + const int texCoord = m_program->attributeLocation("texCoord"); + if (position < 0 || texCoord < 0) + { + qWarning("OpenGL sprite shader has missing attributes"); + return false; + } + glEnableVertexAttribArray(position); + glVertexAttribPointer(position, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), + reinterpret_cast(offsetof(Vertex, x))); + glEnableVertexAttribArray(texCoord); + glVertexAttribPointer(texCoord, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), + reinterpret_cast(offsetof(Vertex, u))); + m_program->setUniformValue("tex", 0); m_program->release(); + m_vao.release(); + + m_textures.reserve(m_scene.textures.size()); + glPixelStorei(GL_UNPACK_ALIGNMENT, 1); + for (const QImage &source : m_scene.textures) + { + const QImage image = source.convertToFormat(QImage::Format_RGBA8888); + GLuint texture{}; + glGenTextures(1, &texture); + glBindTexture(GL_TEXTURE_2D, texture); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, image.width(), image.height(), + 0, GL_RGBA, GL_UNSIGNED_BYTE, image.constBits()); + m_textures.push_back(texture); + } + glBindTexture(GL_TEXTURE_2D, 0); + glBindBuffer(GL_ARRAY_BUFFER, 0); + return true; } -void GlGameWindow::renderLater() +void GlGameWindow::releaseResources() { - requestUpdate(); + if (!m_context) + return; + + if (m_context->makeCurrent(this)) + { + if (!m_textures.empty()) + glDeleteTextures(static_cast(m_textures.size()), m_textures.data()); + if (m_vertexBuffer) + glDeleteBuffers(1, &m_vertexBuffer); + m_vao.destroy(); + delete m_program; + m_program = nullptr; + m_context->doneCurrent(); + } + else + delete m_program; + + m_textures.clear(); + m_vertexBuffer = 0; + m_program = nullptr; + delete m_context; + m_context = nullptr; } void GlGameWindow::renderNow() { - if (!isExposed()) + if (!isExposed() || m_project.rooms.empty()) return; - bool needsInitialize = false; - if (!m_context) { - m_context = new QOpenGLContext{this}; + m_context = new QOpenGLContext; m_context->setFormat(requestedFormat()); - m_context->create(); - - needsInitialize = true; + if (!m_context->create()) + { + qWarning("Could not create OpenGL context for the game window"); + delete m_context; + m_context = nullptr; + return; + } + if (!m_context->makeCurrent(this) || !initialize()) + { + releaseResources(); + return; + } } + else if (!m_context->makeCurrent(this)) + return; - m_context->makeCurrent(this); + const qreal scale = devicePixelRatio(); + glViewport(0, 0, qRound(width() * scale), qRound(height() * scale)); + glClearColor(1.f, 1.f, 1.f, 1.f); + glClear(GL_COLOR_BUFFER_BIT); + glDisable(GL_DEPTH_TEST); + glEnable(GL_BLEND); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - if (needsInitialize) + QMatrix4x4 projection; + projection.ortho(0.f, float(m_scene.roomSize.width()), + float(m_scene.roomSize.height()), 0.f, -1.f, 1.f); + m_program->bind(); + m_vao.bind(); + glActiveTexture(GL_TEXTURE0); + for (const GameScene::Instance *instance : m_scene.drawOrder()) { - initializeOpenGLFunctions(); - initialize(); + if (!instance->visible || !instance->spriteIndex) + continue; + const std::size_t textureIndex = m_scene.textureFor(*instance); + const QImage &image = m_scene.textures.at(textureIndex); + const QPoint &origin = m_scene.sprites.at(*instance->spriteIndex).origin; + + QMatrix4x4 matrix = projection; + matrix.translate(float(instance->position.x() - origin.x()), + float(instance->position.y() - origin.y())); + matrix.scale(float(image.width()), float(image.height())); + m_program->setUniformValue("matrix", matrix); + glBindTexture(GL_TEXTURE_2D, m_textures.at(textureIndex)); + glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); } - - render(); - + m_vao.release(); + m_program->release(); + glBindTexture(GL_TEXTURE_2D, 0); m_context->swapBuffers(this); - - renderLater(); } bool GlGameWindow::event(QEvent *event) { - switch (event->type()) + if (event->type() == QEvent::PlatformSurface && + static_cast(event)->surfaceEventType() == + QPlatformSurfaceEvent::SurfaceAboutToBeDestroyed) + releaseResources(); + + if (event->type() == QEvent::UpdateRequest) { - case QEvent::UpdateRequest: renderNow(); return true; - default: - return QWindow::event(event); } + return QWindow::event(event); } void GlGameWindow::keyPressEvent(QKeyEvent *event) { - QWindow::keyPressEvent(event); - - switch (event->key()) - { - case Qt::Key_Escape: + if (event->key() == Qt::Key_Escape && m_project.globalGameSettings.letEscEndGame) close(); - break; - } -} - -void GlGameWindow::keyReleaseEvent(QKeyEvent *event) -{ - QWindow::keyReleaseEvent(event); + else + QWindow::keyPressEvent(event); } void GlGameWindow::exposeEvent(QExposeEvent *event) { - Q_UNUSED(event); - + QWindow::exposeEvent(event); if (isExposed()) renderNow(); } diff --git a/src/engine/glgamewindow.h b/src/engine/glgamewindow.h index 98b8438..eb84635 100644 --- a/src/engine/glgamewindow.h +++ b/src/engine/glgamewindow.h @@ -1,11 +1,14 @@ #pragma once -#include +#include + #include +#include +#include class QOpenGLContext; -class QOpenGLPaintDevice; class QOpenGLShaderProgram; +struct GameScene; struct ProjectContainer; class GlGameWindow : public QWindow, protected QOpenGLFunctions @@ -13,33 +16,25 @@ class GlGameWindow : public QWindow, protected QOpenGLFunctions Q_OBJECT public: - explicit GlGameWindow(const ProjectContainer &project, const float &m_rotation, QWindow *parent = nullptr); - ~GlGameWindow(); + explicit GlGameWindow(const ProjectContainer &project, const GameScene &scene, QWindow *parent = nullptr); + ~GlGameWindow() override; - void initialize(); - void render(); - -public slots: - void renderLater(); void renderNow(); protected: bool event(QEvent *event) override; void keyPressEvent(QKeyEvent *event) override; - void keyReleaseEvent(QKeyEvent *event) override; - void exposeEvent(QExposeEvent *event) override; private: + bool initialize(); + void releaseResources(); + const ProjectContainer &m_project; - + const GameScene &m_scene; QOpenGLContext *m_context{}; - QOpenGLPaintDevice *m_device{}; - - GLint m_posAttr = 0; - GLint m_colAttr = 0; - GLint m_matrixUniform = 0; - QOpenGLShaderProgram *m_program{}; - const float &m_rotation; + QOpenGLVertexArrayObject m_vao; + GLuint m_vertexBuffer{}; + std::vector m_textures; }; diff --git a/src/engine/opengl_shaders/texture.frag b/src/engine/opengl_shaders/texture.frag new file mode 100644 index 0000000..ad1ca7c --- /dev/null +++ b/src/engine/opengl_shaders/texture.frag @@ -0,0 +1,11 @@ +#ifdef GL_ES +precision mediump float; +#endif + +varying vec2 vTexCoord; +uniform sampler2D tex; + +void main() +{ + gl_FragColor = texture2D(tex, vTexCoord); +} diff --git a/src/engine/opengl_shaders/texture.vert b/src/engine/opengl_shaders/texture.vert new file mode 100644 index 0000000..f5f9cb6 --- /dev/null +++ b/src/engine/opengl_shaders/texture.vert @@ -0,0 +1,10 @@ +attribute vec3 position; +attribute vec2 texCoord; +varying vec2 vTexCoord; +uniform mat4 matrix; + +void main() +{ + vTexCoord = texCoord; + gl_Position = matrix * vec4(position, 1.0); +} diff --git a/src/engine/resources_engine.qrc b/src/engine/resources_engine.qrc index 5df7fe0..8381f60 100644 --- a/src/engine/resources_engine.qrc +++ b/src/engine/resources_engine.qrc @@ -2,6 +2,8 @@ opengl_shaders/color.frag opengl_shaders/color.vert + opengl_shaders/texture.frag + opengl_shaders/texture.vert vulkan_shader_modules/color_frag.spv vulkan_shader_modules/color_vert.spv vulkan_shader_modules/texture_frag.spv diff --git a/src/engine/vulkan_shader_modules/texture.frag b/src/engine/vulkan_shader_modules/texture.frag index e6021fe..4ec724b 100644 --- a/src/engine/vulkan_shader_modules/texture.frag +++ b/src/engine/vulkan_shader_modules/texture.frag @@ -1,10 +1,9 @@ #version 440 layout(location = 0) in vec2 v_texcoord; - layout(location = 0) out vec4 fragColor; -layout(binding = 1) uniform sampler2D tex; +layout(binding = 0) uniform sampler2D tex; void main() { diff --git a/src/engine/vulkan_shader_modules/texture.vert b/src/engine/vulkan_shader_modules/texture.vert index de486cb..1b72049 100644 --- a/src/engine/vulkan_shader_modules/texture.vert +++ b/src/engine/vulkan_shader_modules/texture.vert @@ -1,18 +1,16 @@ #version 440 -layout(location = 0) in vec4 position; +layout(location = 0) in vec3 position; layout(location = 1) in vec2 texcoord; layout(location = 0) out vec2 v_texcoord; -layout(std140, binding = 0) uniform buf { - mat4 mvp; -} ubuf; - -out gl_PerVertex { vec4 gl_Position; }; +layout(push_constant) uniform Push { + mat4 matrix; +} push; void main() { v_texcoord = texcoord; - gl_Position = ubuf.mvp * position; + gl_Position = push.matrix * vec4(position, 1.0); } diff --git a/src/engine/vulkan_shader_modules/texture_frag.spv b/src/engine/vulkan_shader_modules/texture_frag.spv index 7521ef6..3cfe6db 100644 Binary files a/src/engine/vulkan_shader_modules/texture_frag.spv and b/src/engine/vulkan_shader_modules/texture_frag.spv differ diff --git a/src/engine/vulkan_shader_modules/texture_vert.spv b/src/engine/vulkan_shader_modules/texture_vert.spv index 6292c0d..5e1e3ce 100644 Binary files a/src/engine/vulkan_shader_modules/texture_vert.spv and b/src/engine/vulkan_shader_modules/texture_vert.spv differ diff --git a/src/engine/vulkangamerenderer.cpp b/src/engine/vulkangamerenderer.cpp index c975661..5f56d19 100644 --- a/src/engine/vulkangamerenderer.cpp +++ b/src/engine/vulkangamerenderer.cpp @@ -1,855 +1,547 @@ #include "vulkangamerenderer.h" -#include +#include +#include +#include +#include + #include +#include -#include "projectcontainer.h" +#include "gamescene.h" -// Note that the vertex data and the projection matrix assume OpenGL. With -// Vulkan Y is negated in clip space and the near/far plane is at 0/1 instead -// of -1/1. These will be corrected for by an extra transformation when -// calculating the modelview-projection matrix. -static float vertexData[] = { // Y up, front = CW - // x, y, z, u, v - -1, -1, 0, 0, 1, - -1, 1, 0, 0, 0, - 1, -1, 0, 1, 1, - 1, 1, 0, 1, 0 +namespace { + +struct Vertex +{ + float x, y, z, u, v; }; -static const int UNIFORM_DATA_SIZE = 16 * sizeof(float); +constexpr std::array quad {{ + {0.f, 0.f, 0.f, 0.f, 0.f}, + {0.f, 1.f, 0.f, 0.f, 1.f}, + {1.f, 0.f, 0.f, 1.f, 0.f}, + {1.f, 1.f, 0.f, 1.f, 1.f} +}}; -static inline VkDeviceSize aligned(VkDeviceSize v, VkDeviceSize byteAlign) +uint32_t memoryIndex(QVulkanWindow *window, uint32_t allowed, VkMemoryPropertyFlags required) { - return (v + byteAlign - 1) & ~(byteAlign - 1); + VkPhysicalDeviceMemoryProperties properties; + window->vulkanInstance()->functions()->vkGetPhysicalDeviceMemoryProperties( + window->physicalDevice(), &properties); + for (uint32_t i = 0; i < properties.memoryTypeCount; ++i) + if ((allowed & (1u << i)) && + (properties.memoryTypes[i].propertyFlags & required) == required) + return i; + return std::numeric_limits::max(); } -VulkanGameRenderer::VulkanGameRenderer(const ProjectContainer &project, const float &rotation, QVulkanWindow *w, bool msaa) : - m_window{w}, - m_project{project}, - m_rotation{rotation} +} + +VulkanGameRenderer::VulkanGameRenderer(const GameScene &scene, QVulkanWindow *window) : + m_scene{scene}, + m_window{window} { - if (msaa) - { - const QVector counts = w->supportedSampleCounts(); - qDebug() << "Supported sample counts:" << counts; - for (int s = 16; s >= 4; s /= 2) - { - if (counts.contains(s)) - { - qDebug("Requesting sample count %d", s); - m_window->setSampleCount(s); - break; - } - } - } } VkShaderModule VulkanGameRenderer::createShader(const QString &name) { - QByteArray blob; + QFile file{name}; + if (!file.open(QIODevice::ReadOnly)) { - QFile file(name); - if (!file.open(QIODevice::ReadOnly)) - { - qWarning("Failed to read shader %s", qPrintable(name)); - return VK_NULL_HANDLE; - } - blob = file.readAll(); - } - - VkShaderModuleCreateInfo shaderInfo; - memset(&shaderInfo, 0, sizeof(shaderInfo)); - shaderInfo.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO; - shaderInfo.codeSize = blob.size(); - shaderInfo.pCode = reinterpret_cast(blob.constData()); - VkShaderModule shaderModule; - VkResult err = m_devFuncs->vkCreateShaderModule(m_window->device(), &shaderInfo, nullptr, &shaderModule); - if (err != VK_SUCCESS) - { - qWarning("Failed to create shader module: %d", err); + qWarning("Failed to read Vulkan shader %s", qPrintable(name)); return VK_NULL_HANDLE; } + const QByteArray blob = file.readAll(); + VkShaderModuleCreateInfo info{}; + info.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO; + info.codeSize = static_cast(blob.size()); + info.pCode = reinterpret_cast(blob.constData()); - return shaderModule; + VkShaderModule shader = VK_NULL_HANDLE; + const VkResult result = m_devFuncs->vkCreateShaderModule(m_window->device(), &info, nullptr, &shader); + if (result != VK_SUCCESS) + qWarning("Failed to create Vulkan shader module: %d", result); + return shader; } -bool VulkanGameRenderer::createTextureFromFile(const QString &name) +bool VulkanGameRenderer::createTextureImage(const QSize &size, VkImageTiling tiling, + VkImageUsageFlags usage, VkImage *image, VkDeviceMemory *memory) { - QImage img{name}; - if (img.isNull()) - { - qWarning("Failed to load image %s", qPrintable(name)); + const VkDevice device = m_window->device(); + VkImageCreateInfo info{}; + info.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO; + info.imageType = VK_IMAGE_TYPE_2D; + info.format = m_texFormat; + info.extent = {uint32_t(size.width()), uint32_t(size.height()), 1}; + info.mipLevels = 1; + info.arrayLayers = 1; + info.samples = VK_SAMPLE_COUNT_1_BIT; + info.tiling = tiling; + info.usage = usage; + info.initialLayout = tiling == VK_IMAGE_TILING_LINEAR ? + VK_IMAGE_LAYOUT_PREINITIALIZED : VK_IMAGE_LAYOUT_UNDEFINED; + if (m_devFuncs->vkCreateImage(device, &info, nullptr, image) != VK_SUCCESS) return false; - } - return createTexture(img); + VkMemoryRequirements requirements; + m_devFuncs->vkGetImageMemoryRequirements(device, *image, &requirements); + const VkMemoryPropertyFlags flags = tiling == VK_IMAGE_TILING_LINEAR ? + VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT : + VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT; + const uint32_t index = memoryIndex(m_window, requirements.memoryTypeBits, flags); + if (index == std::numeric_limits::max()) + return false; + + VkMemoryAllocateInfo allocation{}; + allocation.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; + allocation.allocationSize = requirements.size; + allocation.memoryTypeIndex = index; + if (m_devFuncs->vkAllocateMemory(device, &allocation, nullptr, memory) != VK_SUCCESS) + return false; + return m_devFuncs->vkBindImageMemory(device, *image, *memory, 0) == VK_SUCCESS; } -bool VulkanGameRenderer::createTexture(const QImage &image) +bool VulkanGameRenderer::writeLinearImage(const QImage &image, VkImage target, VkDeviceMemory memory) { - // Convert to byte ordered RGBA8. Use premultiplied alpha, see pColorBlendState in the pipeline. - const auto img = image.convertToFormat(QImage::Format_RGBA8888_Premultiplied); - - QVulkanFunctions *f = m_window->vulkanInstance()->functions(); - VkDevice dev = m_window->device(); - - const bool srgb = false; //QCoreApplication::arguments().contains(QStringLiteral("--srgb")); - if (srgb) - qDebug("sRGB swapchain was requested, making texture sRGB too"); - - m_texFormat = srgb ? VK_FORMAT_R8G8B8A8_SRGB : VK_FORMAT_R8G8B8A8_UNORM; - - // Now we can either map and copy the image data directly, or have to go - // through a staging buffer to copy and convert into the internal optimal - // tiling format. - VkFormatProperties props; - f->vkGetPhysicalDeviceFormatProperties(m_window->physicalDevice(), m_texFormat, &props); - const bool canSampleLinear = (props.linearTilingFeatures & VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT); - const bool canSampleOptimal = (props.optimalTilingFeatures & VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT); - if (!canSampleLinear && !canSampleOptimal) - { - qWarning("Neither linear nor optimal image sampling is supported for RGBA8"); - return false; - } - - static bool alwaysStage = qEnvironmentVariableIntValue("QT_VK_FORCE_STAGE_TEX"); - - if (canSampleLinear && !alwaysStage) - { - if (!createTextureImage(img.size(), &m_texImage, &m_texMem, - VK_IMAGE_TILING_LINEAR, VK_IMAGE_USAGE_SAMPLED_BIT, - m_window->hostVisibleMemoryIndex())) - return false; - - if (!writeLinearImage(img, m_texImage, m_texMem)) - return false; - - m_texLayoutPending = true; - } - else - { - if (!createTextureImage(img.size(), &m_texStaging, &m_texStagingMem, - VK_IMAGE_TILING_LINEAR, VK_IMAGE_USAGE_TRANSFER_SRC_BIT, - m_window->hostVisibleMemoryIndex())) - return false; - - if (!createTextureImage(img.size(), &m_texImage, &m_texMem, - VK_IMAGE_TILING_OPTIMAL, VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT, - m_window->deviceLocalMemoryIndex())) - return false; - - if (!writeLinearImage(img, m_texStaging, m_texStagingMem)) - return false; - - m_texStagingPending = true; - } - - VkImageViewCreateInfo viewInfo; - memset(&viewInfo, 0, sizeof(viewInfo)); - viewInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO; - viewInfo.image = m_texImage; - viewInfo.viewType = VK_IMAGE_VIEW_TYPE_2D; - viewInfo.format = m_texFormat; - viewInfo.components.r = VK_COMPONENT_SWIZZLE_R; - viewInfo.components.g = VK_COMPONENT_SWIZZLE_G; - viewInfo.components.b = VK_COMPONENT_SWIZZLE_B; - viewInfo.components.a = VK_COMPONENT_SWIZZLE_A; - viewInfo.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; - viewInfo.subresourceRange.levelCount = viewInfo.subresourceRange.layerCount = 1; - - VkResult err = m_devFuncs->vkCreateImageView(dev, &viewInfo, nullptr, &m_texView); - if (err != VK_SUCCESS) - { - qWarning("Failed to create image view for texture: %d", err); - return false; - } - - m_texSize = img.size(); - - return true; -} - -bool VulkanGameRenderer::createTextureImage(const QSize &size, VkImage *image, VkDeviceMemory *mem, - VkImageTiling tiling, VkImageUsageFlags usage, uint32_t memIndex) -{ - VkDevice dev = m_window->device(); - - VkImageCreateInfo imageInfo; - memset(&imageInfo, 0, sizeof(imageInfo)); - imageInfo.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO; - imageInfo.imageType = VK_IMAGE_TYPE_2D; - imageInfo.format = m_texFormat; - imageInfo.extent.width = size.width(); - imageInfo.extent.height = size.height(); - imageInfo.extent.depth = 1; - imageInfo.mipLevels = 1; - imageInfo.arrayLayers = 1; - imageInfo.samples = VK_SAMPLE_COUNT_1_BIT; - imageInfo.tiling = tiling; - imageInfo.usage = usage; - imageInfo.initialLayout = VK_IMAGE_LAYOUT_PREINITIALIZED; - - VkResult err = m_devFuncs->vkCreateImage(dev, &imageInfo, nullptr, image); - if (err != VK_SUCCESS) - { - qWarning("Failed to create linear image for texture: %d", err); - return false; - } - - VkMemoryRequirements memReq; - m_devFuncs->vkGetImageMemoryRequirements(dev, *image, &memReq); - - if (!(memReq.memoryTypeBits & (1 << memIndex))) - { - VkPhysicalDeviceMemoryProperties physDevMemProps; - m_window->vulkanInstance()->functions()->vkGetPhysicalDeviceMemoryProperties(m_window->physicalDevice(), &physDevMemProps); - for (uint32_t i = 0; i < physDevMemProps.memoryTypeCount; ++i) - { - if (!(memReq.memoryTypeBits & (1 << i))) - continue; - memIndex = i; - } - } - - VkMemoryAllocateInfo allocInfo { - VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, - nullptr, - memReq.size, - memIndex - }; - qDebug("allocating %u bytes for texture image", uint32_t(memReq.size)); - - err = m_devFuncs->vkAllocateMemory(dev, &allocInfo, nullptr, mem); - if (err != VK_SUCCESS) - { - qWarning("Failed to allocate memory for linear image: %d", err); - return false; - } - - err = m_devFuncs->vkBindImageMemory(dev, *image, *mem, 0); - if (err != VK_SUCCESS) - { - qWarning("Failed to bind linear image memory: %d", err); - return false; - } - - return true; -} - -bool VulkanGameRenderer::writeLinearImage(const QImage &img, VkImage image, VkDeviceMemory memory) -{ - VkDevice dev = m_window->device(); - - VkImageSubresource subres { - VK_IMAGE_ASPECT_COLOR_BIT, - 0, // mip level - 0 - }; + const VkDevice device = m_window->device(); + VkImageSubresource subresource{VK_IMAGE_ASPECT_COLOR_BIT, 0, 0}; VkSubresourceLayout layout; - m_devFuncs->vkGetImageSubresourceLayout(dev, image, &subres, &layout); + m_devFuncs->vkGetImageSubresourceLayout(device, target, &subresource, &layout); - uchar *p; - VkResult err = m_devFuncs->vkMapMemory(dev, memory, layout.offset, layout.size, 0, reinterpret_cast(&p)); - if (err != VK_SUCCESS) - { - qWarning("Failed to map memory for linear image: %d", err); + uchar *mapped = nullptr; + if (m_devFuncs->vkMapMemory(device, memory, layout.offset, layout.size, 0, + reinterpret_cast(&mapped)) != VK_SUCCESS) return false; - } - - for (int y = 0; y < img.height(); ++y) - { - const uchar *line = img.constScanLine(y); - memcpy(p, line, img.width() * 4); - p += layout.rowPitch; - } - - m_devFuncs->vkUnmapMemory(dev, memory); + for (int y = 0; y < image.height(); ++y) + std::memcpy(mapped + y * layout.rowPitch, image.constScanLine(y), + std::size_t(image.width()) * 4); + m_devFuncs->vkUnmapMemory(device, memory); return true; } -void VulkanGameRenderer::ensureTexture() +bool VulkanGameRenderer::createTexture(const QImage &source, Texture &texture) { - if (!m_texLayoutPending && !m_texStagingPending) - return; + const QImage image = source.convertToFormat(QImage::Format_RGBA8888_Premultiplied); + texture.size = image.size(); - Q_ASSERT(m_texLayoutPending != m_texStagingPending); - VkCommandBuffer cb = m_window->currentCommandBuffer(); + VkFormatProperties properties; + m_window->vulkanInstance()->functions()->vkGetPhysicalDeviceFormatProperties( + m_window->physicalDevice(), m_texFormat, &properties); - VkImageMemoryBarrier barrier; - memset(&barrier, 0, sizeof(barrier)); - barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; - barrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; - barrier.subresourceRange.levelCount = barrier.subresourceRange.layerCount = 1; - - if (m_texLayoutPending) + if ((properties.linearTilingFeatures & VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT) && + !qEnvironmentVariableIntValue("QT_VK_FORCE_STAGE_TEX")) { - m_texLayoutPending = false; - - barrier.oldLayout = VK_IMAGE_LAYOUT_PREINITIALIZED; - barrier.newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; - barrier.srcAccessMask = VK_ACCESS_HOST_WRITE_BIT; - barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT; - barrier.image = m_texImage; - - m_devFuncs->vkCmdPipelineBarrier(cb, - VK_PIPELINE_STAGE_HOST_BIT, - VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, - 0, 0, nullptr, 0, nullptr, - 1, &barrier); + if (!createTextureImage(image.size(), VK_IMAGE_TILING_LINEAR, VK_IMAGE_USAGE_SAMPLED_BIT, + &texture.image, &texture.memory) || + !writeLinearImage(image, texture.image, texture.memory)) + return false; + texture.layoutPending = true; + } + else if (properties.optimalTilingFeatures & VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT) + { + if (!createTextureImage(image.size(), VK_IMAGE_TILING_LINEAR, VK_IMAGE_USAGE_TRANSFER_SRC_BIT, + &texture.stagingImage, &texture.stagingMemory) || + !createTextureImage(image.size(), VK_IMAGE_TILING_OPTIMAL, + VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT, + &texture.image, &texture.memory) || + !writeLinearImage(image, texture.stagingImage, texture.stagingMemory)) + return false; + texture.stagingPending = true; } else + return false; + + VkImageViewCreateInfo view{}; + view.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO; + view.image = texture.image; + view.viewType = VK_IMAGE_VIEW_TYPE_2D; + view.format = m_texFormat; + view.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; + view.subresourceRange.levelCount = 1; + view.subresourceRange.layerCount = 1; + return m_devFuncs->vkCreateImageView(m_window->device(), &view, nullptr, &texture.view) == VK_SUCCESS; +} + +void VulkanGameRenderer::ensureTextures() +{ + const VkCommandBuffer command = m_window->currentCommandBuffer(); + auto transition = [this, command](VkImage image, VkImageLayout oldLayout, + VkImageLayout newLayout, VkAccessFlags sourceAccess, + VkAccessFlags targetAccess, VkPipelineStageFlags sourceStage, + VkPipelineStageFlags targetStage) { + VkImageMemoryBarrier barrier{}; + barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; + barrier.srcAccessMask = sourceAccess; + barrier.dstAccessMask = targetAccess; + barrier.oldLayout = oldLayout; + barrier.newLayout = newLayout; + barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + barrier.image = image; + barrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; + barrier.subresourceRange.levelCount = 1; + barrier.subresourceRange.layerCount = 1; + m_devFuncs->vkCmdPipelineBarrier(command, sourceStage, targetStage, 0, + 0, nullptr, 0, nullptr, 1, &barrier); + }; + + for (Texture &texture : m_textures) { - m_texStagingPending = false; + if (texture.layoutPending) + { + transition(texture.image, VK_IMAGE_LAYOUT_PREINITIALIZED, + VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, + VK_ACCESS_HOST_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT, + VK_PIPELINE_STAGE_HOST_BIT, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT); + texture.layoutPending = false; + } + if (texture.stagingPending) + { + transition(texture.stagingImage, VK_IMAGE_LAYOUT_PREINITIALIZED, + VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, + VK_ACCESS_HOST_WRITE_BIT, VK_ACCESS_TRANSFER_READ_BIT, + VK_PIPELINE_STAGE_HOST_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT); + transition(texture.image, VK_IMAGE_LAYOUT_UNDEFINED, + VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, + 0, VK_ACCESS_TRANSFER_WRITE_BIT, + VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT); - barrier.oldLayout = VK_IMAGE_LAYOUT_PREINITIALIZED; - barrier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL; - barrier.srcAccessMask = VK_ACCESS_HOST_WRITE_BIT; - barrier.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT; - barrier.image = m_texStaging; - m_devFuncs->vkCmdPipelineBarrier(cb, - VK_PIPELINE_STAGE_HOST_BIT, - VK_PIPELINE_STAGE_TRANSFER_BIT, - 0, 0, nullptr, 0, nullptr, - 1, &barrier); - - barrier.oldLayout = VK_IMAGE_LAYOUT_PREINITIALIZED; - barrier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; - barrier.srcAccessMask = 0; - barrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; - barrier.image = m_texImage; - m_devFuncs->vkCmdPipelineBarrier(cb, - VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, - VK_PIPELINE_STAGE_TRANSFER_BIT, - 0, 0, nullptr, 0, nullptr, - 1, &barrier); - - VkImageCopy copyInfo; - memset(©Info, 0, sizeof(copyInfo)); - copyInfo.srcSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; - copyInfo.srcSubresource.layerCount = 1; - copyInfo.dstSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; - copyInfo.dstSubresource.layerCount = 1; - copyInfo.extent.width = m_texSize.width(); - copyInfo.extent.height = m_texSize.height(); - copyInfo.extent.depth = 1; - m_devFuncs->vkCmdCopyImage(cb, m_texStaging, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, - m_texImage, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, ©Info); - - barrier.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; - barrier.newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; - barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; - barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT; - barrier.image = m_texImage; - m_devFuncs->vkCmdPipelineBarrier(cb, - VK_PIPELINE_STAGE_TRANSFER_BIT, - VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, - 0, 0, nullptr, 0, nullptr, - 1, &barrier); + VkImageCopy copy{}; + copy.srcSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; + copy.srcSubresource.layerCount = 1; + copy.dstSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; + copy.dstSubresource.layerCount = 1; + copy.extent = {uint32_t(texture.size.width()), uint32_t(texture.size.height()), 1}; + m_devFuncs->vkCmdCopyImage(command, texture.stagingImage, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, + texture.image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, ©); + transition(texture.image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, + VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, + VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT, + VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT); + texture.stagingPending = false; + } } } void VulkanGameRenderer::initResources() { - qDebug("initResources"); + const VkDevice device = m_window->device(); + m_devFuncs = m_window->vulkanInstance()->deviceFunctions(device); - VkDevice dev = m_window->device(); - m_devFuncs = m_window->vulkanInstance()->deviceFunctions(dev); + VkBufferCreateInfo buffer{}; + buffer.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; + buffer.size = sizeof(quad); + buffer.usage = VK_BUFFER_USAGE_VERTEX_BUFFER_BIT; + if (m_devFuncs->vkCreateBuffer(device, &buffer, nullptr, &m_vertexBuffer) != VK_SUCCESS) + qFatal("Failed to create Vulkan vertex buffer"); - // Prepare the vertex and uniform data. The vertex data will never - // change so one buffer is sufficient regardless of the value of - // QVulkanWindow::CONCURRENT_FRAME_COUNT. Uniform data is changing per - // frame however so active frames have to have a dedicated copy. + VkMemoryRequirements requirements; + m_devFuncs->vkGetBufferMemoryRequirements(device, m_vertexBuffer, &requirements); + const uint32_t index = memoryIndex(m_window, requirements.memoryTypeBits, + VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); + if (index == std::numeric_limits::max()) + qFatal("No host-visible Vulkan vertex buffer memory"); - // Use just one memory allocation and one buffer. We will then specify the - // appropriate offsets for uniform buffers in the VkDescriptorBufferInfo. - // Have to watch out for - // VkPhysicalDeviceLimits::minUniformBufferOffsetAlignment, though. + VkMemoryAllocateInfo allocation{}; + allocation.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; + allocation.allocationSize = requirements.size; + allocation.memoryTypeIndex = index; + if (m_devFuncs->vkAllocateMemory(device, &allocation, nullptr, &m_vertexMemory) != VK_SUCCESS || + m_devFuncs->vkBindBufferMemory(device, m_vertexBuffer, m_vertexMemory, 0) != VK_SUCCESS) + qFatal("Failed to allocate Vulkan vertex buffer"); - // The uniform buffer is not strictly required in this example, we could - // have used push constants as well since our single matrix (64 bytes) fits - // into the spec mandated minimum limit of 128 bytes. However, once that - // limit is not sufficient, the per-frame buffers, as shown below, will - // become necessary. + void *mapped = nullptr; + if (m_devFuncs->vkMapMemory(device, m_vertexMemory, 0, sizeof(quad), 0, &mapped) != VK_SUCCESS) + qFatal("Failed to map Vulkan vertex buffer"); + std::memcpy(mapped, quad.data(), sizeof(quad)); + m_devFuncs->vkUnmapMemory(device, m_vertexMemory); - const int concurrentFrameCount = m_window->concurrentFrameCount(); - const VkPhysicalDeviceLimits *pdevLimits = &m_window->physicalDeviceProperties()->limits; - const VkDeviceSize uniAlign = pdevLimits->minUniformBufferOffsetAlignment; - qDebug("uniform buffer offset alignment is %u", (uint) uniAlign); - VkBufferCreateInfo bufInfo; - memset(&bufInfo, 0, sizeof(bufInfo)); - bufInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; - // Our internal layout is vertex, uniform, uniform, ... with each uniform buffer start offset aligned to uniAlign. - const VkDeviceSize vertexAllocSize = aligned(sizeof(vertexData), uniAlign); - const VkDeviceSize uniformAllocSize = aligned(UNIFORM_DATA_SIZE, uniAlign); - bufInfo.size = vertexAllocSize + concurrentFrameCount * uniformAllocSize; - bufInfo.usage = VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT; + VkSamplerCreateInfo sampler{}; + sampler.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO; + sampler.magFilter = VK_FILTER_NEAREST; + sampler.minFilter = VK_FILTER_NEAREST; + sampler.addressModeU = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE; + sampler.addressModeV = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE; + sampler.addressModeW = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE; + sampler.maxAnisotropy = 1.f; + if (m_devFuncs->vkCreateSampler(device, &sampler, nullptr, &m_sampler) != VK_SUCCESS) + qFatal("Failed to create Vulkan sprite sampler"); - VkResult err = m_devFuncs->vkCreateBuffer(dev, &bufInfo, nullptr, &m_buf); - if (err != VK_SUCCESS) - qFatal("Failed to create buffer: %d", err); + m_textures.resize(m_scene.textures.size()); + for (std::size_t i = 0; i < m_textures.size(); ++i) + if (!createTexture(m_scene.textures[i], m_textures[i])) + qFatal("Failed to upload Vulkan sprite texture %zu", i); - VkMemoryRequirements memReq; - m_devFuncs->vkGetBufferMemoryRequirements(dev, m_buf, &memReq); + const uint32_t textureCount = uint32_t(std::max(1, m_textures.size())); + VkDescriptorPoolSize poolSize{VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, textureCount}; + VkDescriptorPoolCreateInfo pool{}; + pool.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO; + pool.maxSets = textureCount; + pool.poolSizeCount = 1; + pool.pPoolSizes = &poolSize; + if (m_devFuncs->vkCreateDescriptorPool(device, &pool, nullptr, &m_descPool) != VK_SUCCESS) + qFatal("Failed to create Vulkan descriptor pool"); - VkMemoryAllocateInfo memAllocInfo { - VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, - nullptr, - memReq.size, - m_window->hostVisibleMemoryIndex() - }; + VkDescriptorSetLayoutBinding binding{}; + binding.binding = 0; + binding.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; + binding.descriptorCount = 1; + binding.stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT; + VkDescriptorSetLayoutCreateInfo setLayout{}; + setLayout.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO; + setLayout.bindingCount = 1; + setLayout.pBindings = &binding; + if (m_devFuncs->vkCreateDescriptorSetLayout(device, &setLayout, nullptr, &m_descSetLayout) != VK_SUCCESS) + qFatal("Failed to create Vulkan descriptor set layout"); - err = m_devFuncs->vkAllocateMemory(dev, &memAllocInfo, nullptr, &m_bufMem); - if (err != VK_SUCCESS) - qFatal("Failed to allocate memory: %d", err); - - err = m_devFuncs->vkBindBufferMemory(dev, m_buf, m_bufMem, 0); - if (err != VK_SUCCESS) - qFatal("Failed to bind buffer memory: %d", err); - - quint8 *p; - err = m_devFuncs->vkMapMemory(dev, m_bufMem, 0, memReq.size, 0, reinterpret_cast(&p)); - if (err != VK_SUCCESS) - qFatal("Failed to map memory: %d", err); - memcpy(p, vertexData, sizeof(vertexData)); - QMatrix4x4 ident; - memset(m_uniformBufInfo, 0, sizeof(m_uniformBufInfo)); - for (int i = 0; i < concurrentFrameCount; ++i) + for (Texture &texture : m_textures) { - const VkDeviceSize offset = vertexAllocSize + i * uniformAllocSize; - memcpy(p + offset, ident.constData(), 16 * sizeof(float)); - m_uniformBufInfo[i].buffer = m_buf; - m_uniformBufInfo[i].offset = offset; - m_uniformBufInfo[i].range = uniformAllocSize; - } - m_devFuncs->vkUnmapMemory(dev, m_bufMem); + VkDescriptorSetAllocateInfo set{}; + set.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO; + set.descriptorPool = m_descPool; + set.descriptorSetCount = 1; + set.pSetLayouts = &m_descSetLayout; + if (m_devFuncs->vkAllocateDescriptorSets(device, &set, &texture.descriptorSet) != VK_SUCCESS) + qFatal("Failed to allocate Vulkan texture descriptor"); - VkVertexInputBindingDescription vertexBindingDesc { - 0, // binding - 5 * sizeof(float), - VK_VERTEX_INPUT_RATE_VERTEX - }; - VkVertexInputAttributeDescription vertexAttrDesc[] { - { // position - 0, // location - 0, // binding - VK_FORMAT_R32G32B32_SFLOAT, - 0 - }, - { // texcoord - 1, - 0, - VK_FORMAT_R32G32_SFLOAT, - 3 * sizeof(float) - } - }; - - VkPipelineVertexInputStateCreateInfo vertexInputInfo; - vertexInputInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO; - vertexInputInfo.pNext = nullptr; - vertexInputInfo.flags = 0; - vertexInputInfo.vertexBindingDescriptionCount = 1; - vertexInputInfo.pVertexBindingDescriptions = &vertexBindingDesc; - vertexInputInfo.vertexAttributeDescriptionCount = 2; - vertexInputInfo.pVertexAttributeDescriptions = vertexAttrDesc; - - // Sampler. - VkSamplerCreateInfo samplerInfo; - memset(&samplerInfo, 0, sizeof(samplerInfo)); - samplerInfo.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO; - samplerInfo.magFilter = VK_FILTER_NEAREST; - samplerInfo.minFilter = VK_FILTER_NEAREST; - samplerInfo.addressModeU = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE; - samplerInfo.addressModeV = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE; - samplerInfo.addressModeW = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE; - samplerInfo.maxAnisotropy = 1.0f; - err = m_devFuncs->vkCreateSampler(dev, &samplerInfo, nullptr, &m_sampler); - if (err != VK_SUCCESS) - qFatal("Failed to create sampler: %d", err); - - if (m_project.sprites.empty() || - m_project.sprites.front().pixmaps.empty() || - m_project.sprites.front().pixmaps.front().isNull()) - qFatal("no sprites in game project!"); - - // Texture. - //if (!createTextureFromFile(QStringLiteral(":/qtgameengine/qt256.png"))) - // qFatal("Failed to create texture"); - if (!createTexture(m_project.sprites.front().pixmaps.front().toImage())) - qFatal("Failed to create texture"); - - // Set up descriptor set and its layout. - VkDescriptorPoolSize descPoolSizes[2] = { - { VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, uint32_t(concurrentFrameCount) }, - { VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, uint32_t(concurrentFrameCount) } - }; - VkDescriptorPoolCreateInfo descPoolInfo; - memset(&descPoolInfo, 0, sizeof(descPoolInfo)); - descPoolInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO; - descPoolInfo.maxSets = concurrentFrameCount; - descPoolInfo.poolSizeCount = 2; - descPoolInfo.pPoolSizes = descPoolSizes; - err = m_devFuncs->vkCreateDescriptorPool(dev, &descPoolInfo, nullptr, &m_descPool); - if (err != VK_SUCCESS) - qFatal("Failed to create descriptor pool: %d", err); - - VkDescriptorSetLayoutBinding layoutBinding[2] { - { - 0, // binding - VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, - 1, // descriptorCount - VK_SHADER_STAGE_VERTEX_BIT, - nullptr - }, - { - 1, // binding - VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, - 1, // descriptorCount - VK_SHADER_STAGE_FRAGMENT_BIT, - nullptr - } - }; - VkDescriptorSetLayoutCreateInfo descLayoutInfo { - VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO, - nullptr, - 0, - 2, // bindingCount - layoutBinding - }; - err = m_devFuncs->vkCreateDescriptorSetLayout(dev, &descLayoutInfo, nullptr, &m_descSetLayout); - if (err != VK_SUCCESS) - qFatal("Failed to create descriptor set layout: %d", err); - - for (int i = 0; i < concurrentFrameCount; ++i) - { - VkDescriptorSetAllocateInfo descSetAllocInfo { - VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO, - nullptr, - m_descPool, - 1, - &m_descSetLayout - }; - err = m_devFuncs->vkAllocateDescriptorSets(dev, &descSetAllocInfo, &m_descSet[i]); - if (err != VK_SUCCESS) - qFatal("Failed to allocate descriptor set: %d", err); - - VkWriteDescriptorSet descWrite[2]; - memset(descWrite, 0, sizeof(descWrite)); - descWrite[0].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; - descWrite[0].dstSet = m_descSet[i]; - descWrite[0].dstBinding = 0; - descWrite[0].descriptorCount = 1; - descWrite[0].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER; - descWrite[0].pBufferInfo = &m_uniformBufInfo[i]; - - VkDescriptorImageInfo descImageInfo { - m_sampler, - m_texView, - VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL - }; - - descWrite[1].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; - descWrite[1].dstSet = m_descSet[i]; - descWrite[1].dstBinding = 1; - descWrite[1].descriptorCount = 1; - descWrite[1].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; - descWrite[1].pImageInfo = &descImageInfo; - - m_devFuncs->vkUpdateDescriptorSets(dev, 2, descWrite, 0, nullptr); + VkDescriptorImageInfo imageInfo{m_sampler, texture.view, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL}; + VkWriteDescriptorSet write{}; + write.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; + write.dstSet = texture.descriptorSet; + write.dstBinding = 0; + write.descriptorCount = 1; + write.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; + write.pImageInfo = &imageInfo; + m_devFuncs->vkUpdateDescriptorSets(device, 1, &write, 0, nullptr); } - // Pipeline cache - VkPipelineCacheCreateInfo pipelineCacheInfo; - memset(&pipelineCacheInfo, 0, sizeof(pipelineCacheInfo)); - pipelineCacheInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO; - err = m_devFuncs->vkCreatePipelineCache(dev, &pipelineCacheInfo, nullptr, &m_pipelineCache); - if (err != VK_SUCCESS) - qFatal("Failed to create pipeline cache: %d", err); + VkPipelineCacheCreateInfo cache{}; + cache.sType = VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO; + if (m_devFuncs->vkCreatePipelineCache(device, &cache, nullptr, &m_pipelineCache) != VK_SUCCESS) + qFatal("Failed to create Vulkan pipeline cache"); - // Pipeline layout - VkPipelineLayoutCreateInfo pipelineLayoutInfo; - memset(&pipelineLayoutInfo, 0, sizeof(pipelineLayoutInfo)); - pipelineLayoutInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO; - pipelineLayoutInfo.setLayoutCount = 1; - pipelineLayoutInfo.pSetLayouts = &m_descSetLayout; - err = m_devFuncs->vkCreatePipelineLayout(dev, &pipelineLayoutInfo, nullptr, &m_pipelineLayout); - if (err != VK_SUCCESS) - qFatal("Failed to create pipeline layout: %d", err); + VkPushConstantRange push{}; + push.stageFlags = VK_SHADER_STAGE_VERTEX_BIT; + push.offset = 0; + push.size = 16 * sizeof(float); + VkPipelineLayoutCreateInfo pipelineLayout{}; + pipelineLayout.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO; + pipelineLayout.setLayoutCount = 1; + pipelineLayout.pSetLayouts = &m_descSetLayout; + pipelineLayout.pushConstantRangeCount = 1; + pipelineLayout.pPushConstantRanges = &push; + if (m_devFuncs->vkCreatePipelineLayout(device, &pipelineLayout, nullptr, &m_pipelineLayout) != VK_SUCCESS) + qFatal("Failed to create Vulkan pipeline layout"); - // Shaders - VkShaderModule vertShaderModule = createShader(QStringLiteral(":/qtgameengine/vulkan_shader_modules/texture_vert.spv")); - VkShaderModule fragShaderModule = createShader(QStringLiteral(":/qtgameengine/vulkan_shader_modules/texture_frag.spv")); + const VkShaderModule vertexShader = createShader(QStringLiteral(":/qtgameengine/vulkan_shader_modules/texture_vert.spv")); + const VkShaderModule fragmentShader = createShader(QStringLiteral(":/qtgameengine/vulkan_shader_modules/texture_frag.spv")); + if (!vertexShader || !fragmentShader) + qFatal("Failed to load Vulkan sprite shaders"); - // Graphics pipeline - VkGraphicsPipelineCreateInfo pipelineInfo; - memset(&pipelineInfo, 0, sizeof(pipelineInfo)); - pipelineInfo.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO; + VkPipelineShaderStageCreateInfo stages[2]{}; + stages[0].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; + stages[0].stage = VK_SHADER_STAGE_VERTEX_BIT; + stages[0].module = vertexShader; + stages[0].pName = "main"; + stages[1].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; + stages[1].stage = VK_SHADER_STAGE_FRAGMENT_BIT; + stages[1].module = fragmentShader; + stages[1].pName = "main"; - VkPipelineShaderStageCreateInfo shaderStages[2] { - { - VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, - nullptr, - 0, - VK_SHADER_STAGE_VERTEX_BIT, - vertShaderModule, - "main", - nullptr - }, - { - VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, - nullptr, - 0, - VK_SHADER_STAGE_FRAGMENT_BIT, - fragShaderModule, - "main", - nullptr - } + VkVertexInputBindingDescription vertexBinding{0, sizeof(Vertex), VK_VERTEX_INPUT_RATE_VERTEX}; + VkVertexInputAttributeDescription attributes[2]{ + {0, 0, VK_FORMAT_R32G32B32_SFLOAT, 0}, + {1, 0, VK_FORMAT_R32G32_SFLOAT, 3 * sizeof(float)} }; - pipelineInfo.stageCount = 2; - pipelineInfo.pStages = shaderStages; + VkPipelineVertexInputStateCreateInfo vertexInput{}; + vertexInput.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO; + vertexInput.vertexBindingDescriptionCount = 1; + vertexInput.pVertexBindingDescriptions = &vertexBinding; + vertexInput.vertexAttributeDescriptionCount = 2; + vertexInput.pVertexAttributeDescriptions = attributes; - pipelineInfo.pVertexInputState = &vertexInputInfo; + VkPipelineInputAssemblyStateCreateInfo assembly{}; + assembly.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO; + assembly.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP; - VkPipelineInputAssemblyStateCreateInfo ia; - memset(&ia, 0, sizeof(ia)); - ia.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO; - ia.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP; - pipelineInfo.pInputAssemblyState = &ia; + VkPipelineViewportStateCreateInfo viewport{}; + viewport.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO; + viewport.viewportCount = 1; + viewport.scissorCount = 1; - // The viewport and scissor will be set dynamically via vkCmdSetViewport/Scissor. - // This way the pipeline does not need to be touched when resizing the window. - VkPipelineViewportStateCreateInfo vp; - memset(&vp, 0, sizeof(vp)); - vp.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO; - vp.viewportCount = 1; - vp.scissorCount = 1; - pipelineInfo.pViewportState = &vp; + VkPipelineRasterizationStateCreateInfo raster{}; + raster.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO; + raster.polygonMode = VK_POLYGON_MODE_FILL; + raster.cullMode = VK_CULL_MODE_NONE; + raster.frontFace = VK_FRONT_FACE_CLOCKWISE; + raster.lineWidth = 1.f; - VkPipelineRasterizationStateCreateInfo rs; - memset(&rs, 0, sizeof(rs)); - rs.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO; - rs.polygonMode = VK_POLYGON_MODE_FILL; - rs.cullMode = VK_CULL_MODE_BACK_BIT; - rs.frontFace = VK_FRONT_FACE_CLOCKWISE; - rs.lineWidth = 1.0f; - pipelineInfo.pRasterizationState = &rs; + VkPipelineMultisampleStateCreateInfo multisample{}; + multisample.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO; + multisample.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT; - VkPipelineMultisampleStateCreateInfo ms; - memset(&ms, 0, sizeof(ms)); - ms.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO; - ms.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT; - pipelineInfo.pMultisampleState = &ms; + VkPipelineDepthStencilStateCreateInfo depth{}; + depth.sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO; + depth.depthTestEnable = VK_FALSE; + depth.depthWriteEnable = VK_FALSE; - VkPipelineDepthStencilStateCreateInfo ds; - memset(&ds, 0, sizeof(ds)); - ds.sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO; - ds.depthTestEnable = VK_TRUE; - ds.depthWriteEnable = VK_TRUE; - ds.depthCompareOp = VK_COMPARE_OP_LESS_OR_EQUAL; - pipelineInfo.pDepthStencilState = &ds; + VkPipelineColorBlendAttachmentState attachment{}; + attachment.blendEnable = VK_TRUE; + attachment.srcColorBlendFactor = VK_BLEND_FACTOR_ONE; + attachment.dstColorBlendFactor = VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA; + attachment.colorBlendOp = VK_BLEND_OP_ADD; + attachment.srcAlphaBlendFactor = VK_BLEND_FACTOR_ONE; + attachment.dstAlphaBlendFactor = VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA; + attachment.alphaBlendOp = VK_BLEND_OP_ADD; + attachment.colorWriteMask = VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | + VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT; + VkPipelineColorBlendStateCreateInfo blend{}; + blend.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO; + blend.attachmentCount = 1; + blend.pAttachments = &attachment; - VkPipelineColorBlendStateCreateInfo cb; - memset(&cb, 0, sizeof(cb)); - cb.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO; - // assume pre-multiplied alpha, blend, write out all of rgba - VkPipelineColorBlendAttachmentState att; - memset(&att, 0, sizeof(att)); - att.colorWriteMask = 0xF; - att.blendEnable = VK_TRUE; - att.srcColorBlendFactor = VK_BLEND_FACTOR_ONE; - att.dstColorBlendFactor = VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA; - att.colorBlendOp = VK_BLEND_OP_ADD; - att.srcAlphaBlendFactor = VK_BLEND_FACTOR_ONE; - att.dstAlphaBlendFactor = VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA; - att.alphaBlendOp = VK_BLEND_OP_ADD; - cb.attachmentCount = 1; - cb.pAttachments = &att; - pipelineInfo.pColorBlendState = &cb; + VkDynamicState dynamicStates[]{VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR}; + VkPipelineDynamicStateCreateInfo dynamic{}; + dynamic.sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO; + dynamic.dynamicStateCount = 2; + dynamic.pDynamicStates = dynamicStates; - VkDynamicState dynEnable[] = { VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR }; - VkPipelineDynamicStateCreateInfo dyn; - memset(&dyn, 0, sizeof(dyn)); - dyn.sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO; - dyn.dynamicStateCount = sizeof(dynEnable) / sizeof(VkDynamicState); - dyn.pDynamicStates = dynEnable; - pipelineInfo.pDynamicState = &dyn; + VkGraphicsPipelineCreateInfo pipeline{}; + pipeline.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO; + pipeline.stageCount = 2; + pipeline.pStages = stages; + pipeline.pVertexInputState = &vertexInput; + pipeline.pInputAssemblyState = &assembly; + pipeline.pViewportState = &viewport; + pipeline.pRasterizationState = &raster; + pipeline.pMultisampleState = &multisample; + pipeline.pDepthStencilState = &depth; + pipeline.pColorBlendState = &blend; + pipeline.pDynamicState = &dynamic; + pipeline.layout = m_pipelineLayout; + pipeline.renderPass = m_window->defaultRenderPass(); + if (m_devFuncs->vkCreateGraphicsPipelines(device, m_pipelineCache, 1, &pipeline, nullptr, &m_pipeline) != VK_SUCCESS) + qFatal("Failed to create Vulkan sprite pipeline"); - pipelineInfo.layout = m_pipelineLayout; - pipelineInfo.renderPass = m_window->defaultRenderPass(); - - err = m_devFuncs->vkCreateGraphicsPipelines(dev, m_pipelineCache, 1, &pipelineInfo, nullptr, &m_pipeline); - if (err != VK_SUCCESS) - qFatal("Failed to create graphics pipeline: %d", err); - - if (vertShaderModule) - m_devFuncs->vkDestroyShaderModule(dev, vertShaderModule, nullptr); - if (fragShaderModule) - m_devFuncs->vkDestroyShaderModule(dev, fragShaderModule, nullptr); + m_devFuncs->vkDestroyShaderModule(device, vertexShader, nullptr); + m_devFuncs->vkDestroyShaderModule(device, fragmentShader, nullptr); } void VulkanGameRenderer::initSwapChainResources() { - qDebug("initSwapChainResources"); - - // Projection matrix - m_proj = m_window->clipCorrectionMatrix(); // adjust for Vulkan-OpenGL clip space differences - const QSize sz = m_window->swapChainImageSize(); - m_proj.perspective(45.0f, sz.width() / (float) sz.height(), 0.01f, 100.0f); - m_proj.translate(0, 0, -4); + m_projection = m_window->clipCorrectionMatrix(); + m_projection.ortho(0.f, float(m_scene.roomSize.width()), + float(m_scene.roomSize.height()), 0.f, -1.f, 1.f); } void VulkanGameRenderer::releaseSwapChainResources() { - qDebug("releaseSwapChainResources"); } void VulkanGameRenderer::releaseResources() { - qDebug("releaseResources"); - - VkDevice dev = m_window->device(); - - if (m_sampler) - { - m_devFuncs->vkDestroySampler(dev, m_sampler, nullptr); - m_sampler = VK_NULL_HANDLE; - } - - if (m_texStaging) - { - m_devFuncs->vkDestroyImage(dev, m_texStaging, nullptr); - m_texStaging = VK_NULL_HANDLE; - } - - if (m_texStagingMem) - { - m_devFuncs->vkFreeMemory(dev, m_texStagingMem, nullptr); - m_texStagingMem = VK_NULL_HANDLE; - } - - if (m_texView) - { - m_devFuncs->vkDestroyImageView(dev, m_texView, nullptr); - m_texView = VK_NULL_HANDLE; - } - - if (m_texImage) - { - m_devFuncs->vkDestroyImage(dev, m_texImage, nullptr); - m_texImage = VK_NULL_HANDLE; - } - - if (m_texMem) - { - m_devFuncs->vkFreeMemory(dev, m_texMem, nullptr); - m_texMem = VK_NULL_HANDLE; - } + if (!m_devFuncs) + return; + const VkDevice device = m_window->device(); if (m_pipeline) - { - m_devFuncs->vkDestroyPipeline(dev, m_pipeline, nullptr); - m_pipeline = VK_NULL_HANDLE; - } - + m_devFuncs->vkDestroyPipeline(device, m_pipeline, nullptr); if (m_pipelineLayout) - { - m_devFuncs->vkDestroyPipelineLayout(dev, m_pipelineLayout, nullptr); - m_pipelineLayout = VK_NULL_HANDLE; - } - + m_devFuncs->vkDestroyPipelineLayout(device, m_pipelineLayout, nullptr); if (m_pipelineCache) - { - m_devFuncs->vkDestroyPipelineCache(dev, m_pipelineCache, nullptr); - m_pipelineCache = VK_NULL_HANDLE; - } - - if (m_descSetLayout) - { - m_devFuncs->vkDestroyDescriptorSetLayout(dev, m_descSetLayout, nullptr); - m_descSetLayout = VK_NULL_HANDLE; - } - + m_devFuncs->vkDestroyPipelineCache(device, m_pipelineCache, nullptr); if (m_descPool) - { - m_devFuncs->vkDestroyDescriptorPool(dev, m_descPool, nullptr); - m_descPool = VK_NULL_HANDLE; - } + m_devFuncs->vkDestroyDescriptorPool(device, m_descPool, nullptr); + if (m_descSetLayout) + m_devFuncs->vkDestroyDescriptorSetLayout(device, m_descSetLayout, nullptr); + if (m_sampler) + m_devFuncs->vkDestroySampler(device, m_sampler, nullptr); + m_pipeline = VK_NULL_HANDLE; + m_pipelineLayout = VK_NULL_HANDLE; + m_pipelineCache = VK_NULL_HANDLE; + m_descPool = VK_NULL_HANDLE; + m_descSetLayout = VK_NULL_HANDLE; + m_sampler = VK_NULL_HANDLE; - if (m_buf) + for (Texture &texture : m_textures) { - m_devFuncs->vkDestroyBuffer(dev, m_buf, nullptr); - m_buf = VK_NULL_HANDLE; + if (texture.view) + m_devFuncs->vkDestroyImageView(device, texture.view, nullptr); + if (texture.image) + m_devFuncs->vkDestroyImage(device, texture.image, nullptr); + if (texture.memory) + m_devFuncs->vkFreeMemory(device, texture.memory, nullptr); + if (texture.stagingImage) + m_devFuncs->vkDestroyImage(device, texture.stagingImage, nullptr); + if (texture.stagingMemory) + m_devFuncs->vkFreeMemory(device, texture.stagingMemory, nullptr); } + m_textures.clear(); - if (m_bufMem) - { - m_devFuncs->vkFreeMemory(dev, m_bufMem, nullptr); - m_bufMem = VK_NULL_HANDLE; - } + if (m_vertexBuffer) + m_devFuncs->vkDestroyBuffer(device, m_vertexBuffer, nullptr); + if (m_vertexMemory) + m_devFuncs->vkFreeMemory(device, m_vertexMemory, nullptr); + m_vertexBuffer = VK_NULL_HANDLE; + m_vertexMemory = VK_NULL_HANDLE; } void VulkanGameRenderer::startNextFrame() { - VkDevice dev = m_window->device(); - VkCommandBuffer cb = m_window->currentCommandBuffer(); - const QSize sz = m_window->swapChainImageSize(); + const VkCommandBuffer command = m_window->currentCommandBuffer(); + const QSize size = m_window->swapChainImageSize(); + ensureTextures(); - // Add the necessary barriers and do the host-linear -> device-optimal copy, if not yet done. - ensureTexture(); + VkClearValue clearValues[2]{}; + clearValues[0].color.float32[0] = 1.f; + clearValues[0].color.float32[1] = 1.f; + clearValues[0].color.float32[2] = 1.f; + clearValues[0].color.float32[3] = 1.f; + clearValues[1].depthStencil = {1.f, 0}; - VkClearColorValue clearColor = {{ 0, 0, 0, 1 }}; - VkClearDepthStencilValue clearDS = { 1, 0 }; - VkClearValue clearValues[2]; - memset(clearValues, 0, sizeof(clearValues)); - clearValues[0].color = clearColor; - clearValues[1].depthStencil = clearDS; + VkRenderPassBeginInfo begin{}; + begin.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO; + begin.renderPass = m_window->defaultRenderPass(); + begin.framebuffer = m_window->currentFramebuffer(); + begin.renderArea.extent = {uint32_t(size.width()), uint32_t(size.height())}; + begin.clearValueCount = 2; + begin.pClearValues = clearValues; + m_devFuncs->vkCmdBeginRenderPass(command, &begin, VK_SUBPASS_CONTENTS_INLINE); - VkRenderPassBeginInfo rpBeginInfo; - memset(&rpBeginInfo, 0, sizeof(rpBeginInfo)); - rpBeginInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO; - rpBeginInfo.renderPass = m_window->defaultRenderPass(); - rpBeginInfo.framebuffer = m_window->currentFramebuffer(); - rpBeginInfo.renderArea.extent.width = sz.width(); - rpBeginInfo.renderArea.extent.height = sz.height(); - rpBeginInfo.clearValueCount = 2; - rpBeginInfo.pClearValues = clearValues; - VkCommandBuffer cmdBuf = m_window->currentCommandBuffer(); - m_devFuncs->vkCmdBeginRenderPass(cmdBuf, &rpBeginInfo, VK_SUBPASS_CONTENTS_INLINE); + m_devFuncs->vkCmdBindPipeline(command, VK_PIPELINE_BIND_POINT_GRAPHICS, m_pipeline); + const VkDeviceSize vertexOffset = 0; + m_devFuncs->vkCmdBindVertexBuffers(command, 0, 1, &m_vertexBuffer, &vertexOffset); - quint8 *p; - VkResult err = m_devFuncs->vkMapMemory(dev, m_bufMem, m_uniformBufInfo[m_window->currentFrame()].offset, - UNIFORM_DATA_SIZE, 0, reinterpret_cast(&p)); - if (err != VK_SUCCESS) - qFatal("Failed to map memory: %d", err); - QMatrix4x4 m = m_proj; - m.rotate(m_rotation, 0, 0, 1); - memcpy(p, m.constData(), 16 * sizeof(float)); - m_devFuncs->vkUnmapMemory(dev, m_bufMem); + VkViewport viewport{}; + viewport.width = float(size.width()); + viewport.height = float(size.height()); + viewport.minDepth = 0.f; + viewport.maxDepth = 1.f; + m_devFuncs->vkCmdSetViewport(command, 0, 1, &viewport); + VkRect2D scissor{}; + scissor.extent = {uint32_t(size.width()), uint32_t(size.height())}; + m_devFuncs->vkCmdSetScissor(command, 0, 1, &scissor); - m_devFuncs->vkCmdBindPipeline(cb, VK_PIPELINE_BIND_POINT_GRAPHICS, m_pipeline); - m_devFuncs->vkCmdBindDescriptorSets(cb, VK_PIPELINE_BIND_POINT_GRAPHICS, m_pipelineLayout, 0, 1, - &m_descSet[m_window->currentFrame()], 0, nullptr); - VkDeviceSize vbOffset = 0; - m_devFuncs->vkCmdBindVertexBuffers(cb, 0, 1, &m_buf, &vbOffset); + for (const GameScene::Instance *instance : m_scene.drawOrder()) + { + if (!instance->visible || !instance->spriteIndex) + continue; + const std::size_t textureIndex = m_scene.textureFor(*instance); + const Texture &texture = m_textures.at(textureIndex); + const QPoint &origin = m_scene.sprites.at(*instance->spriteIndex).origin; - VkViewport viewport; - viewport.x = viewport.y = 0; - viewport.width = sz.width(); - viewport.height = sz.height(); - viewport.minDepth = 0; - viewport.maxDepth = 1; - m_devFuncs->vkCmdSetViewport(cb, 0, 1, &viewport); - - VkRect2D scissor; - scissor.offset.x = scissor.offset.y = 0; - scissor.extent.width = viewport.width; - scissor.extent.height = viewport.height; - m_devFuncs->vkCmdSetScissor(cb, 0, 1, &scissor); - - m_devFuncs->vkCmdDraw(cb, 4, 1, 0, 0); - - m_devFuncs->vkCmdEndRenderPass(cmdBuf); + QMatrix4x4 matrix = m_projection; + matrix.translate(float(instance->position.x() - origin.x()), + float(instance->position.y() - origin.y())); + matrix.scale(float(texture.size.width()), float(texture.size.height())); + m_devFuncs->vkCmdPushConstants(command, m_pipelineLayout, VK_SHADER_STAGE_VERTEX_BIT, + 0, 16 * sizeof(float), matrix.constData()); + m_devFuncs->vkCmdBindDescriptorSets(command, VK_PIPELINE_BIND_POINT_GRAPHICS, + m_pipelineLayout, 0, 1, &texture.descriptorSet, 0, nullptr); + m_devFuncs->vkCmdDraw(command, 4, 1, 0, 0); + } + m_devFuncs->vkCmdEndRenderPass(command); m_window->frameReady(); - m_window->requestUpdate(); // render continuously, throttled by the presentation rate } diff --git a/src/engine/vulkangamerenderer.h b/src/engine/vulkangamerenderer.h index 020c636..f3760b8 100644 --- a/src/engine/vulkangamerenderer.h +++ b/src/engine/vulkangamerenderer.h @@ -1,59 +1,57 @@ #pragma once -#include -#include +#include -struct ProjectContainer; +#include +#include + +struct GameScene; class VulkanGameRenderer : public QVulkanWindowRenderer { public: - VulkanGameRenderer(const ProjectContainer &project, const float &rotation, QVulkanWindow *w, bool msaa = false); + VulkanGameRenderer(const GameScene &scene, QVulkanWindow *window); void initResources() override; void initSwapChainResources() override; void releaseSwapChainResources() override; void releaseResources() override; - void startNextFrame() override; -protected: +private: + struct Texture + { + VkImage image = VK_NULL_HANDLE; + VkDeviceMemory memory = VK_NULL_HANDLE; + VkImageView view = VK_NULL_HANDLE; + VkImage stagingImage = VK_NULL_HANDLE; + VkDeviceMemory stagingMemory = VK_NULL_HANDLE; + VkDescriptorSet descriptorSet = VK_NULL_HANDLE; + QSize size; + bool layoutPending{}; + bool stagingPending{}; + }; + VkShaderModule createShader(const QString &name); - bool createTextureFromFile(const QString &name); - bool createTexture(const QImage &image); - bool createTextureImage(const QSize &size, VkImage *image, VkDeviceMemory *mem, - VkImageTiling tiling, VkImageUsageFlags usage, uint32_t memIndex); - bool writeLinearImage(const QImage &img, VkImage image, VkDeviceMemory memory); - void ensureTexture(); + bool createTexture(const QImage &image, Texture &texture); + bool createTextureImage(const QSize &size, VkImageTiling tiling, + VkImageUsageFlags usage, VkImage *image, VkDeviceMemory *memory); + bool writeLinearImage(const QImage &image, VkImage target, VkDeviceMemory memory); + void ensureTextures(); + const GameScene &m_scene; QVulkanWindow *m_window; - QVulkanDeviceFunctions *m_devFuncs; - - VkDeviceMemory m_bufMem = VK_NULL_HANDLE; - VkBuffer m_buf = VK_NULL_HANDLE; - VkDescriptorBufferInfo m_uniformBufInfo[QVulkanWindow::MAX_CONCURRENT_FRAME_COUNT]; + QVulkanDeviceFunctions *m_devFuncs{}; + VkBuffer m_vertexBuffer = VK_NULL_HANDLE; + VkDeviceMemory m_vertexMemory = VK_NULL_HANDLE; VkDescriptorPool m_descPool = VK_NULL_HANDLE; VkDescriptorSetLayout m_descSetLayout = VK_NULL_HANDLE; - VkDescriptorSet m_descSet[QVulkanWindow::MAX_CONCURRENT_FRAME_COUNT]; - VkPipelineCache m_pipelineCache = VK_NULL_HANDLE; VkPipelineLayout m_pipelineLayout = VK_NULL_HANDLE; VkPipeline m_pipeline = VK_NULL_HANDLE; - VkSampler m_sampler = VK_NULL_HANDLE; - VkImage m_texImage = VK_NULL_HANDLE; - VkDeviceMemory m_texMem = VK_NULL_HANDLE; - bool m_texLayoutPending = false; - VkImageView m_texView = VK_NULL_HANDLE; - VkImage m_texStaging = VK_NULL_HANDLE; - VkDeviceMemory m_texStagingMem = VK_NULL_HANDLE; - bool m_texStagingPending = false; - QSize m_texSize; - VkFormat m_texFormat; - - QMatrix4x4 m_proj; - - const ProjectContainer &m_project; - const float &m_rotation; + VkFormat m_texFormat = VK_FORMAT_R8G8B8A8_UNORM; + std::vector m_textures; + QMatrix4x4 m_projection; }; diff --git a/src/engine/vulkangamewindow.cpp b/src/engine/vulkangamewindow.cpp index 32b8a1c..71e2710 100644 --- a/src/engine/vulkangamewindow.cpp +++ b/src/engine/vulkangamewindow.cpp @@ -2,35 +2,39 @@ #include +#include "projectcontainer.h" +#include "gamescene.h" #include "vulkangamerenderer.h" -VulkanGameWindow::VulkanGameWindow(const ProjectContainer &project, const float &rotation, QWindow *parent) : +VulkanGameWindow::VulkanGameWindow(const ProjectContainer &project, const GameScene &scene, QWindow *parent) : QVulkanWindow{parent}, m_project{project}, - m_rotation{rotation} + m_scene{scene} { - setMinimumWidth(640); - setMaximumWidth(640); - setMinimumHeight(480); - setMaximumHeight(480); - resize(640, 480); + setPreferredColorFormats({VK_FORMAT_B8G8R8A8_UNORM, VK_FORMAT_R8G8B8A8_UNORM}); + if (!m_project.rooms.empty()) + { + resize(m_scene.roomSize); + if (!m_project.globalGameSettings.resizable) + { + setMinimumSize(m_scene.roomSize); + setMaximumSize(m_scene.roomSize); + } + setTitle(m_scene.caption); + } } QVulkanWindowRenderer *VulkanGameWindow::createRenderer() { - return new VulkanGameRenderer{m_project, m_rotation, this, true}; // try MSAA, when available + return new VulkanGameRenderer{m_scene, this}; } void VulkanGameWindow::keyPressEvent(QKeyEvent *event) { QVulkanWindow::keyPressEvent(event); - switch (event->key()) - { - case Qt::Key_Escape: + if (event->key() == Qt::Key_Escape && m_project.globalGameSettings.letEscEndGame) close(); - break; - } } void VulkanGameWindow::keyReleaseEvent(QKeyEvent *event) diff --git a/src/engine/vulkangamewindow.h b/src/engine/vulkangamewindow.h index d71fa05..bd0117c 100644 --- a/src/engine/vulkangamewindow.h +++ b/src/engine/vulkangamewindow.h @@ -4,11 +4,12 @@ #include struct ProjectContainer; +struct GameScene; class VulkanGameWindow : public QVulkanWindow { public: - explicit VulkanGameWindow(const ProjectContainer &project, const float &rotation, QWindow *parent = nullptr); + explicit VulkanGameWindow(const ProjectContainer &project, const GameScene &scene, QWindow *parent = nullptr); QVulkanWindowRenderer *createRenderer() override; @@ -18,5 +19,5 @@ protected: private: const ProjectContainer &m_project; - const float &m_rotation; + const GameScene &m_scene; };