From ba02d564f8a0b0167b96f247b6ad9d2bde05b6c8 Mon Sep 17 00:00:00 2001
From: Fernando Sahmkow <fsahmkow27@gmail.com>
Date: Sun, 15 Sep 2019 11:48:54 -0400
Subject: [PATCH 1/7] Video Core: initial Implementation of InstanceDraw
 Packaging

---
 src/video_core/engines/maxwell_3d.cpp         | 74 +++++++++++++++
 src/video_core/engines/maxwell_3d.h           | 23 ++++-
 src/video_core/macro_interpreter.cpp          |  2 +-
 src/video_core/rasterizer_interface.h         |  7 ++
 .../renderer_opengl/gl_rasterizer.cpp         | 89 +++++++++++++++++--
 .../renderer_opengl/gl_rasterizer.h           |  6 ++
 .../renderer_opengl/gl_shader_decompiler.cpp  |  2 +-
 7 files changed, 192 insertions(+), 11 deletions(-)

diff --git a/src/video_core/engines/maxwell_3d.cpp b/src/video_core/engines/maxwell_3d.cpp
index c7a3c85a0..48fc1a9e1 100644
--- a/src/video_core/engines/maxwell_3d.cpp
+++ b/src/video_core/engines/maxwell_3d.cpp
@@ -92,6 +92,10 @@ void Maxwell3D::InitializeRegisterDefaults() {
 
     // Some games (like Super Mario Odyssey) assume that SRGB is enabled.
     regs.framebuffer_srgb = 1;
+    mme_inline[MAXWELL3D_REG_INDEX(draw.vertex_end_gl)] = true;
+    mme_inline[MAXWELL3D_REG_INDEX(draw.vertex_begin_gl)] = true;
+    mme_inline[MAXWELL3D_REG_INDEX(vertex_buffer.count)] = true;
+    mme_inline[MAXWELL3D_REG_INDEX(index_array.count)] = true;
 }
 
 #define DIRTY_REGS_POS(field_name) (offsetof(Maxwell3D::DirtyRegs, field_name))
@@ -416,6 +420,76 @@ void Maxwell3D::CallMethod(const GPU::MethodCall& method_call) {
     }
 }
 
