To add gray grid lines to your OpenGL window with ModernGL, you will need to render a series of lines across your viewport. Since your current setup is fairly basic, we can start by setting up a simple vertex array object (VAO) specifically for the grid lines. Below is a modified version of your code which includes a simple grid rendered with gray lines:
python
import glfw
import moderngl
import numpy as np
# Initialize GLFW
glfw.init()
window = glfw.create_window(400, 300, "Window with Grid", None, None)
glfw.make_context_current(window)
# Create a ModernGL context
ctx = moderngl.create_context()
# Define shader for the grid
vertex_shader = '''
#version 330
in vec2 in_vert;
void main() {
gl_Position = vec4(in_vert, 0.0, 1.0);
}
'''
fragment_shader = '''
#version 330
out vec4 out_color;
void main() {
out_color = vec4(0.5, 0.5, 0.5, 1.0); // Gray grid lines
}
'''
# Create a program with the shaders
prog = ctx.program(vertex_shader=vertex_shader, fragment_shader=fragment_shader)
# Define grid lines data
grid_vertices = []
num_lines = 10
for i in range(num_lines + 1):
fraction = i / num_lines
# Vertical lines
grid_vertices.extend([fraction * 2 - 1, -1.0]) # x1, y1
grid_vertices.extend([fraction * 2 - 1, 1.0]) # x2, y2
# Horizontal lines
grid_vertices.extend([-1.0, fraction * 2 - 1]) # x1, y1
grid_vertices.extend([1.0, fraction * 2 - 1]) # x2, y2
grid_vertices = np.array(grid_vertices, dtype='f4')
# Create a Vertex Buffer Object (VBO) and a Vertex Array Object (VAO)
vbo = ctx.buffer(grid_vertices)
vao = ctx.simple_vertex_array(prog, vbo, 'in_vert')
# Main render loop
while not glfw.window_should_close(window):
glfw.poll_events()
# Clear the window with a white background
ctx.clear(1.0, 1.0, 1.0, 1.0)
# Render the grid
vao.render(moderngl.LINES)
# Swap buffers
glfw.swap_buffers(window)
# Terminate GLFW
glfw.terminate()
Key Steps:
Shaders: We define a simple vertex and fragment shader. The fragment shader sets the color for our grid lines (gray in this case).
Vertices: We generate vertices for vertical and horizontal grid lines. The grid_vertices array stores coordinates for these lines. This example sets up 10 lines across both axes, but you can adjust the num_lines variable for a different density.
VBO & VAO: We use a Vertex Buffer Object to hold vertex data and a simple Vertex Array Object to manage data between the VBO and our shaders.
Rendering Loop: During each frame, we clear the window and draw the grid lines using the established shaders and VAO setup.
This example renders a static grid of lines across the window, so you may want to adjust the number of lines or other parameters to fit your needs.