=begin gtkglarea2.rb draw a triangle using shaders on a grey background this script need the opengl-bindings gem from : https://github.com/vaiorabbit/ruby-opengl gem install opengl-bindings sources: http://antongerdelan.net/opengl/hellotriangle.html opengl-bindings/sample/RedBook/varray opengl-bindings/sample/GLES/gles.rb http://www.opengl-tutorial.org/beginners-tutorials/tutorial-2-the-first-triangle/ https://developer.gnome.org/gtk3/stable/GtkGLArea.html https://www.bassi.io/articles/2015/02/17/using-opengl-with-gtk/ http://stackoverflow.com/questions/30337845/gldrawarrays-not-working-using-gtkglarea-in-gtk3 =end require "gtk3" require "opengl" unless Gtk::Version.or_later?(3, 16, 0) puts "This sample requires GTK+ 3.16.0 or later: #{Gtk::Version::STRING}" exit end OpenGL.load_lib include OpenGL window = Gtk::Window.new("OpenGL widget shaders test") window.set_size_request(400, 400) glarea = Gtk::GLArea.new window.add(glarea) vertex_shader = <= 3 && version[1] >= 2 puts "Gtk::GLArea widget require an OpenGL version >= 3.2, your version is #{version[0]}.#{version[1]}" exit 1 end puts "realize" # Define a triangle in a vertex buffer ( Vertex Buffer Object) points = [ 0.0, 0.5, 0.0, # x1, y1, z1 0.5, -0.5, 0.0, # x2, y2, z2 -0.5, -0.5, 0.0 # x3, y3, z3 ] vao_buf = " " glGenVertexArrays(1, vao_buf) gl_vao = vao_buf.unpack("L")[0] glBindVertexArray(gl_vao) # We copy those points onto the graphics card in a unit called vertex buffer object (vbo). # Create an empty buffer vbo_buf = " " glGenBuffers(1, vbo_buf) g_vbo = vbo_buf.unpack("L")[0] # Set the empty buffer as the current OpenGL's state machine by "binding" glBindBuffer(GL_ARRAY_BUFFER, g_vbo) # Copy the points in the currently bound buffer glBufferData(GL_ARRAY_BUFFER, 3 * 4 * Fiddle::SIZEOF_FLOAT, points.pack("F*"), GL_STATIC_DRAW ) # First attribute buffer : vertices glEnableVertexAttribArray(0) glVertexAttribPointer(0, # No particular reason for 0 3, # size GL_FLOAT, # type GL_FALSE, # normalized? 0, # stride 0 # array buffer offset ) glBindVertexArray(0) # Load the shaders: _ok, shader_program = setup_shaders(vertex_shader, fragment_shader) end glarea.signal_connect("render") do |_widget, _context| puts "render" glClearColor(0.3, 0.3, 0.3, 1) glClear(GL_COLOR_BUFFER_BIT) # Set the created shader program as current glUseProgram(shader_program) glBindVertexArray(gl_vao) glDrawArrays(GL_TRIANGLES, 0, 3) true end glarea.signal_connect("unrealize") do |widget| puts "unrealize" widget.make_current glDeleteVertexArrays(1, [gl_vao].pack("L")) glDeleteProgram(shader_program) end window.signal_connect("destroy") { Gtk.main_quit } window.show_all Gtk.main