+void Maxwell3D::CallMethodFromMME(const GPU::MethodCall& method_call) {
+    const u32 method = method_call.method;
+    if (mme_inline[method]) {
+        regs.reg_array[method] = method_call.argument;
+        if (method == MAXWELL3D_REG_INDEX(vertex_buffer.count) ||
+            method == MAXWELL3D_REG_INDEX(index_array.count)) {
+            MMMEDrawMode expected_mode = method == MAXWELL3D_REG_INDEX(vertex_buffer.count)
+                                             ? MMMEDrawMode::Array
+                                             : MMMEDrawMode::Indexed;
+            u32 count = method_call.argument;
+            while (true) {
+                if (mme_draw.current_mode == MMMEDrawMode::Undefined) {
+                    mme_draw.current_mode = expected_mode;
+                    mme_draw.current_count = count;
+                    mme_draw.instance_count = 1;
+                    break;
+                } else {
+                    if (mme_draw.current_mode == expected_mode && count == mme_draw.current_count) {
+                        mme_draw.instance_count++;
+                        break;
+                    } else {
+                        FlushMMEInlineDraw();
+                    }
+                }
+            }
+        }
+    } else {
+        if (mme_draw.current_mode != MMMEDrawMode::Undefined) {
+            FlushMMEInlineDraw();
+        }
+        CallMethod(method_call);
+    }
+}
+
+void Maxwell3D::FlushMMEInlineDraw() {
+    LOG_DEBUG(HW_GPU, "called, topology={}, count={}", static_cast<u32>(regs.draw.topology.Value()),
+              regs.vertex_buffer.count);
+    ASSERT_MSG(!(regs.index_array.count && regs.vertex_buffer.count), "Both indexed and direct?");
+
+    auto debug_context = system.GetGPUDebugContext();
+
+    if (debug_context) {
+        debug_context->OnEvent(Tegra::DebugContext::Event::IncomingPrimitiveBatch, nullptr);
+    }
+
+    // Both instance configuration registers can not be set at the same time.
+    ASSERT_MSG(!regs.draw.instance_next || !regs.draw.instance_cont,
+               "Illegal combination of instancing parameters");
+
+    const bool is_indexed = mme_draw.current_mode == MMMEDrawMode::Indexed;
+    rasterizer.AccelerateDrawMultiBatch(is_indexed);
+
+    if (debug_context) {
+        debug_context->OnEvent(Tegra::DebugContext::Event::FinishedPrimitiveBatch, nullptr);
+    }
+
+    // TODO(bunnei): Below, we reset vertex count so that we can use these registers to determine if
+    // the game is trying to draw indexed or direct mode. This needs to be verified on HW still -
+    // it's possible that it is incorrect and that there is some other register used to specify the
+    // drawing mode.
+    if (is_indexed) {
+        regs.index_array.count = 0;
+    } else {
+        regs.vertex_buffer.count = 0;
+    }
+    mme_draw.current_mode = MMMEDrawMode::Undefined;
+    mme_draw.current_count = 0;
+    mme_draw.instance_count = 0;
+}
+
 void Maxwell3D::ProcessMacroUpload(u32 data) {
     ASSERT_MSG(regs.macros.upload_address < macro_memory.size(),
                "upload_address exceeded macro_memory size!");
diff --git a/src/video_core/engines/maxwell_3d.h b/src/video_core/engines/maxwell_3d.h
index e5ec90717..1547d930e 100644
--- a/src/video_core/engines/maxwell_3d.h
+++ b/src/video_core/engines/maxwell_3d.h
@@ -811,8 +811,9 @@ public:
                 INSERT_PADDING_WORDS(0x21);
 
                 u32 vb_element_base;
+                u32 vb_base_instance;
 
-                INSERT_PADDING_WORDS(0x36);
+                INSERT_PADDING_WORDS(0x35);
 
                 union {
                     BitField<0, 1, u32> c0;
@@ -1238,6 +1239,11 @@ public:
     /// Write the value to the register identified by method.
     void CallMethod(const GPU::MethodCall& method_call);
 
+    /// Write the value to the register identified by method.
+    void CallMethodFromMME(const GPU::MethodCall& method_call);
+
+    void FlushMMEInlineDraw();
+
     /// Given a Texture Handle, returns the TSC and TIC entries.
     Texture::FullTextureInfo GetTextureInfo(const Texture::TextureHandle tex_handle,
                                             std::size_t offset) const;
@@ -1263,6 +1269,18 @@ public:
         return execute_on;
     }
 
+    enum class MMMEDrawMode : u32 {
+        Undefined,
+        Array,
+        Indexed,
+    };
+
+    struct MMEDrawState {
+        MMMEDrawMode current_mode{MMMEDrawMode::Undefined};
+        u32 current_count;
+        u32 instance_count;
+    } mme_draw;
+
 private:
     void InitializeRegisterDefaults();
 
@@ -1275,6 +1293,8 @@ private:
     /// Start offsets of each macro in macro_memory
     std::array<u32, 0x80> macro_positions = {};
 
+    std::array<bool, Regs::NUM_REGS> mme_inline{};
+
     /// Memory for macro code
     MacroMemory macro_memory;
 
@@ -1402,6 +1422,7 @@ ASSERT_REG_POSITION(stencil_front_mask, 0x4E7);
 ASSERT_REG_POSITION(frag_color_clamp, 0x4EA);
 ASSERT_REG_POSITION(screen_y_control, 0x4EB);
 ASSERT_REG_POSITION(vb_element_base, 0x50D);
+ASSERT_REG_POSITION(vb_base_instance, 0x50E);
 ASSERT_REG_POSITION(clip_distance_enabled, 0x544);
 ASSERT_REG_POSITION(point_size, 0x546);
 ASSERT_REG_POSITION(zeta_enable, 0x54E);
diff --git a/src/video_core/macro_interpreter.cpp b/src/video_core/macro_interpreter.cpp
index 62afc0d11..dbaeac6db 100644
--- a/src/video_core/macro_interpreter.cpp
+++ b/src/video_core/macro_interpreter.cpp
@@ -257,7 +257,7 @@ void MacroInterpreter::SetMethodAddress(u32 address) {
 }
 
 void MacroInterpreter::Send(u32 value) {
-    maxwell3d.CallMethod({method_address.address, value});
+    maxwell3d.CallMethodFromMME({method_address.address, value});
     // Increment the method address by the method increment.
     method_address.address.Assign(method_address.address.Value() +
                                   method_address.increment.Value());
diff --git a/src/video_core/rasterizer_interface.h b/src/video_core/rasterizer_interface.h
index 6b3f2d50a..a37b84b8c 100644
--- a/src/video_core/rasterizer_interface.h
+++ b/src/video_core/rasterizer_interface.h
@@ -31,6 +31,9 @@ public:
     /// Draw the current batch of vertex arrays
     virtual void DrawArrays() = 0;
 
+    /// Draw the current batch of vertex arrays
+    virtual void DrawMultiArrays() = 0;
+
     /// Clear the current framebuffer
     virtual void Clear() = 0;
 
@@ -73,6 +76,10 @@ public:
         return false;
     }
 
+    virtual bool AccelerateDrawMultiBatch(bool is_indexed) {
+        return false;
+    }
+
     /// Increase/decrease the number of object in pages touching the specified region
     virtual void UpdatePagesCachedCount(VAddr addr, u64 size, int delta) {}
 
diff --git a/src/video_core/renderer_opengl/gl_rasterizer.cpp b/src/video_core/renderer_opengl/gl_rasterizer.cpp
index 4dd08bccb..5df7f3f56 100644
--- a/src/video_core/renderer_opengl/gl_rasterizer.cpp
+++ b/src/video_core/renderer_opengl/gl_rasterizer.cpp
@@ -405,6 +405,12 @@ bool RasterizerOpenGL::AccelerateDrawBatch(bool is_indexed) {
     return true;
 }
 
+bool RasterizerOpenGL::AccelerateDrawMultiBatch(bool is_indexed) {
+    accelerate_draw = is_indexed ? AccelDraw::Indexed : AccelDraw::Arrays;
+    DrawMultiArrays();
+    return true;
+}
+
 template <typename Map, typename Interval>
 static constexpr auto RangeFromInterval(Map& map, const Interval& interval) {
     return boost::make_iterator_range(map.equal_range(interval));
@@ -688,7 +694,7 @@ void RasterizerOpenGL::Clear() {
     }
 }
 
-void RasterizerOpenGL::DrawArrays() {
+void RasterizerOpenGL::DrawPrelude() {
     if (accelerate_draw == AccelDraw::Disabled)
         return;
 
@@ -743,10 +749,7 @@ void RasterizerOpenGL::DrawArrays() {
     // Upload vertex and index data.
     SetupVertexBuffer(vao);
     SetupVertexInstances(vao);
-    const GLintptr index_buffer_offset = SetupIndexBuffer();
-
-    // Setup draw parameters. It will automatically choose what glDraw* method to use.
-    const DrawParameters params = SetupDraw(index_buffer_offset);
+    index_buffer_offset = SetupIndexBuffer();
 
     // Prepare packed bindings.
     bind_ubo_pushbuffer.Setup(0);
@@ -754,7 +757,8 @@ void RasterizerOpenGL::DrawArrays() {
 
     // Setup shaders and their used resources.
     texture_cache.GuardSamplers(true);
-    SetupShaders(params.primitive_mode);
+    const auto primitive_mode = MaxwellToGL::PrimitiveTopology(gpu.regs.draw.topology);
+    SetupShaders(primitive_mode);
     texture_cache.GuardSamplers(false);
 
     ConfigureFramebuffers(state);
@@ -778,11 +782,80 @@ void RasterizerOpenGL::DrawArrays() {
     if (texture_cache.TextureBarrier()) {
         glTextureBarrier();
     }
+}
 
-    params.DispatchDraw();
+void RasterizerOpenGL::DrawArrays() {
+    DrawPrelude();
+
+    auto& maxwell3d = system.GPU().Maxwell3D();
+    auto& regs = maxwell3d.regs;
+    auto current_instance = maxwell3d.state.current_instance;
+    auto primitive_mode = MaxwellToGL::PrimitiveTopology(regs.draw.topology);
+    if (accelerate_draw == AccelDraw::Indexed) {
+        auto index_format = MaxwellToGL::IndexFormat(regs.index_array.format);
+        auto count = regs.index_array.count;
+        auto base_vertex = static_cast<GLint>(regs.vb_element_base);
+        const auto index_buffer_ptr = reinterpret_cast<const void*>(index_buffer_offset);
+        if (current_instance > 0) {
+            glDrawElementsInstancedBaseVertexBaseInstance(primitive_mode, count, index_format,
+                                                          index_buffer_ptr, 1, base_vertex,
+                                                          current_instance);
+        } else {
+            glDrawElementsBaseVertex(primitive_mode, count, index_format, index_buffer_ptr,
+                                     base_vertex);
+        }
+    } else {
+        auto count = regs.vertex_buffer.count;
+        auto vertex_first = regs.vertex_buffer.first;
+        if (current_instance > 0) {
+            glDrawArraysInstancedBaseInstance(primitive_mode, vertex_first, count, 1,
+                                              current_instance);
+        } else {
+            glDrawArrays(primitive_mode, vertex_first, count);
+        }
+    }
 
     accelerate_draw = AccelDraw::Disabled;
-    gpu.dirty.memory_general = false;
+    maxwell3d.dirty.memory_general = false;
+}
+
+#pragma optimize("", off)
+
+void RasterizerOpenGL::DrawMultiArrays() {
+    DrawPrelude();
+
+    auto& maxwell3d = system.GPU().Maxwell3D();
+    auto& regs = maxwell3d.regs;
+    auto& draw_setup = maxwell3d.mme_draw;
+    auto num_instances = draw_setup.instance_count;
+    auto base_instance = static_cast<GLint>(regs.vb_base_instance);
+    auto primitive_mode = MaxwellToGL::PrimitiveTopology(regs.draw.topology);
+    if (draw_setup.current_mode == Tegra::Engines::Maxwell3D::MMMEDrawMode::Indexed) {
+        auto index_format = MaxwellToGL::IndexFormat(regs.index_array.format);
+        auto count = regs.index_array.count;
+        auto base_vertex = static_cast<GLint>(regs.vb_element_base);
+        const auto index_buffer_ptr = reinterpret_cast<const void*>(index_buffer_offset);
+        if (num_instances > 1) {
+            glDrawElementsInstancedBaseVertexBaseInstance(primitive_mode, count, index_format,
+                                                          index_buffer_ptr, num_instances,
+                                                          base_vertex, base_instance);
+        } else {
+            glDrawElementsBaseVertex(primitive_mode, count, index_format, index_buffer_ptr,
+                                     base_vertex);
+        }
+    } else {
+        auto count = regs.vertex_buffer.count;
+        auto vertex_first = regs.vertex_buffer.first;
+        if (num_instances > 1) {
+            glDrawArraysInstancedBaseInstance(primitive_mode, vertex_first, count, num_instances,
+                                              base_instance);
+        } else {
+            glDrawArrays(primitive_mode, vertex_first, count);
+        }
+    }
+
+    accelerate_draw = AccelDraw::Disabled;
+    maxwell3d.dirty.memory_general = false;
 }
 
 void RasterizerOpenGL::DispatchCompute(GPUVAddr code_addr) {
diff --git a/src/video_core/renderer_opengl/gl_rasterizer.h b/src/video_core/renderer_opengl/gl_rasterizer.h
index eada752e0..63a914ff9 100644
--- a/src/video_core/renderer_opengl/gl_rasterizer.h
+++ b/src/video_core/renderer_opengl/gl_rasterizer.h
@@ -58,6 +58,7 @@ public:
     ~RasterizerOpenGL() override;
 
     void DrawArrays() override;
+    void DrawMultiArrays() override;
     void Clear() override;
     void DispatchCompute(GPUVAddr code_addr) override;
     void FlushAll() override;
@@ -72,6 +73,7 @@ public:
     bool AccelerateDisplay(const Tegra::FramebufferConfig& config, VAddr framebuffer_addr,
                            u32 pixel_stride) override;
     bool AccelerateDrawBatch(bool is_indexed) override;
+    bool AccelerateDrawMultiBatch(bool is_indexed) override;
     void UpdatePagesCachedCount(VAddr addr, u64 size, int delta) override;
     void LoadDiskResources(const std::atomic_bool& stop_loading,
                            const VideoCore::DiskResourceLoadCallback& callback) override;
@@ -136,6 +138,8 @@ private:
     void SetupGlobalMemory(const GLShader::GlobalMemoryEntry& entry, GPUVAddr gpu_addr,
                            std::size_t size);
 
+    void DrawPrelude();
+
     /// Configures the current textures to use for the draw command. Returns shaders texture buffer
     /// usage.
     TextureBufferUsage SetupDrawTextures(Tegra::Engines::Maxwell3D::Regs::ShaderStage stage,
@@ -252,6 +256,8 @@ private:
 
     DrawParameters SetupDraw(GLintptr index_buffer_offset);
 
+    GLintptr index_buffer_offset;
+
     void SetupShaders(GLenum primitive_mode);
 
     enum class AccelDraw { Disabled, Arrays, Indexed };
diff --git a/src/video_core/renderer_opengl/gl_shader_decompiler.cpp b/src/video_core/renderer_opengl/gl_shader_decompiler.cpp
index 14834d86a..62e32697e 100644
--- a/src/video_core/renderer_opengl/gl_shader_decompiler.cpp
+++ b/src/video_core/renderer_opengl/gl_shader_decompiler.cpp
@@ -964,7 +964,7 @@ private:
             switch (element) {
             case 2:
                 // Config pack's first value is instance_id.
-                return {"config_pack[0]", Type::Uint};
+                return {"gl_InstanceID", Type::Uint};
             case 3:
                 return {"gl_VertexID", Type::Int};
             }

From 7606da5611b5626790e99b4387e033eaea20c2cb Mon Sep 17 00:00:00 2001
From: Fernando Sahmkow <fsahmkow27@gmail.com>
Date: Sun, 15 Sep 2019 14:25:07 -0400
Subject: [PATCH 2/7] VideoCore: Corrections to the MME Inliner and removal of
 hacky instance management.

---
 src/video_core/engines/maxwell_3d.cpp         | 35 +++++++++++++----
 src/video_core/engines/maxwell_3d.h           |  7 +++-
 .../renderer_opengl/gl_rasterizer.cpp         | 38 +++++++++----------
 .../renderer_opengl/gl_shader_decompiler.cpp  | 10 ++++-
 src/video_core/shader/shader_ir.cpp           | 12 ++++++
 src/video_core/shader/shader_ir.h             | 10 +++++
 6 files changed, 81 insertions(+), 31 deletions(-)

diff --git a/src/video_core/engines/maxwell_3d.cpp b/src/video_core/engines/maxwell_3d.cpp
index 48fc1a9e1..d1f63a5eb 100644
--- a/src/video_core/engines/maxwell_3d.cpp
+++ b/src/video_core/engines/maxwell_3d.cpp
@@ -260,6 +260,9 @@ void Maxwell3D::CallMacroMethod(u32 method, std::size_t num_parameters, const u3
 
     // Execute the current macro.
     macro_interpreter.Execute(macro_positions[entry], num_parameters, parameters);
+    if (mme_draw.current_mode != MMMEDrawMode::Undefined) {
+        FlushMMEInlineDraw();
+    }
 }
 
 void Maxwell3D::CallMethod(const GPU::MethodCall& method_call) {
@@ -426,25 +429,37 @@ void Maxwell3D::CallMethodFromMME(const GPU::MethodCall& method_call) {
         regs.reg_array[method] = method_call.argument;
         if (method == MAXWELL3D_REG_INDEX(vertex_buffer.count) ||
             method == MAXWELL3D_REG_INDEX(index_array.count)) {
-            MMMEDrawMode expected_mode = method == MAXWELL3D_REG_INDEX(vertex_buffer.count)
-                                             ? MMMEDrawMode::Array
-                                             : MMMEDrawMode::Indexed;
-            u32 count = method_call.argument;
+            const MMMEDrawMode expected_mode = method == MAXWELL3D_REG_INDEX(vertex_buffer.count)
+                                                   ? MMMEDrawMode::Array
+                                                   : MMMEDrawMode::Indexed;
+            const u32 count = method_call.argument;
             while (true) {
                 if (mme_draw.current_mode == MMMEDrawMode::Undefined) {
-                    mme_draw.current_mode = expected_mode;
-                    mme_draw.current_count = count;
-                    mme_draw.instance_count = 1;
+                    if (mme_draw.gl_begin_consume) {
+                        mme_draw.current_mode = expected_mode;
+                        mme_draw.current_count = count;
+                        mme_draw.instance_count = 1;
+                        mme_draw.gl_begin_consume = false;
+                        mme_draw.gl_end_count = 0;
+                    }
                     break;
                 } else {
-                    if (mme_draw.current_mode == expected_mode && count == mme_draw.current_count) {
+                    if (mme_draw.current_mode == expected_mode && count == mme_draw.current_count &&
+                        mme_draw.instance_mode && mme_draw.gl_begin_consume) {
                         mme_draw.instance_count++;
+                        mme_draw.gl_begin_consume = false;
                         break;
                     } else {
                         FlushMMEInlineDraw();
                     }
                 }
             }
+        } else if (method == MAXWELL3D_REG_INDEX(draw.vertex_begin_gl)) {
+            mme_draw.instance_mode =
+                (regs.draw.instance_next != 0) || (regs.draw.instance_cont != 0);
+            mme_draw.gl_begin_consume = true;
+        } else {
+            mme_draw.gl_end_count++;
         }
     } else {
         if (mme_draw.current_mode != MMMEDrawMode::Undefined) {
@@ -458,6 +473,7 @@ void Maxwell3D::FlushMMEInlineDraw() {
     LOG_DEBUG(HW_GPU, "called, topology={}, count={}", static_cast<u32>(regs.draw.topology.Value()),
               regs.vertex_buffer.count);
     ASSERT_MSG(!(regs.index_array.count && regs.vertex_buffer.count), "Both indexed and direct?");
+    ASSERT(mme_draw.instance_count == mme_draw.gl_end_count);
 
     auto debug_context = system.GetGPUDebugContext();
 
@@ -488,6 +504,9 @@ void Maxwell3D::FlushMMEInlineDraw() {
     mme_draw.current_mode = MMMEDrawMode::Undefined;
     mme_draw.current_count = 0;
     mme_draw.instance_count = 0;
+    mme_draw.instance_mode = false;
+    mme_draw.gl_begin_consume = false;
+    mme_draw.gl_end_count = 0;
 }
 
 void Maxwell3D::ProcessMacroUpload(u32 data) {
diff --git a/src/video_core/engines/maxwell_3d.h b/src/video_core/engines/maxwell_3d.h
index 1547d930e..8fd3ec85c 100644
--- a/src/video_core/engines/maxwell_3d.h
+++ b/src/video_core/engines/maxwell_3d.h
@@ -1277,8 +1277,11 @@ public:
 
     struct MMEDrawState {
         MMMEDrawMode current_mode{MMMEDrawMode::Undefined};
-        u32 current_count;
-        u32 instance_count;
+        u32 current_count{};
+        u32 instance_count{};
+        bool instance_mode{};
+        bool gl_begin_consume{};
+        u32 gl_end_count{};
     } mme_draw;
 
 private:
diff --git a/src/video_core/renderer_opengl/gl_rasterizer.cpp b/src/video_core/renderer_opengl/gl_rasterizer.cpp
index 5df7f3f56..f71a22738 100644
--- a/src/video_core/renderer_opengl/gl_rasterizer.cpp
+++ b/src/video_core/renderer_opengl/gl_rasterizer.cpp
@@ -788,13 +788,13 @@ void RasterizerOpenGL::DrawArrays() {
     DrawPrelude();
 
     auto& maxwell3d = system.GPU().Maxwell3D();
-    auto& regs = maxwell3d.regs;
-    auto current_instance = maxwell3d.state.current_instance;
-    auto primitive_mode = MaxwellToGL::PrimitiveTopology(regs.draw.topology);
+    const auto& regs = maxwell3d.regs;
+    const auto current_instance = maxwell3d.state.current_instance;
+    const auto primitive_mode = MaxwellToGL::PrimitiveTopology(regs.draw.topology);
     if (accelerate_draw == AccelDraw::Indexed) {
-        auto index_format = MaxwellToGL::IndexFormat(regs.index_array.format);
-        auto count = regs.index_array.count;
-        auto base_vertex = static_cast<GLint>(regs.vb_element_base);
+        const auto index_format = MaxwellToGL::IndexFormat(regs.index_array.format);
+        const auto count = regs.index_array.count;
+        const auto base_vertex = static_cast<GLint>(regs.vb_element_base);
         const auto index_buffer_ptr = reinterpret_cast<const void*>(index_buffer_offset);
         if (current_instance > 0) {
             glDrawElementsInstancedBaseVertexBaseInstance(primitive_mode, count, index_format,
@@ -805,8 +805,8 @@ void RasterizerOpenGL::DrawArrays() {
                                      base_vertex);
         }
     } else {
-        auto count = regs.vertex_buffer.count;
-        auto vertex_first = regs.vertex_buffer.first;
+        const auto count = regs.vertex_buffer.count;
+        const auto vertex_first = regs.vertex_buffer.first;
         if (current_instance > 0) {
             glDrawArraysInstancedBaseInstance(primitive_mode, vertex_first, count, 1,
                                               current_instance);
@@ -819,21 +819,19 @@ void RasterizerOpenGL::DrawArrays() {
     maxwell3d.dirty.memory_general = false;
 }
 
-#pragma optimize("", off)
-
 void RasterizerOpenGL::DrawMultiArrays() {
     DrawPrelude();
 
     auto& maxwell3d = system.GPU().Maxwell3D();
-    auto& regs = maxwell3d.regs;
-    auto& draw_setup = maxwell3d.mme_draw;
-    auto num_instances = draw_setup.instance_count;
-    auto base_instance = static_cast<GLint>(regs.vb_base_instance);
-    auto primitive_mode = MaxwellToGL::PrimitiveTopology(regs.draw.topology);
+    const auto& regs = maxwell3d.regs;
+    const auto& draw_setup = maxwell3d.mme_draw;
+    const auto num_instances = draw_setup.instance_count;
+    const auto base_instance = static_cast<GLint>(regs.vb_base_instance);
+    const auto primitive_mode = MaxwellToGL::PrimitiveTopology(regs.draw.topology);
     if (draw_setup.current_mode == Tegra::Engines::Maxwell3D::MMMEDrawMode::Indexed) {
-        auto index_format = MaxwellToGL::IndexFormat(regs.index_array.format);
-        auto count = regs.index_array.count;
-        auto base_vertex = static_cast<GLint>(regs.vb_element_base);
+        const auto index_format = MaxwellToGL::IndexFormat(regs.index_array.format);
+        const auto count = regs.index_array.count;
+        const auto base_vertex = static_cast<GLint>(regs.vb_element_base);
         const auto index_buffer_ptr = reinterpret_cast<const void*>(index_buffer_offset);
         if (num_instances > 1) {
             glDrawElementsInstancedBaseVertexBaseInstance(primitive_mode, count, index_format,
@@ -844,8 +842,8 @@ void RasterizerOpenGL::DrawMultiArrays() {
                                      base_vertex);
         }
     } else {
-        auto count = regs.vertex_buffer.count;
-        auto vertex_first = regs.vertex_buffer.first;
+        const auto count = regs.vertex_buffer.count;
+        const auto vertex_first = regs.vertex_buffer.first;
         if (num_instances > 1) {
             glDrawArraysInstancedBaseInstance(primitive_mode, vertex_first, count, num_instances,
                                               base_instance);
diff --git a/src/video_core/renderer_opengl/gl_shader_decompiler.cpp b/src/video_core/renderer_opengl/gl_shader_decompiler.cpp
index 62e32697e..f7e86ab26 100644
--- a/src/video_core/renderer_opengl/gl_shader_decompiler.cpp
+++ b/src/video_core/renderer_opengl/gl_shader_decompiler.cpp
@@ -462,6 +462,14 @@ private:
             code.AddLine("float gl_PointSize;");
         }
 
+        if (ir.UsesInstanceId()) {
+            code.AddLine("int gl_InstanceID;");
+        }
+
+        if (ir.UsesVertexId()) {
+            code.AddLine("int gl_VertexID;");
+        }
+
         --code.scope;
         code.AddLine("}};");
         code.AddNewLine();
@@ -964,7 +972,7 @@ private:
             switch (element) {
             case 2:
                 // Config pack's first value is instance_id.
-                return {"gl_InstanceID", Type::Uint};
+                return {"gl_InstanceID", Type::Int};
             case 3:
                 return {"gl_VertexID", Type::Int};
             }
diff --git a/src/video_core/shader/shader_ir.cpp b/src/video_core/shader/shader_ir.cpp
index bbbab0bca..2c357f310 100644
--- a/src/video_core/shader/shader_ir.cpp
+++ b/src/video_core/shader/shader_ir.cpp
@@ -114,6 +114,18 @@ Node ShaderIR::GetOutputAttribute(Attribute::Index index, u64 element, Node buff
             break;
         }
     }
+    if (index == Attribute::Index::TessCoordInstanceIDVertexID) {
+        switch (element) {
+        case 2:
+            uses_instance_id = true;
+            break;
+        case 3:
+            uses_vertex_id = true;
+            break;
+        default:
+            break;
+        }
+    }
     if (index == Attribute::Index::ClipDistances0123 ||
         index == Attribute::Index::ClipDistances4567) {
         const auto clip_index =
diff --git a/src/video_core/shader/shader_ir.h b/src/video_core/shader/shader_ir.h
index 6aed9bb84..2f03d83ba 100644
--- a/src/video_core/shader/shader_ir.h
+++ b/src/video_core/shader/shader_ir.h
@@ -124,6 +124,14 @@ public:
         return uses_point_size;
     }
 
+    bool UsesInstanceId() const {
+        return uses_instance_id;
+    }
+
+    bool UsesVertexId() const {
+        return uses_vertex_id;
+    }
+
     bool HasPhysicalAttributes() const {
         return uses_physical_attributes;
     }
@@ -373,6 +381,8 @@ private:
     bool uses_viewport_index{};
     bool uses_point_size{};
     bool uses_physical_attributes{}; // Shader uses AL2P or physical attribute read/writes
+    bool uses_instance_id{};
+    bool uses_vertex_id{};
 
     Tegra::Shader::Header header;
 };

From c17655ce7465815bb69adf22c2d12f02a93d7d5c Mon Sep 17 00:00:00 2001
From: Fernando Sahmkow <fsahmkow27@gmail.com>
Date: Wed, 18 Sep 2019 07:51:05 -0400
Subject: [PATCH 3/7] Rasterizer: Refactor draw calls, remove deadcode and
 clean up.

---
 src/video_core/rasterizer_interface.h         |   2 +-
 .../renderer_opengl/gl_rasterizer.cpp         | 169 +++++++-----------
 .../renderer_opengl/gl_rasterizer.h           |   3 +-
 3 files changed, 68 insertions(+), 106 deletions(-)

diff --git a/src/video_core/rasterizer_interface.h b/src/video_core/rasterizer_interface.h
index a37b84b8c..fe0d82255 100644
--- a/src/video_core/rasterizer_interface.h
+++ b/src/video_core/rasterizer_interface.h
@@ -31,7 +31,7 @@ public:
     /// Draw the current batch of vertex arrays
     virtual void DrawArrays() = 0;
 
-    /// Draw the current batch of vertex arrays
+    /// Draw the current batch of multiple instasnces of vertex arrays
     virtual void DrawMultiArrays() = 0;
 
     /// Clear the current framebuffer
diff --git a/src/video_core/renderer_opengl/gl_rasterizer.cpp b/src/video_core/renderer_opengl/gl_rasterizer.cpp
index f71a22738..9ca832863 100644
--- a/src/video_core/renderer_opengl/gl_rasterizer.cpp
+++ b/src/video_core/renderer_opengl/gl_rasterizer.cpp
@@ -49,40 +49,6 @@ MICROPROFILE_DEFINE(OpenGL_Blits, "OpenGL", "Blits", MP_RGB(128, 128, 192));
 MICROPROFILE_DEFINE(OpenGL_CacheManagement, "OpenGL", "Cache Mgmt", MP_RGB(100, 255, 100));
 MICROPROFILE_DEFINE(OpenGL_PrimitiveAssembly, "OpenGL", "Prim Asmbl", MP_RGB(255, 100, 100));
 
-struct DrawParameters {
-    GLenum primitive_mode;
-    GLsizei count;
-    GLint current_instance;
-    bool use_indexed;
-
-    GLint vertex_first;
-
-    GLenum index_format;
-    GLint base_vertex;
-    GLintptr index_buffer_offset;
-
-    void DispatchDraw() const {
-        if (use_indexed) {
-            const auto index_buffer_ptr = reinterpret_cast<const void*>(index_buffer_offset);
-            if (current_instance > 0) {
-                glDrawElementsInstancedBaseVertexBaseInstance(primitive_mode, count, index_format,
-                                                              index_buffer_ptr, 1, base_vertex,
-                                                              current_instance);
-            } else {
-                glDrawElementsBaseVertex(primitive_mode, count, index_format, index_buffer_ptr,
-                                         base_vertex);
-            }
-        } else {
-            if (current_instance > 0) {
-                glDrawArraysInstancedBaseInstance(primitive_mode, vertex_first, count, 1,
-                                                  current_instance);
-            } else {
-                glDrawArrays(primitive_mode, vertex_first, count);
-            }
-        }
-    }
-};
-
 static std::size_t GetConstBufferSize(const Tegra::Engines::ConstBufferInfo& buffer,
                                       const GLShader::ConstBufferEntry& entry) {
     if (!entry.IsIndirect()) {
@@ -270,29 +236,6 @@ GLintptr RasterizerOpenGL::SetupIndexBuffer() {
     return offset;
 }
 
-DrawParameters RasterizerOpenGL::SetupDraw(GLintptr index_buffer_offset) {
-    const auto& gpu = system.GPU().Maxwell3D();
-    const auto& regs = gpu.regs;
-    const bool is_indexed = accelerate_draw == AccelDraw::Indexed;
-
-    DrawParameters params{};
-    params.current_instance = gpu.state.current_instance;
-
-    params.use_indexed = is_indexed;
-    params.primitive_mode = MaxwellToGL::PrimitiveTopology(regs.draw.topology);
-
-    if (is_indexed) {
-        params.index_format = MaxwellToGL::IndexFormat(regs.index_array.format);
-        params.count = regs.index_array.count;
-        params.index_buffer_offset = index_buffer_offset;
-        params.base_vertex = static_cast<GLint>(regs.vb_element_base);
-    } else {
-        params.count = regs.vertex_buffer.count;
-        params.vertex_first = regs.vertex_buffer.first;
-    }
-    return params;
-}
-
 void RasterizerOpenGL::SetupShaders(GLenum primitive_mode) {
     MICROPROFILE_SCOPE(OpenGL_Shader);
     auto& gpu = system.GPU().Maxwell3D();
@@ -784,36 +727,65 @@ void RasterizerOpenGL::DrawPrelude() {
     }
 }
 
+struct DrawParams {
+    bool is_indexed;
+    bool is_instanced;
+    GLenum primitive_mode;
+    GLint count;
+    GLint base_vertex;
+
+    // Indexed settings
+    GLenum index_format;
+    GLintptr index_buffer_offset;
+
+    // Instanced setting
+    GLint num_instances;
+    GLint base_instance;
+
+    void DispatchDraw() {
+        if (is_indexed) {
+            const auto index_buffer_ptr = reinterpret_cast<const void*>(index_buffer_offset);
+            if (is_instanced) {
+                glDrawElementsInstancedBaseVertexBaseInstance(primitive_mode, count, index_format,
+                                                              index_buffer_ptr, num_instances,
+                                                              base_vertex, base_instance);
+            } else {
+                glDrawElementsBaseVertex(primitive_mode, count, index_format, index_buffer_ptr,
+                                         base_vertex);
+            }
+        } else {
+            if (is_instanced) {
+                glDrawArraysInstancedBaseInstance(primitive_mode, base_vertex, count, num_instances,
+                                                  base_instance);
+            } else {
+                glDrawArrays(primitive_mode, base_vertex, count);
+            }
+        }
+    }
+};
+
 void RasterizerOpenGL::DrawArrays() {
     DrawPrelude();
 
     auto& maxwell3d = system.GPU().Maxwell3D();
     const auto& regs = maxwell3d.regs;
     const auto current_instance = maxwell3d.state.current_instance;
-    const auto primitive_mode = MaxwellToGL::PrimitiveTopology(regs.draw.topology);
-    if (accelerate_draw == AccelDraw::Indexed) {
-        const auto index_format = MaxwellToGL::IndexFormat(regs.index_array.format);
-        const auto count = regs.index_array.count;
-        const auto base_vertex = static_cast<GLint>(regs.vb_element_base);
-        const auto index_buffer_ptr = reinterpret_cast<const void*>(index_buffer_offset);
-        if (current_instance > 0) {
-            glDrawElementsInstancedBaseVertexBaseInstance(primitive_mode, count, index_format,
-                                                          index_buffer_ptr, 1, base_vertex,
-                                                          current_instance);
-        } else {
-            glDrawElementsBaseVertex(primitive_mode, count, index_format, index_buffer_ptr,
-                                     base_vertex);
-        }
+    DrawParams draw_call;
+    draw_call.is_indexed = accelerate_draw == AccelDraw::Indexed;
+    draw_call.num_instances = static_cast<GLint>(1);
+    draw_call.base_instance = static_cast<GLint>(current_instance);
+    draw_call.is_instanced = current_instance > 0;
+    draw_call.primitive_mode = MaxwellToGL::PrimitiveTopology(regs.draw.topology);
+    if (draw_call.is_indexed) {
+        draw_call.count = static_cast<GLint>(regs.index_array.count);
+        draw_call.base_vertex = static_cast<GLint>(regs.vb_element_base);
+        draw_call.index_format = MaxwellToGL::IndexFormat(regs.index_array.format);
+        draw_call.index_buffer_offset = index_buffer_offset;
     } else {
-        const auto count = regs.vertex_buffer.count;
-        const auto vertex_first = regs.vertex_buffer.first;
-        if (current_instance > 0) {
-            glDrawArraysInstancedBaseInstance(primitive_mode, vertex_first, count, 1,
-                                              current_instance);
-        } else {
-            glDrawArrays(primitive_mode, vertex_first, count);
-        }
+        draw_call.count = static_cast<GLint>(regs.vertex_buffer.count);
+        draw_call.base_vertex = static_cast<GLint>(regs.vertex_buffer.first);
     }
+    draw_call.DispatchDraw();
 
     accelerate_draw = AccelDraw::Disabled;
     maxwell3d.dirty.memory_general = false;
@@ -825,32 +797,23 @@ void RasterizerOpenGL::DrawMultiArrays() {
     auto& maxwell3d = system.GPU().Maxwell3D();
     const auto& regs = maxwell3d.regs;
     const auto& draw_setup = maxwell3d.mme_draw;
-    const auto num_instances = draw_setup.instance_count;
-    const auto base_instance = static_cast<GLint>(regs.vb_base_instance);
-    const auto primitive_mode = MaxwellToGL::PrimitiveTopology(regs.draw.topology);
-    if (draw_setup.current_mode == Tegra::Engines::Maxwell3D::MMMEDrawMode::Indexed) {
-        const auto index_format = MaxwellToGL::IndexFormat(regs.index_array.format);
-        const auto count = regs.index_array.count;
-        const auto base_vertex = static_cast<GLint>(regs.vb_element_base);
-        const auto index_buffer_ptr = reinterpret_cast<const void*>(index_buffer_offset);
-        if (num_instances > 1) {
-            glDrawElementsInstancedBaseVertexBaseInstance(primitive_mode, count, index_format,
-                                                          index_buffer_ptr, num_instances,
-                                                          base_vertex, base_instance);
-        } else {
-            glDrawElementsBaseVertex(primitive_mode, count, index_format, index_buffer_ptr,
-                                     base_vertex);
-        }
+    DrawParams draw_call;
+    draw_call.is_indexed =
+        draw_setup.current_mode == Tegra::Engines::Maxwell3D::MMMEDrawMode::Indexed;
+    draw_call.num_instances = static_cast<GLint>(draw_setup.instance_count);
+    draw_call.base_instance = static_cast<GLint>(regs.vb_base_instance);
+    draw_call.is_instanced = draw_setup.instance_count > 1;
+    draw_call.primitive_mode = MaxwellToGL::PrimitiveTopology(regs.draw.topology);
+    if (draw_call.is_indexed) {
+        draw_call.count = static_cast<GLint>(regs.index_array.count);
+        draw_call.base_vertex = static_cast<GLint>(regs.vb_element_base);
+        draw_call.index_format = MaxwellToGL::IndexFormat(regs.index_array.format);
+        draw_call.index_buffer_offset = index_buffer_offset;
     } else {
-        const auto count = regs.vertex_buffer.count;
-        const auto vertex_first = regs.vertex_buffer.first;
-        if (num_instances > 1) {
-            glDrawArraysInstancedBaseInstance(primitive_mode, vertex_first, count, num_instances,
-                                              base_instance);
-        } else {
-            glDrawArrays(primitive_mode, vertex_first, count);
-        }
+        draw_call.count = static_cast<GLint>(regs.vertex_buffer.count);
+        draw_call.base_vertex = static_cast<GLint>(regs.vertex_buffer.first);
     }
+    draw_call.DispatchDraw();
 
     accelerate_draw = AccelDraw::Disabled;
     maxwell3d.dirty.memory_general = false;
diff --git a/src/video_core/renderer_opengl/gl_rasterizer.h b/src/video_core/renderer_opengl/gl_rasterizer.h
index 63a914ff9..b4e21b9de 100644
--- a/src/video_core/renderer_opengl/gl_rasterizer.h
+++ b/src/video_core/renderer_opengl/gl_rasterizer.h
@@ -138,6 +138,7 @@ private:
     void SetupGlobalMemory(const GLShader::GlobalMemoryEntry& entry, GPUVAddr gpu_addr,
                            std::size_t size);
 
+    /// Syncs all the state, shaders, render targets and textures setting before a draw call.
     void DrawPrelude();
 
     /// Configures the current textures to use for the draw command. Returns shaders texture buffer
@@ -254,8 +255,6 @@ private:
 
     GLintptr SetupIndexBuffer();
 
-    DrawParameters SetupDraw(GLintptr index_buffer_offset);
-
     GLintptr index_buffer_offset;
 
     void SetupShaders(GLenum primitive_mode);

From d2ea592ddbf1d236ebb4eb58eedd2d0ffbe92455 Mon Sep 17 00:00:00 2001
From: Fernando Sahmkow <fsahmkow27@gmail.com>
Date: Wed, 18 Sep 2019 10:20:33 -0400
Subject: [PATCH 4/7] Rasterizer: Address Feedback and conscerns.

---
 .../renderer_opengl/gl_rasterizer.cpp         | 22 +++++++++----------
 1 file changed, 11 insertions(+), 11 deletions(-)

diff --git a/src/video_core/renderer_opengl/gl_rasterizer.cpp b/src/video_core/renderer_opengl/gl_rasterizer.cpp
index 9ca832863..b86aa49f3 100644
--- a/src/video_core/renderer_opengl/gl_rasterizer.cpp
+++ b/src/video_core/renderer_opengl/gl_rasterizer.cpp
@@ -728,19 +728,19 @@ void RasterizerOpenGL::DrawPrelude() {
 }
 
 struct DrawParams {
-    bool is_indexed;
-    bool is_instanced;
-    GLenum primitive_mode;
-    GLint count;
-    GLint base_vertex;
+    bool is_indexed{};
+    bool is_instanced{};
+    GLenum primitive_mode{};
+    GLint count{};
+    GLint base_vertex{};
 
     // Indexed settings
-    GLenum index_format;
-    GLintptr index_buffer_offset;
+    GLenum index_format{};
+    GLintptr index_buffer_offset{};
 
     // Instanced setting
-    GLint num_instances;
-    GLint base_instance;
+    GLint num_instances{};
+    GLint base_instance{};
 
     void DispatchDraw() {
         if (is_indexed) {
@@ -770,7 +770,7 @@ void RasterizerOpenGL::DrawArrays() {
     auto& maxwell3d = system.GPU().Maxwell3D();
     const auto& regs = maxwell3d.regs;
     const auto current_instance = maxwell3d.state.current_instance;
-    DrawParams draw_call;
+    DrawParams draw_call{};
     draw_call.is_indexed = accelerate_draw == AccelDraw::Indexed;
     draw_call.num_instances = static_cast<GLint>(1);
     draw_call.base_instance = static_cast<GLint>(current_instance);
@@ -797,7 +797,7 @@ void RasterizerOpenGL::DrawMultiArrays() {
     auto& maxwell3d = system.GPU().Maxwell3D();
     const auto& regs = maxwell3d.regs;
     const auto& draw_setup = maxwell3d.mme_draw;
-    DrawParams draw_call;
+    DrawParams draw_call{};
     draw_call.is_indexed =
         draw_setup.current_mode == Tegra::Engines::Maxwell3D::MMMEDrawMode::Indexed;
     draw_call.num_instances = static_cast<GLint>(draw_setup.instance_count);

From 7761e44d186deff278e51814bdec0c25e8e1a09c Mon Sep 17 00:00:00 2001
From: Fernando Sahmkow <fsahmkow27@gmail.com>
Date: Thu, 19 Sep 2019 11:41:07 -0400
Subject: [PATCH 5/7] Rasterizer: Refactor and simplify DrawBatch Interface.

---
 src/video_core/engines/maxwell_3d.cpp         |  4 +--
 src/video_core/rasterizer_interface.h         | 12 ++------
 .../renderer_opengl/gl_rasterizer.cpp         | 29 +++++++------------
 .../renderer_opengl/gl_rasterizer.h           |  6 ++--
 4 files changed, 16 insertions(+), 35 deletions(-)

diff --git a/src/video_core/engines/maxwell_3d.cpp b/src/video_core/engines/maxwell_3d.cpp
index d1f63a5eb..b8f071bc0 100644
--- a/src/video_core/engines/maxwell_3d.cpp
+++ b/src/video_core/engines/maxwell_3d.cpp
@@ -486,7 +486,7 @@ void Maxwell3D::FlushMMEInlineDraw() {
                "Illegal combination of instancing parameters");
 
     const bool is_indexed = mme_draw.current_mode == MMMEDrawMode::Indexed;
-    rasterizer.AccelerateDrawMultiBatch(is_indexed);
+    rasterizer.DrawMultiBatch(is_indexed);
 
     if (debug_context) {
         debug_context->OnEvent(Tegra::DebugContext::Event::FinishedPrimitiveBatch, nullptr);
@@ -657,7 +657,7 @@ void Maxwell3D::DrawArrays() {
     }
 
     const bool is_indexed{regs.index_array.count && !regs.vertex_buffer.count};
-    rasterizer.AccelerateDrawBatch(is_indexed);
+    rasterizer.DrawBatch(is_indexed);
 
     if (debug_context) {
         debug_context->OnEvent(Tegra::DebugContext::Event::FinishedPrimitiveBatch, nullptr);
diff --git a/src/video_core/rasterizer_interface.h b/src/video_core/rasterizer_interface.h
index fe0d82255..deadd70ec 100644
--- a/src/video_core/rasterizer_interface.h
+++ b/src/video_core/rasterizer_interface.h
@@ -29,10 +29,10 @@ public:
     virtual ~RasterizerInterface() {}
 
     /// Draw the current batch of vertex arrays
-    virtual void DrawArrays() = 0;
+    virtual bool DrawBatch(bool is_indexed) = 0;
 
     /// Draw the current batch of multiple instasnces of vertex arrays
-    virtual void DrawMultiArrays() = 0;
+    virtual bool DrawMultiBatch(bool is_indexed) = 0;
 
     /// Clear the current framebuffer
     virtual void Clear() = 0;
@@ -72,14 +72,6 @@ public:
         return false;
     }
 
-    virtual bool AccelerateDrawBatch(bool is_indexed) {
-        return false;
-    }
-
-    virtual bool AccelerateDrawMultiBatch(bool is_indexed) {
-        return false;
-    }
-
     /// Increase/decrease the number of object in pages touching the specified region
     virtual void UpdatePagesCachedCount(VAddr addr, u64 size, int delta) {}
 
diff --git a/src/video_core/renderer_opengl/gl_rasterizer.cpp b/src/video_core/renderer_opengl/gl_rasterizer.cpp
index b86aa49f3..b5c55482f 100644
--- a/src/video_core/renderer_opengl/gl_rasterizer.cpp
+++ b/src/video_core/renderer_opengl/gl_rasterizer.cpp
@@ -342,18 +342,6 @@ std::size_t RasterizerOpenGL::CalculateIndexBufferSize() const {
            static_cast<std::size_t>(regs.index_array.FormatSizeInBytes());
 }
 
-bool RasterizerOpenGL::AccelerateDrawBatch(bool is_indexed) {
-    accelerate_draw = is_indexed ? AccelDraw::Indexed : AccelDraw::Arrays;
-    DrawArrays();
-    return true;
-}
-
-bool RasterizerOpenGL::AccelerateDrawMultiBatch(bool is_indexed) {
-    accelerate_draw = is_indexed ? AccelDraw::Indexed : AccelDraw::Arrays;
-    DrawMultiArrays();
-    return true;
-}
-
 template <typename Map, typename Interval>
 static constexpr auto RangeFromInterval(Map& map, const Interval& interval) {
     return boost::make_iterator_range(map.equal_range(interval));
@@ -764,14 +752,15 @@ struct DrawParams {
     }
 };
 
-void RasterizerOpenGL::DrawArrays() {
+bool RasterizerOpenGL::DrawBatch(bool is_indexed) {
+    accelerate_draw = is_indexed ? AccelDraw::Indexed : AccelDraw::Arrays;
     DrawPrelude();
 
     auto& maxwell3d = system.GPU().Maxwell3D();
     const auto& regs = maxwell3d.regs;
     const auto current_instance = maxwell3d.state.current_instance;
     DrawParams draw_call{};
-    draw_call.is_indexed = accelerate_draw == AccelDraw::Indexed;
+    draw_call.is_indexed = is_indexed;
     draw_call.num_instances = static_cast<GLint>(1);
     draw_call.base_instance = static_cast<GLint>(current_instance);
     draw_call.is_instanced = current_instance > 0;
@@ -787,19 +776,20 @@ void RasterizerOpenGL::DrawArrays() {
     }
     draw_call.DispatchDraw();
 
-    accelerate_draw = AccelDraw::Disabled;
     maxwell3d.dirty.memory_general = false;
+    accelerate_draw = AccelDraw::Disabled;
+    return true;
 }
 
-void RasterizerOpenGL::DrawMultiArrays() {
+bool RasterizerOpenGL::DrawMultiBatch(bool is_indexed) {
+    accelerate_draw = is_indexed ? AccelDraw::Indexed : AccelDraw::Arrays;
     DrawPrelude();
 
     auto& maxwell3d = system.GPU().Maxwell3D();
     const auto& regs = maxwell3d.regs;
     const auto& draw_setup = maxwell3d.mme_draw;
     DrawParams draw_call{};
-    draw_call.is_indexed =
-        draw_setup.current_mode == Tegra::Engines::Maxwell3D::MMMEDrawMode::Indexed;
+    draw_call.is_indexed = is_indexed;
     draw_call.num_instances = static_cast<GLint>(draw_setup.instance_count);
     draw_call.base_instance = static_cast<GLint>(regs.vb_base_instance);
     draw_call.is_instanced = draw_setup.instance_count > 1;
@@ -815,8 +805,9 @@ void RasterizerOpenGL::DrawMultiArrays() {
     }
     draw_call.DispatchDraw();
 
-    accelerate_draw = AccelDraw::Disabled;
     maxwell3d.dirty.memory_general = false;
+    accelerate_draw = AccelDraw::Disabled;
+    return true;
 }
 
 void RasterizerOpenGL::DispatchCompute(GPUVAddr code_addr) {
diff --git a/src/video_core/renderer_opengl/gl_rasterizer.h b/src/video_core/renderer_opengl/gl_rasterizer.h
index b4e21b9de..682f0becc 100644
--- a/src/video_core/renderer_opengl/gl_rasterizer.h
+++ b/src/video_core/renderer_opengl/gl_rasterizer.h
@@ -57,8 +57,8 @@ public:
                               ScreenInfo& info);
     ~RasterizerOpenGL() override;
 
-    void DrawArrays() override;
-    void DrawMultiArrays() override;
+    bool DrawBatch(bool is_indexed) override;
+    bool DrawMultiBatch(bool is_indexed) override;
     void Clear() override;
     void DispatchCompute(GPUVAddr code_addr) override;
     void FlushAll() override;
@@ -72,8 +72,6 @@ public:
                                const Tegra::Engines::Fermi2D::Config& copy_config) override;
     bool AccelerateDisplay(const Tegra::FramebufferConfig& config, VAddr framebuffer_addr,
                            u32 pixel_stride) override;
-    bool AccelerateDrawBatch(bool is_indexed) override;
-    bool AccelerateDrawMultiBatch(bool is_indexed) override;
     void UpdatePagesCachedCount(VAddr addr, u64 size, int delta) override;
     void LoadDiskResources(const std::atomic_bool& stop_loading,
                            const VideoCore::DiskResourceLoadCallback& callback) override;

From 433e764bb0e8e7478f0cca675960c994fadae3ea Mon Sep 17 00:00:00 2001
From: Fernando Sahmkow <fsahmkow27@gmail.com>
Date: Fri, 20 Sep 2019 15:44:28 -0400
Subject: [PATCH 6/7] Rasterizer: Correct introduced bug where a conditional
 render wouldn't stop a draw call from executing

---
 .../renderer_opengl/gl_rasterizer.cpp         | 26 ++++++++++++-------
 1 file changed, 16 insertions(+), 10 deletions(-)

diff --git a/src/video_core/renderer_opengl/gl_rasterizer.cpp b/src/video_core/renderer_opengl/gl_rasterizer.cpp
index b5c55482f..a6fe7dd71 100644
--- a/src/video_core/renderer_opengl/gl_rasterizer.cpp
+++ b/src/video_core/renderer_opengl/gl_rasterizer.cpp
@@ -626,16 +626,8 @@ void RasterizerOpenGL::Clear() {
 }
 
 void RasterizerOpenGL::DrawPrelude() {
-    if (accelerate_draw == AccelDraw::Disabled)
-        return;
-
-    MICROPROFILE_SCOPE(OpenGL_Drawing);
     auto& gpu = system.GPU().Maxwell3D();
 
-    if (!gpu.ShouldExecute()) {
-        return;
-    }
-
     SyncColorMask();
     SyncFragmentColorClampState();
     SyncMultiSampleState();
@@ -754,9 +746,16 @@ struct DrawParams {
 
 bool RasterizerOpenGL::DrawBatch(bool is_indexed) {
     accelerate_draw = is_indexed ? AccelDraw::Indexed : AccelDraw::Arrays;
-    DrawPrelude();
+
+    MICROPROFILE_SCOPE(OpenGL_Drawing);
 
     auto& maxwell3d = system.GPU().Maxwell3D();
+    if (!maxwell3d.ShouldExecute()) {
+        return false;
+    }
+
+    DrawPrelude();
+
     const auto& regs = maxwell3d.regs;
     const auto current_instance = maxwell3d.state.current_instance;
     DrawParams draw_call{};
@@ -783,9 +782,16 @@ bool RasterizerOpenGL::DrawBatch(bool is_indexed) {
 
 bool RasterizerOpenGL::DrawMultiBatch(bool is_indexed) {
     accelerate_draw = is_indexed ? AccelDraw::Indexed : AccelDraw::Arrays;
-    DrawPrelude();
+
+    MICROPROFILE_SCOPE(OpenGL_Drawing);
 
     auto& maxwell3d = system.GPU().Maxwell3D();
+    if (!maxwell3d.ShouldExecute()) {
+        return false;
+    }
+
+    DrawPrelude();
+
     const auto& regs = maxwell3d.regs;
     const auto& draw_setup = maxwell3d.mme_draw;
     DrawParams draw_call{};

From 68f5aff64f231e77fed726b91619061e308b7b2d Mon Sep 17 00:00:00 2001
From: Fernando Sahmkow <fsahmkow27@gmail.com>
Date: Sun, 22 Sep 2019 07:23:13 -0400
Subject: [PATCH 7/7] Maxwell3D: Corrections and refactors to MME instance
 refactor

---
 src/video_core/engines/maxwell_3d.cpp         | 69 ++++++++++---------
 src/video_core/engines/maxwell_3d.h           |  7 +-
 src/video_core/rasterizer_interface.h         |  2 +-
 .../renderer_opengl/gl_rasterizer.cpp         | 12 +---
 4 files changed, 46 insertions(+), 44 deletions(-)

diff --git a/src/video_core/engines/maxwell_3d.cpp b/src/video_core/engines/maxwell_3d.cpp
index b8f071bc0..e9c15beff 100644
--- a/src/video_core/engines/maxwell_3d.cpp
+++ b/src/video_core/engines/maxwell_3d.cpp
@@ -260,7 +260,7 @@ void Maxwell3D::CallMacroMethod(u32 method, std::size_t num_parameters, const u3
 
     // Execute the current macro.
     macro_interpreter.Execute(macro_positions[entry], num_parameters, parameters);
-    if (mme_draw.current_mode != MMMEDrawMode::Undefined) {
+    if (mme_draw.current_mode != MMEDrawMode::Undefined) {
         FlushMMEInlineDraw();
     }
 }
@@ -423,37 +423,40 @@ void Maxwell3D::CallMethod(const GPU::MethodCall& method_call) {
     }
 }
 
+void Maxwell3D::StepInstance(const MMEDrawMode expected_mode, const u32 count) {
+    if (mme_draw.current_mode == MMEDrawMode::Undefined) {
+        if (mme_draw.gl_begin_consume) {
+            mme_draw.current_mode = expected_mode;
+            mme_draw.current_count = count;
+            mme_draw.instance_count = 1;
+            mme_draw.gl_begin_consume = false;
+            mme_draw.gl_end_count = 0;
+        }
+        return;
+    } else {
+        if (mme_draw.current_mode == expected_mode && count == mme_draw.current_count &&
+            mme_draw.instance_mode && mme_draw.gl_begin_consume) {
+            mme_draw.instance_count++;
+            mme_draw.gl_begin_consume = false;
+            return;
+        } else {
+            FlushMMEInlineDraw();
+        }
+    }
+    // Tail call in case it needs to retry.
+    StepInstance(expected_mode, count);
+}
+
 void Maxwell3D::CallMethodFromMME(const GPU::MethodCall& method_call) {
     const u32 method = method_call.method;
     if (mme_inline[method]) {
         regs.reg_array[method] = method_call.argument;
         if (method == MAXWELL3D_REG_INDEX(vertex_buffer.count) ||
             method == MAXWELL3D_REG_INDEX(index_array.count)) {
-            const MMMEDrawMode expected_mode = method == MAXWELL3D_REG_INDEX(vertex_buffer.count)
-                                                   ? MMMEDrawMode::Array
-                                                   : MMMEDrawMode::Indexed;
-            const u32 count = method_call.argument;
-            while (true) {
-                if (mme_draw.current_mode == MMMEDrawMode::Undefined) {
-                    if (mme_draw.gl_begin_consume) {
-                        mme_draw.current_mode = expected_mode;
-                        mme_draw.current_count = count;
-                        mme_draw.instance_count = 1;
-                        mme_draw.gl_begin_consume = false;
-                        mme_draw.gl_end_count = 0;
-                    }
-                    break;
-                } else {
-                    if (mme_draw.current_mode == expected_mode && count == mme_draw.current_count &&
-                        mme_draw.instance_mode && mme_draw.gl_begin_consume) {
-                        mme_draw.instance_count++;
-                        mme_draw.gl_begin_consume = false;
-                        break;
-                    } else {
-                        FlushMMEInlineDraw();
-                    }
-                }
-            }
+            const MMEDrawMode expected_mode = method == MAXWELL3D_REG_INDEX(vertex_buffer.count)
+                                                  ? MMEDrawMode::Array
+                                                  : MMEDrawMode::Indexed;
+            StepInstance(expected_mode, method_call.argument);
         } else if (method == MAXWELL3D_REG_INDEX(draw.vertex_begin_gl)) {
             mme_draw.instance_mode =
                 (regs.draw.instance_next != 0) || (regs.draw.instance_cont != 0);
@@ -462,7 +465,7 @@ void Maxwell3D::CallMethodFromMME(const GPU::MethodCall& method_call) {
             mme_draw.gl_end_count++;
         }
     } else {
-        if (mme_draw.current_mode != MMMEDrawMode::Undefined) {
+        if (mme_draw.current_mode != MMEDrawMode::Undefined) {
             FlushMMEInlineDraw();
         }
         CallMethod(method_call);
@@ -485,8 +488,10 @@ void Maxwell3D::FlushMMEInlineDraw() {
     ASSERT_MSG(!regs.draw.instance_next || !regs.draw.instance_cont,
                "Illegal combination of instancing parameters");
 
-    const bool is_indexed = mme_draw.current_mode == MMMEDrawMode::Indexed;
-    rasterizer.DrawMultiBatch(is_indexed);
+    const bool is_indexed = mme_draw.current_mode == MMEDrawMode::Indexed;
+    if (ShouldExecute()) {
+        rasterizer.DrawMultiBatch(is_indexed);
+    }
 
     if (debug_context) {
         debug_context->OnEvent(Tegra::DebugContext::Event::FinishedPrimitiveBatch, nullptr);
@@ -501,7 +506,7 @@ void Maxwell3D::FlushMMEInlineDraw() {
     } else {
         regs.vertex_buffer.count = 0;
     }
-    mme_draw.current_mode = MMMEDrawMode::Undefined;
+    mme_draw.current_mode = MMEDrawMode::Undefined;
     mme_draw.current_count = 0;
     mme_draw.instance_count = 0;
     mme_draw.instance_mode = false;
@@ -657,7 +662,9 @@ void Maxwell3D::DrawArrays() {
     }
 
     const bool is_indexed{regs.index_array.count && !regs.vertex_buffer.count};
-    rasterizer.DrawBatch(is_indexed);
+    if (ShouldExecute()) {
+        rasterizer.DrawBatch(is_indexed);
+    }
 
     if (debug_context) {
         debug_context->OnEvent(Tegra::DebugContext::Event::FinishedPrimitiveBatch, nullptr);
diff --git a/src/video_core/engines/maxwell_3d.h b/src/video_core/engines/maxwell_3d.h
index 8fd3ec85c..4c97759ed 100644
--- a/src/video_core/engines/maxwell_3d.h
+++ b/src/video_core/engines/maxwell_3d.h
@@ -1269,14 +1269,14 @@ public:
         return execute_on;
     }
 
-    enum class MMMEDrawMode : u32 {
+    enum class MMEDrawMode : u32 {
         Undefined,
         Array,
         Indexed,
     };
 
     struct MMEDrawState {
-        MMMEDrawMode current_mode{MMMEDrawMode::Undefined};
+        MMEDrawMode current_mode{MMEDrawMode::Undefined};
         u32 current_count{};
         u32 instance_count{};
         bool instance_mode{};
@@ -1369,6 +1369,9 @@ private:
 
     /// Handles a write to the VERTEX_END_GL register, triggering a draw.
     void DrawArrays();
+
+    // Handles a instance drawcall from MME
+    void StepInstance(MMEDrawMode expected_mode, u32 count);
 };
 
 #define ASSERT_REG_POSITION(field_name, position)                                                  \
diff --git a/src/video_core/rasterizer_interface.h b/src/video_core/rasterizer_interface.h
index deadd70ec..5b0eca9e2 100644
--- a/src/video_core/rasterizer_interface.h
+++ b/src/video_core/rasterizer_interface.h
@@ -31,7 +31,7 @@ public:
     /// Draw the current batch of vertex arrays
     virtual bool DrawBatch(bool is_indexed) = 0;
 
-    /// Draw the current batch of multiple instasnces of vertex arrays
+    /// Draw the current batch of multiple instances of vertex arrays
     virtual bool DrawMultiBatch(bool is_indexed) = 0;
 
     /// Clear the current framebuffer
diff --git a/src/video_core/renderer_opengl/gl_rasterizer.cpp b/src/video_core/renderer_opengl/gl_rasterizer.cpp
index a6fe7dd71..246b892c5 100644
--- a/src/video_core/renderer_opengl/gl_rasterizer.cpp
+++ b/src/video_core/renderer_opengl/gl_rasterizer.cpp
@@ -749,13 +749,9 @@ bool RasterizerOpenGL::DrawBatch(bool is_indexed) {
 
     MICROPROFILE_SCOPE(OpenGL_Drawing);
 
-    auto& maxwell3d = system.GPU().Maxwell3D();
-    if (!maxwell3d.ShouldExecute()) {
-        return false;
-    }
-
     DrawPrelude();
 
+    auto& maxwell3d = system.GPU().Maxwell3D();
     const auto& regs = maxwell3d.regs;
     const auto current_instance = maxwell3d.state.current_instance;
     DrawParams draw_call{};
@@ -785,13 +781,9 @@ bool RasterizerOpenGL::DrawMultiBatch(bool is_indexed) {
 
     MICROPROFILE_SCOPE(OpenGL_Drawing);
 
-    auto& maxwell3d = system.GPU().Maxwell3D();
-    if (!maxwell3d.ShouldExecute()) {
-        return false;
-    }
-
     DrawPrelude();
 
+    auto& maxwell3d = system.GPU().Maxwell3D();
     const auto& regs = maxwell3d.regs;
     const auto& draw_setup = maxwell3d.mme_draw;
     DrawParams draw_call{};