Skip to content

Instantly share code, notes, and snippets.

@somecho
Last active June 30, 2024 20:27
Show Gist options
  • Save somecho/7d19aa122b6875e2d742dd11b7fabfce to your computer and use it in GitHub Desktop.
Save somecho/7d19aa122b6875e2d742dd11b7fabfce to your computer and use it in GitHub Desktop.
OpenGL Hello Triangle in common lisp
(ql:quickload :cl-glfw3)
(ql:quickload :cl-opengl)
(defvar vs-source "#version 330
in vec3 aPos;
void main(){
gl_Position = vec4(aPos.x,aPos.y,aPos.z, 1.0);
}")
(defvar fs-source "
#version 330
out vec4 FragColor;
void main()
{
FragColor = vec4(1.0f, 0.5f, 0.2f, 1.0f);
}")
(defvar *VBO* nil)
(defvar *VAO* nil)
(defun create-default-shader ()
(let ((*vs* nil)
(*fs* nil)
(*shader* nil))
(setf *vs* (gl:create-shader :vertex-shader))
(gl:shader-source *vs* vs-source)
(gl:compile-shader *vs*)
(setf *fs* (gl:create-shader :fragment-shader))
(gl:shader-source *fs* fs-source)
(gl:compile-shader *fs*)
(setf *shader* (gl:create-program))
(gl:attach-shader *shader* *vs*)
(gl:attach-shader *shader* *fs*)
(gl:link-program *shader*)
(gl:delete-shader *vs*)
(gl:delete-shader *fs*)
*shader*))
(defun create-gl-array (data
&optional (type :float)
&aux (length (length data)))
(let ((arr (gl:alloc-gl-array :float length)))
(dotimes (i (length data))
(setf (gl:glaref arr i) (aref data i)))
arr))
(glfw:with-init-window (:width width :height height :title "GLFW")
;; Send the buffer data to the GPU
(setf *VBO* (gl:gen-buffer))
(gl:bind-buffer :array-buffer *VBO*)
(gl:buffer-data :array-buffer
:static-draw
(create-gl-array #(-0.5 0.5 0.0
0.0 0.0 0.0
0.5 0.5 0.0)))
;; Tell the GPU what the data represents by binding VAO
(setf *VAO* (gl:gen-vertex-array))
(gl:bind-vertex-array *VAO*)
(gl:vertex-attrib-pointer 0 3 :float :false 0 0)
(gl:enable-vertex-attrib-array 0)
;; main window draw loop
(let ((shader (create-default-shader)))
(loop until (glfw:window-should-close-p)
do (gl:clear :color-buffer)
do (gl:use-program *shader*)
do (gl:draw-arrays :triangles 0 3)
do (glfw:swap-buffers)
do (glfw:poll-events))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment