Skip to content

Instantly share code, notes, and snippets.

@postspectacular
Last active August 29, 2015 14:17
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save postspectacular/894fc58d75005069a546 to your computer and use it in GitHub Desktop.
Save postspectacular/894fc58d75005069a546 to your computer and use it in GitHub Desktop.
geom-webgl workaround for individual colored faces: Until face/vertex attributes are implemented in https://github.com/thi-ng/geom, colored meshes for WebGL apps can be achieved by building the attribute buffers (semi)manually...
(ns coloredmesh
(:require
[thi.ng.geom.core :as g]
[thi.ng.geom.core.vector :as v]
[thi.ng.geom.core.matrix :as mat :refer [M44]]
[thi.ng.geom.aabb :as a]
[thi.ng.geom.core.utils :as gu]
[thi.ng.geom.webgl.core :as gl]
[thi.ng.geom.webgl.arrays :as arrays]
[thi.ng.geom.webgl.animator :as anim]
[thi.ng.geom.webgl.buffers :as buf]
[thi.ng.geom.webgl.shaders :as shader]
[thi.ng.geom.webgl.shaders.basic :as basic]))
(defn colored-verts
"Flattens given seq of faces into seq of vertices and associates color with each.
Returns vector of [vertices colors]"
[faces col]
(let [verts (apply concat faces)]
[verts (repeat (count verts) col)]))
(defn flat-map
[f coll] (flatten (map f coll)))
(defn ^:export start!
[]
(let [gl (gl/gl-context "main") ;; ID of canvas
view-rect (gl/get-viewport-rect gl)
;; create centered box and tessellate each side
;; results in a seq of pairs of triangles
sides (->> (a/aabb 1) (g/center) (g/faces) (map gu/tessellate-3))
;; associate colors with vertices, one color per side (here face pair)
col-verts (map colored-verts sides [[1 0 0 1] [0 1 0 1] [0 0 1 1] [1 1 0 1] [1 0 1 1] [0 1 1 1]])
verts (flat-map first col-verts)
cols (flat-map second col-verts)
;; build model spec w/ attribute buffers and associated shader
;; usually one would use one of the geom lib's mesh types & converters,
;; but they currently don't support face/vertex attribs (yet)
model (-> {:attribs {:position {:data (arrays/float32 verts) :size 3}
:color {:data (arrays/float32 cols) :size 4}}
:uniforms {:proj (gl/perspective 45 view-rect 0.1 100.0)
:view (mat/look-at (v/vec3 0 0 2) (v/vec3) v/V3Y)}
:mode gl/triangles
:num-vertices (/ (count verts) 3)
:shader (->> (basic/make-color-shader-spec {:use-attrib true :3d true})
(sh/make-shader-from-spec gl))}
(buf/make-attribute-buffers-in-spec gl gl/static-draw))]
(anim/animate
(fn [[t frame]]
(gl/set-viewport gl view-rect)
(gl/clear-color-buffer gl 1 1 1 1)
(gl/enable gl gl/depth-test)
(buf/draw-arrays
gl (assoc-in model [:uniforms :model] (-> M44 (g/rotate-x t) (g/rotate-y (* t 2)))))
true))))
(start!)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment