Example #1
0
// Rendering this LineRender.
func (lr *LineRender) Render() {
	// Binding the appropriate information.
	gl.BindVertexArray(lr.vao)
	gl.BindBuffer(gl.ARRAY_BUFFER, lr.vbo)
	gl.BindBuffer(gl.ELEMENT_ARRAY_BUFFER, lr.ebo)
	gl.UseProgram(lr.shaderProgram)

	// Loading up vertex attributes.
	vertAttrib := uint32(gl.GetAttribLocation(lr.shaderProgram, gl.Str("vert\x00")))
	gl.EnableVertexAttribArray(vertAttrib)
	gl.VertexAttribPointer(vertAttrib, 2, gl.FLOAT, false, 2*4, gl.PtrOffset(0))

	// Line thickness information.
	gl.Uniform1f(
		gl.GetUniformLocation(lr.shaderProgram, gl.Str("in_thickness\x00")),
		lr.weight)

	// Fragment shader color information.
	gl.Uniform4f(
		gl.GetUniformLocation(lr.shaderProgram, gl.Str("in_color\x00")),
		lr.color.Red,
		lr.color.Green,
		lr.color.Blue,
		lr.color.Alpha)

	gl.BindFragDataLocation(lr.shaderProgram, 0, gl.Str("out_color\x00"))

	// Performing the render.
	gl.DrawElements(gl.LINE_STRIP, lr.points, gl.UNSIGNED_INT, nil)
}
Example #2
0
func NewEffectsRenderer(w, h int) (r *EffectsRenderer, err error) {
	r = &EffectsRenderer{
		width:  w,
		height: h,
		Color:  mgl32.Vec3{0.0, 0.0, 0.0},
	}
	_, _, r.oldwidth, r.oldheight = twodee.GetInteger4(gl.VIEWPORT)
	if r.shader, err = twodee.BuildProgram(EFFECTS_VERTEX, EFFECTS_FRAGMENT); err != nil {
		return
	}
	r.positionLoc = uint32(gl.GetAttribLocation(r.shader, gl.Str("a_Position\x00")))
	r.textureLoc = uint32(gl.GetAttribLocation(r.shader, gl.Str("a_TextureCoordinates\x00")))
	r.textureUnitLoc = gl.GetUniformLocation(r.shader, gl.Str("u_TextureUnit\x00"))
	r.colorLoc = gl.GetUniformLocation(r.shader, gl.Str("v_Color\x00"))
	gl.BindFragDataLocation(r.shader, 0, gl.Str("v_FragData\x00"))
	var size float32 = 1.0
	var rect = []float32{
		-size, -size, 0.0, 0, 0,
		-size, size, 0.0, 0, 1,
		size, -size, 0.0, 1, 0,
		size, size, 0.0, 1, 1,
	}
	if r.coords, err = twodee.CreateVBO(len(rect)*4, rect, gl.STATIC_DRAW); err != nil {
		return
	}

	if r.framebuffer, r.texture, err = r.initFramebuffer(w, h); err != nil {
		return
	}
	return
}
Example #3
0
func NewLinesRenderer(camera *Camera) (lr *LinesRenderer, err error) {
	var (
		program uint32
		vbos    = make([]uint32, 2)
		point   TexturedPoint
	)
	if program, err = BuildProgram(LINES_VERTEX, LINES_FRAGMENT); err != nil {
		return
	}
	gl.GenBuffers(2, &vbos[0])
	lr = &LinesRenderer{
		Renderer:      NewRenderer(camera),
		program:       program,
		buffer:        vbos[0],
		indexBuffer:   vbos[1],
		bufferBytes:   0,
		positionLoc:   uint32(gl.GetAttribLocation(program, gl.Str("v_Position\x00"))),
		normalLoc:     uint32(gl.GetAttribLocation(program, gl.Str("v_Normal\x00"))),
		miterLoc:      uint32(gl.GetAttribLocation(program, gl.Str("f_Miter\x00"))),
		modelviewLoc:  gl.GetUniformLocation(program, gl.Str("m_ModelView\x00")),
		projectionLoc: gl.GetUniformLocation(program, gl.Str("m_Projection\x00")),
		thicknessLoc:  gl.GetUniformLocation(program, gl.Str("f_Thickness\x00")),
		colorLoc:      gl.GetUniformLocation(program, gl.Str("v_Color\x00")),
		innerLoc:      gl.GetUniformLocation(program, gl.Str("f_Inner\x00")),
		offPosition:   gl.PtrOffset(int(unsafe.Offsetof(point.X))),
		offNormal:     gl.PtrOffset(int(unsafe.Offsetof(point.TextureX))),
		offMiter:      gl.PtrOffset(int(unsafe.Offsetof(point.Z))),
		stride:        int32(unsafe.Sizeof(point)),
	}
	if e := gl.GetError(); e != 0 {
		err = fmt.Errorf("ERROR: OpenGL error %X", e)
	}
	return
}
Example #4
0
func (c Context) DrawRectangle(x, y, w, h float32, color Color) {

	gl.UseProgram(c.program)
	model := mgl32.Translate3D(x, y, 0).Mul4(mgl32.Scale3D(w, h, 0))
	modelUniform := gl.GetUniformLocation(c.program, gl.Str("model\x00"))
	gl.UniformMatrix4fv(modelUniform, 1, false, &model[0])

	colorArray := []float32{color.B, color.G, color.R}

	colorUniform := gl.GetUniformLocation(c.program, gl.Str("color\x00"))
	gl.Uniform4fv(colorUniform, 1, &colorArray[0])

	gl.DrawArrays(gl.TRIANGLES, 0, 6)
}
Example #5
0
func GetUniformLocation(shaderName, uniformName string) (int32, error) {
	prog, ok := shader_progs[shaderName]
	if !ok {
		return -1, fmt.Errorf("No shader named '%s'", shaderName)
	}
	return gl.GetUniformLocation(prog, gl.Str(fmt.Sprintf("%s\x00", uniformName))), nil
}
Example #6
0
func getUniformLocation(program uint32, name string) (int32, error) {
	u := gl.GetUniformLocation(program, gl.Str(name+"\x00"))
	if u == -1 {
		return 0, fmt.Errorf("couldn't get uniform location: %q", name)
	}
	return u, nil
}
Example #7
0
func (shader *MVCShader) initMVC() error {
	uniform := gl.GetUniformLocation(shader.Handle, gl.Str("mvc\x00"))
	if uniform == -1 {
		return errors.New("GetUniformLocation Failed")
	}
	shader.mVCHandle = uniform
	return nil
}
Example #8
0
func SetUniform4F(shader, variable string, vs []float32) error {
	prog, ok := shader_progs[shader]
	if !ok {
		return fmt.Errorf("Tried to set a uniform in an unknown shader '%s'", shader)
	}
	bvariable := []byte(fmt.Sprintf("%s\x00", variable))
	loc := gl.GetUniformLocation(prog, (*uint8)(unsafe.Pointer(&bvariable[0])))
	gl.Uniform4f(loc, vs[0], vs[1], vs[2], vs[3])
	return nil
}
Example #9
0
func NewBatchRenderer(camera *Camera) (tr *BatchRenderer, err error) {
	var (
		program uint32
	)
	if program, err = BuildProgram(BATCH_VERTEX, BATCH_FRAGMENT); err != nil {
		return
	}
	tr = &BatchRenderer{
		Renderer:       NewRenderer(camera),
		Program:        program,
		PositionLoc:    uint32(gl.GetAttribLocation(program, gl.Str("a_Position\x00"))),
		TextureLoc:     uint32(gl.GetAttribLocation(program, gl.Str("a_TextureCoordinates\x00"))),
		TextureUnitLoc: gl.GetUniformLocation(program, gl.Str("u_TextureUnit\x00")),
		ModelViewLoc:   gl.GetUniformLocation(program, gl.Str("m_ModelViewMatrix\x00")),
		ProjectionLoc:  gl.GetUniformLocation(program, gl.Str("m_ProjectionMatrix\x00")),
		TexOffsetLoc:   gl.GetUniformLocation(program, gl.Str("u_TextureOffset\x00")),
	}
	if e := gl.GetError(); e != 0 {
		err = fmt.Errorf("ERROR: OpenGL error %X", e)
	}
	return
}
Example #10
0
func NewSpriteRenderer(camera *Camera) (tr *SpriteRenderer, err error) {
	var (
		program     uint32
		vbos        = make([]uint32, 1)
		sprite      SpriteConfig
		frameOffset = int(unsafe.Offsetof(sprite.Frame))
		viewOffset  = int(unsafe.Offsetof(sprite.View))
	)
	if program, err = BuildProgram(SPRITE_VERTEX, SPRITE_FRAGMENT); err != nil {
		return
	}
	gl.GenBuffers(1, &vbos[0])
	tr = &SpriteRenderer{
		Renderer:          NewRenderer(camera),
		program:           program,
		instanceVBO:       vbos[0],
		instanceBytes:     0,
		translationLoc:    uint32(gl.GetAttribLocation(program, gl.Str("v_Translation\x00"))),
		rotationLoc:       uint32(gl.GetAttribLocation(program, gl.Str("v_Rotation\x00"))),
		scaleLoc:          uint32(gl.GetAttribLocation(program, gl.Str("v_Scale\x00"))),
		pointAdjLoc:       uint32(gl.GetAttribLocation(program, gl.Str("m_PointAdjustment\x00"))),
		textureAdjLoc:     uint32(gl.GetAttribLocation(program, gl.Str("m_TextureAdjustment\x00"))),
		colorLoc:          uint32(gl.GetAttribLocation(program, gl.Str("v_Color\x00"))),
		textureUnitLoc:    gl.GetUniformLocation(program, gl.Str("TextureUnit\x00")),
		projectionLoc:     gl.GetUniformLocation(program, gl.Str("m_ProjectionMatrix\x00")),
		offAttrX:          gl.PtrOffset(viewOffset + int(unsafe.Offsetof(sprite.View.X))),
		offAttrRotationX:  gl.PtrOffset(viewOffset + int(unsafe.Offsetof(sprite.View.RotationX))),
		offAttrColor:      gl.PtrOffset(int(unsafe.Offsetof(sprite.Color))),
		offAttrScaleX:     gl.PtrOffset(viewOffset + int(unsafe.Offsetof(sprite.View.ScaleX))),
		offAttrPointAdj:   frameOffset + int(unsafe.Offsetof(sprite.Frame.PointAdjustment)),
		offAttrTextureAdj: frameOffset + int(unsafe.Offsetof(sprite.Frame.TextureAdjustment)),
	}
	if e := gl.GetError(); e != 0 {
		err = fmt.Errorf("ERROR: OpenGL error %X", e)
	}
	return
}
Example #11
0
func NewFramerateRenderer() (r *Framerate, err error) {
	r = &Framerate{
		shader: core.NewProgram(),
		data:   newFramerateData(120),
	}
	if err = r.shader.Load(FRAMERATE_VERTEX, FRAMERATE_FRAGMENT); err != nil {
		return
	}
	r.shader.Bind()
	gl.GenBuffers(1, &r.vbo)
	gl.BindBuffer(gl.ARRAY_BUFFER, r.vbo)
	var (
		point       framerateDataPoint
		locPosition = uint32(gl.GetAttribLocation(r.shader.ID(), gl.Str("v_Position\x00")))
		offPosition = gl.PtrOffset(int(unsafe.Offsetof(point.pos)))
	)
	r.stride = int32(unsafe.Sizeof(point))
	r.locColor = gl.GetUniformLocation(r.shader.ID(), gl.Str("v_Color\x00"))
	r.locModelView = gl.GetUniformLocation(r.shader.ID(), gl.Str("m_ModelView\x00"))
	r.locProjection = gl.GetUniformLocation(r.shader.ID(), gl.Str("m_Projection\x00"))
	gl.EnableVertexAttribArray(locPosition)
	gl.VertexAttribPointer(locPosition, 2, gl.FLOAT, false, r.stride, offPosition)
	return
}
Example #12
0
func NewTextRenderer(camera *Camera) (tr *TextRenderer, err error) {
	var (
		rect    []float32
		program uint32
		vbo     uint32
	)
	rect = []float32{
		0, 0, 0.0, 0.0, 0.0,
		0, 1, 0.0, 0.0, 1.0,
		1, 0, 0.0, 1.0, 0.0,
		1, 1, 0.0, 1.0, 1.0,
	}
	if program, err = BuildProgram(TEXT_VERTEX, TEXT_FRAGMENT); err != nil {
		return
	}
	if vbo, err = CreateVBO(len(rect)*4, rect, gl.STATIC_DRAW); err != nil {
		return
	}
	tr = &TextRenderer{
		Renderer:       NewRenderer(camera),
		VBO:            vbo,
		Program:        program,
		PositionLoc:    uint32(gl.GetAttribLocation(program, gl.Str("a_Position\x00"))),
		TextureLoc:     uint32(gl.GetAttribLocation(program, gl.Str("a_TextureCoordinates\x00"))),
		TextureUnitLoc: gl.GetUniformLocation(program, gl.Str("u_TextureUnit\x00")),
		TransLoc:       gl.GetUniformLocation(program, gl.Str("v_Trans\x00")),
		ScaleLoc:       gl.GetUniformLocation(program, gl.Str("v_Scale\x00")),
		ProjectionLoc:  gl.GetUniformLocation(program, gl.Str("m_ProjectionMatrix\x00")),
		Width:          camera.ScreenBounds.Max.X() - camera.ScreenBounds.Min.X(),
		Height:         camera.ScreenBounds.Max.Y() - camera.ScreenBounds.Min.Y(),
	}
	if e := gl.GetError(); e != 0 {
		err = fmt.Errorf("ERROR: OpenGL error %X", e)
	}
	return
}
Example #13
0
func getUniformLocation(prog uint32, name string) int32 {
	// attempt to get it from the cache first
	ul, found := uniCache[name]
	if found {
		return ul
	}

	// pull the location from the shader and cache it
	uniGLName := name + "\x00"
	ul = gl.GetUniformLocation(prog, gl.Str(uniGLName))

	// cache even if it returns -1 so that it doesn't repeatedly check
	uniCache[name] = ul
	return ul
}
Example #14
0
func CreateBuffers() {

	var err error
	program, err = MakeProgram(VertexShader(), FragmentShader())
	// defer program.Delete()

	if err != nil {
		fmt.Println("Error loading shaders: " + err.Error())
		panic("error loading shaders")
	}

	gl.BindFragDataLocation(program, 0, gl.Str("color\x00"))

	MVPid = gl.GetUniformLocation(program, gl.Str("MVP\x00"))
	lightpositionID = gl.GetUniformLocation(program, gl.Str("light.position\x00"))
	lightintensitiesID = gl.GetUniformLocation(program, gl.Str("light.intensities\x00"))
	lightattenuationID = gl.GetUniformLocation(program, gl.Str("light.attenuation\x00"))
	lightambientCoeficientID = gl.GetUniformLocation(program, gl.Str("light.ambientCoeficient\x00"))

	cameraPositionID = gl.GetUniformLocation(program, gl.Str("cameraPosition\x00"))

	// View := mathgl.LookAt(0.0, 0.0, 5.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0)

	// viewM = View

	gl.DepthFunc(gl.LEQUAL)
	gl.Enable(gl.BLEND)
	gl.BlendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA)

	// var vao uint32
	gl.GenVertexArrays(1, &vao)
	gl.BindVertexArray(vao)

	// var vbo uint32
	gl.GenBuffers(1, &vbo)

	// gl.GenBuffers(1, &elementvbo)
	// fmt.Println(program)
	gl.UseProgram(program)

	for idx, img := range aggregateImages {
		bindAggregateImage(img, idx)

	}

}
Example #15
0
func bindAggregateImage(img image.Image, idx int) uint32 {

	newIdx := idx

	if rgba, ok := img.(*image.RGBA); ok {

		gl.GenTextures(1, &textures[newIdx])

		gl.ActiveTexture(gl.TEXTURE0 + uint32(newIdx))
		gl.BindTexture(gl.TEXTURE_2D, textures[newIdx])
		gl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_LINEAR)
		gl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR)
		gl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE)
		gl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE)
		gl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_R, gl.CLAMP_TO_EDGE)

		gl.TexImage2D(gl.TEXTURE_2D, 0, gl.RGBA, int32(rgba.Rect.Size().X), int32(rgba.Rect.Size().Y), 0, gl.RGBA, gl.UNSIGNED_BYTE, gl.Ptr(rgba.Pix))
		gl.GenerateMipmap(gl.TEXTURE_2D)

		idxS := strconv.Itoa(newIdx)
		fmt.Println("idx: ", int32(newIdx), "myTextureSampler["+idxS+"]\x00")
		gl.Uniform1i(gl.GetUniformLocation(program, gl.Str("myTextureSampler["+idxS+"]\x00")), int32(newIdx))
		if ok := gl.GetError(); ok != gl.NO_ERROR {

			fmt.Println("1- Cannot load Image in location: ./: ", ok)
			os.Exit(-1)
		}

		return textures[newIdx]
	} else {
		fmt.Println("Image not RGBA at location: ./")
		os.Exit(-1)
	}

	return 0
}
Example #16
0
func NewGlowRenderer(w, h int, blur int, strength float32, scale float32) (r *GlowRenderer, err error) {
	r = &GlowRenderer{
		width:    w,
		height:   h,
		blur:     blur,
		strength: strength,
		scale:    scale,
	}
	_, _, r.oldwidth, r.oldheight = GetInteger4(gl.VIEWPORT)
	if r.shader, err = BuildProgram(GLOW_VERTEX, GLOW_FRAGMENT); err != nil {
		return
	}
	r.orientationLoc = gl.GetUniformLocation(r.shader, gl.Str("Orientation\x00"))
	r.blurAmountLoc = gl.GetUniformLocation(r.shader, gl.Str("BlurAmount\x00"))
	r.blurScaleLoc = gl.GetUniformLocation(r.shader, gl.Str("BlurScale\x00"))
	r.blurStrengthLoc = gl.GetUniformLocation(r.shader, gl.Str("BlurStrength\x00"))
	r.bufferDimensionsLoc = gl.GetUniformLocation(r.shader, gl.Str("BufferDimensions\x00"))
	r.positionLoc = uint32(gl.GetAttribLocation(r.shader, gl.Str("a_Position\x00")))
	r.textureLoc = uint32(gl.GetAttribLocation(r.shader, gl.Str("a_TextureCoordinates\x00")))
	r.textureUnitLoc = gl.GetUniformLocation(r.shader, gl.Str("u_TextureUnit\x00"))
	gl.BindFragDataLocation(r.shader, 0, gl.Str("v_FragData\x00"))
	var size float32 = 1.0
	var rect = []float32{
		-size, -size, 0.0, 0, 0,
		-size, size, 0.0, 0, 1,
		size, -size, 0.0, 1, 0,
		size, size, 0.0, 1, 1,
	}
	if r.coords, err = CreateVBO(len(rect)*4, rect, gl.STATIC_DRAW); err != nil {
		return
	}

	if r.GlowFb, r.GlowTex, err = r.initFramebuffer(w, h); err != nil {
		return
	}
	if r.BlurFb, r.BlurTex, err = r.initFramebuffer(w, h); err != nil {
		return
	}
	return
}
Example #17
0
func main() {
	// init glfw
	if err := glfw.Init(); err != nil {
		panic(err)
	}

	defer glfw.Terminate()

	glfw.WindowHint(glfw.Resizable, glfw.False)
	glfw.WindowHint(glfw.ContextVersionMajor, 4)
	glfw.WindowHint(glfw.ContextVersionMinor, 1)
	glfw.WindowHint(glfw.OpenGLProfile, glfw.OpenGLCoreProfile)
	glfw.WindowHint(glfw.OpenGLForwardCompatible, glfw.True)

	// make an application window
	window, err := glfw.CreateWindow(windowWidth, windowHeight, "Transform", nil, nil)
	if err != nil {
		panic(err)
	}
	window.MakeContextCurrent()

	// init gl
	if err := gl.Init(); err != nil {
		panic(err)
	}
	fmt.Println("OpenGL version", gl.GoStr(gl.GetString(gl.VERSION)))

	// create vertex & fragment shader
	program, err := newProgram(vertexShader, fragmentShader)
	if err != nil {
		panic(err)
	}
	gl.UseProgram(program)

	projection := mgl32.Perspective(mgl32.DegToRad(45.0), float32(windowWidth)/windowHeight, 0.1, 10.0)
	projectionUniform := gl.GetUniformLocation(program, gl.Str("projection\x00"))
	gl.UniformMatrix4fv(projectionUniform, 1, false, &projection[0])

	camera := mgl32.LookAtV(
		mgl32.Vec3{3, 3, 3},
		mgl32.Vec3{0, 0, 0},
		mgl32.Vec3{0, 1, 0},
	)
	cameraUniform := gl.GetUniformLocation(program, gl.Str("camera\x00"))
	gl.UniformMatrix4fv(cameraUniform, 1, false, &camera[0])

	model := mgl32.Ident4()
	modelUniform := gl.GetUniformLocation(program, gl.Str("model\x00"))
	gl.UniformMatrix4fv(modelUniform, 1, false, &model[0])

	gl.BindFragDataLocation(program, 0, gl.Str("vert\x00"))

	points := []float32{
		-0.9, -0.9, -0.9,
		0.9, -0.9, -0.9,
		0.9, -0.9, 0.9,
		-0.9, -0.9, 0.9,
		-0.9, 0.9, -0.9,
		0.9, 0.9, -0.9,
		0.9, 0.9, 0.9,
		-0.9, 0.9, 0.9,
	}

	vertices := []uint32{
		0, 1,
		1, 2,
		2, 3,
		3, 0,
		0, 4,
		1, 5,
		2, 6,
		3, 7,
		4, 5,
		5, 6,
		6, 7,
		7, 4,
	}

	// configure the vertex data
	var vao uint32
	gl.GenVertexArrays(1, &vao)
	gl.BindVertexArray(vao)

	defer gl.BindVertexArray(0)

	var vbo uint32
	gl.GenBuffers(1, &vbo)
	gl.BindBuffer(gl.ARRAY_BUFFER, vbo)
	gl.BufferData(gl.ARRAY_BUFFER, len(points)*4, gl.Ptr(points), gl.STATIC_DRAW)

	var ibo uint32
	gl.GenBuffers(1, &ibo)
	gl.BindBuffer(gl.ELEMENT_ARRAY_BUFFER, ibo)
	gl.BufferData(gl.ELEMENT_ARRAY_BUFFER, len(vertices)*4, gl.Ptr(vertices), gl.STATIC_DRAW)

	vertAttrib := uint32(gl.GetAttribLocation(program, gl.Str("vert\x00")))
	gl.EnableVertexAttribArray(vertAttrib)
	gl.VertexAttribPointer(vertAttrib, 3, gl.FLOAT, false, 3*4, gl.PtrOffset(0))

	// global settings
	gl.Enable(gl.DEPTH_TEST)
	gl.DepthFunc(gl.LESS)
	gl.ClearColor(0.0, 0.0, 0.0, 1.0)

	angleX := 0.0
	angleY := 0.0
	angleZ := 0.0
	previousTime := glfw.GetTime()

	for !window.ShouldClose() {
		gl.Clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT)

		time := glfw.GetTime()
		elapsed := time - previousTime
		previousTime = time

		angleX += math.Sin((elapsed / period) * math.Pi * 2.0)
		angleY += math.Sin((elapsed / period) / 6.0 * math.Pi * 2.0)
		angleZ += math.Sin((elapsed / period) / 3.0 * math.Pi * 2.0)
		model = mgl32.HomogRotate3DY(float32(angleY)).Mul4(mgl32.HomogRotate3DX(float32(angleX))).Mul4(mgl32.HomogRotate3DZ(float32(angleZ)))
		gl.UseProgram(program)
		gl.UniformMatrix4fv(modelUniform, 1, false, &model[0])

		gl.BindVertexArray(vao)

		gl.DrawElements(gl.LINES, int32(len(vertices)), gl.UNSIGNED_INT, gl.PtrOffset(0))

		window.SwapBuffers()
		glfw.PollEvents()
	}
}
Example #18
0
func CreateContext(width, height int) Context {
	vertexShader := `
#version 330
uniform mat4 projection;
uniform mat4 camera;
uniform mat4 model;
in vec3 vert;
void main() {
    gl_Position = projection * camera * model * vec4(vert, 1);
}
` + "\x00"

	fragmentShader := `
#version 330
uniform vec4 color;
out vec4 outputColor;
void main() {
    outputColor = color;
}
` + "\x00"

	vertices := []float32{
		0.0, 0.0, 0.0,
		1.0, 0.0, 0.0,
		1.0, 1.0, 0.0,
		1.0, 1.0, 0.0,
		0.0, 1.0, 0.0,
		0.0, 0.0, 0.0,
	}

	if err := glfw.Init(); err != nil {
		log.Fatalln("failed to initialize glfw:", err)
	}
	// defer glfw.Terminate()

	glfw.WindowHint(glfw.Resizable, glfw.False)
	glfw.WindowHint(glfw.ContextVersionMajor, 3)
	glfw.WindowHint(glfw.ContextVersionMinor, 3)
	glfw.WindowHint(glfw.OpenGLProfile, glfw.OpenGLCoreProfile)
	glfw.WindowHint(glfw.OpenGLForwardCompatible, glfw.True)
	window, err := glfw.CreateWindow(width, height, "OpenGL", nil, nil)
	if err != nil {
		panic(err)
	}
	window.MakeContextCurrent()

	if err := gl.Init(); err != nil {
		panic(err)
	}

	program, err := newProgram(vertexShader, fragmentShader)
	if err != nil {
		panic(err)
	}

	gl.UseProgram(program)

	projection := mgl32.Ortho2D(0, 800, 0, 600)
	projectionUniform := gl.GetUniformLocation(program, gl.Str("projection\x00"))
	gl.UniformMatrix4fv(projectionUniform, 1, false, &projection[0])

	camera := mgl32.LookAtV(mgl32.Vec3{0, 0, 0.5}, mgl32.Vec3{0, 0, 0}, mgl32.Vec3{0, 1, 0})
	cameraUniform := gl.GetUniformLocation(program, gl.Str("camera\x00"))
	gl.UniformMatrix4fv(cameraUniform, 1, false, &camera[0])

	model := mgl32.Ident4()
	modelUniform := gl.GetUniformLocation(program, gl.Str("model\x00"))
	gl.UniformMatrix4fv(modelUniform, 1, false, &model[0])

	var vao uint32
	gl.GenVertexArrays(1, &vao)
	gl.BindVertexArray(vao)

	var vbo uint32
	gl.GenBuffers(1, &vbo)
	gl.BindBuffer(gl.ARRAY_BUFFER, vbo)
	gl.BufferData(gl.ARRAY_BUFFER, len(vertices)*4, gl.Ptr(vertices), gl.STATIC_DRAW)

	vertAttrib := uint32(gl.GetAttribLocation(program, gl.Str("vert\x00")))
	gl.EnableVertexAttribArray(vertAttrib)
	gl.VertexAttribPointer(vertAttrib, 3, gl.FLOAT, false, 3*4, gl.PtrOffset(0))

	gl.Enable(gl.DEPTH_TEST)
	gl.DepthFunc(gl.LESS)

	return Context{Window: window, program: program}
}
Example #19
0
func main() {
	vertices, normals := obj.Parse(os.Args[1])

	// initialize GLFW
	if err := glfw.Init(); err != nil {
		panic(err)
	}
	defer glfw.Terminate()

	// set opengl core profile 3.3
	glfw.WindowHint(glfw.ContextVersionMajor, 3)
	glfw.WindowHint(glfw.ContextVersionMinor, 3)
	glfw.WindowHint(glfw.OpenGLProfile, glfw.OpenGLCoreProfile)
	glfw.WindowHint(glfw.OpenGLForwardCompatible, glfw.True)

	window, err := glfw.CreateWindow(640, 480, "GOpenGL", nil, nil)
	if err != nil {
		panic(err)
	}
	window.MakeContextCurrent()

	// initialise OpenGL library
	if err := gl.Init(); err != nil {
		panic(err)
	}

	// link program from shaders
	program, err := newProgram("vertex.glsl", "fragment.glsl")
	if err != nil {
		panic(err)
	}
	gl.UseProgram(program)

	// vertex attribute object holds links between attributes and vbo
	var vao uint32
	gl.GenVertexArrays(1, &vao)
	gl.BindVertexArray(vao)

	// vertex buffer with per-vertex data
	var vbo [2]uint32
	gl.GenBuffers(2, &vbo[0])

	// position data
	gl.BindBuffer(gl.ARRAY_BUFFER, vbo[0])
	gl.BufferData(gl.ARRAY_BUFFER, len(vertices)*4, gl.Ptr(vertices), gl.STATIC_DRAW)

	// set up position attribute with layout of vertices
	posAttrib := uint32(gl.GetAttribLocation(program, gl.Str("position\x00")))
	gl.VertexAttribPointer(posAttrib, 3, gl.FLOAT, false, 3*4, gl.PtrOffset(0))
	gl.EnableVertexAttribArray(posAttrib)

	// normal data
	gl.BindBuffer(gl.ARRAY_BUFFER, vbo[1])
	gl.BufferData(gl.ARRAY_BUFFER, len(normals)*4, gl.Ptr(normals), gl.STATIC_DRAW)

	normAttrib := uint32(gl.GetAttribLocation(program, gl.Str("normal\x00")))
	gl.VertexAttribPointer(normAttrib, 3, gl.FLOAT, false, 3*4, gl.PtrOffset(0))
	gl.EnableVertexAttribArray(normAttrib)

	uniModel := gl.GetUniformLocation(program, gl.Str("model\x00"))
	uniView := gl.GetUniformLocation(program, gl.Str("view\x00"))
	uniProj := gl.GetUniformLocation(program, gl.Str("proj\x00"))

	matView := mgl32.LookAt(2.0, 2.0, 2.0,
		0.0, 0.0, 0.0,
		0.0, 0.0, 1.0)
	gl.UniformMatrix4fv(uniView, 1, false, &matView[0])

	matProj := mgl32.Perspective(mgl32.DegToRad(45.0), 640.0/480.0, 1.0, 10.0)
	gl.UniformMatrix4fv(uniProj, 1, false, &matProj[0])

	uniLightDir := gl.GetUniformLocation(program, gl.Str("lightDir\x00"))
	uniLightCol := gl.GetUniformLocation(program, gl.Str("lightCol\x00"))

	gl.Uniform3f(uniLightDir, -0.5, 0.0, -1.0)
	gl.Uniform3f(uniLightCol, 0.0, 0.5, 0.5)

	startTime := glfw.GetTime()
	gl.Enable(gl.DEPTH_TEST)
	gl.ClearColor(1.0, 1.0, 1.0, 1.0)

	for !window.ShouldClose() {
		// clear buffer
		gl.Clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT)

		matRot := mgl32.HomogRotate3DZ(float32(glfw.GetTime() - startTime))
		gl.UniformMatrix4fv(uniModel, 1, false, &matRot[0])

		gl.DrawArrays(gl.TRIANGLES, 0, int32(len(vertices)))

		window.SwapBuffers()
		glfw.PollEvents()
	}
}
Example #20
0
func loadFont(img *image.RGBA, config *FontConfig) (f *Font, err error) {
	f = new(Font)
	f.config = config

	// Resize image to next power-of-two.
	img = Pow2Image(img).(*image.RGBA)
	ib := img.Bounds()

	f.textureWidth = float32(ib.Dx())
	f.textureHeight = float32(ib.Dy())

	for _, glyph := range config.Glyphs {
		if glyph.Width > f.maxGlyphWidth {
			f.maxGlyphWidth = glyph.Width
		}
		if glyph.Height > f.maxGlyphHeight {
			f.maxGlyphHeight = glyph.Height
		}
	}

	// save to disk for testing
	if f.IsDebug {
		file, err := os.Create("out.png")
		if err != nil {
			panic(err)
		}
		defer file.Close()

		b := bufio.NewWriter(file)
		err = png.Encode(b, img)
		if err != nil {
			panic(err)
		}
		err = b.Flush()
		if err != nil {
			panic(err)
		}
	}

	// generate texture
	gl.GenTextures(1, &f.textureID)
	gl.BindTexture(gl.TEXTURE_2D, f.textureID)
	gl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR)
	gl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR)
	gl.TexImage2D(
		gl.TEXTURE_2D,
		0,
		gl.RGBA,
		int32(ib.Dx()),
		int32(ib.Dy()),
		0,
		gl.RGBA,
		gl.UNSIGNED_BYTE,
		gl.Ptr(img.Pix),
	)
	gl.BindTexture(gl.TEXTURE_2D, 0)

	// create shader program and define attributes and uniforms
	f.program, err = NewProgram(fontVertexShaderSource, fontFragmentShaderSource)
	if err != nil {
		return f, err
	}

	// attributes
	f.centeredPosition = uint32(gl.GetAttribLocation(f.program, gl.Str("centered_position\x00")))
	f.uv = uint32(gl.GetAttribLocation(f.program, gl.Str("uv\x00")))

	// uniforms
	f.finalPositionUniform = gl.GetUniformLocation(f.program, gl.Str("final_position\x00"))
	f.orthographicMatrixUniform = gl.GetUniformLocation(f.program, gl.Str("orthographic_matrix\x00"))
	f.scaleMatrixUniform = gl.GetUniformLocation(f.program, gl.Str("scale_matrix\x00"))
	f.fragmentTextureUniform = gl.GetUniformLocation(f.program, gl.Str("fragment_texture\x00"))
	f.colorUniform = gl.GetUniformLocation(f.program, gl.Str("fragment_color_adjustment\x00"))
	return f, nil
}
Example #21
0
func (p *Program) Uniform(name string) *Uniform {
	var nameStr = gl.Str(fmt.Sprintf("%v\x00", name))
	return &Uniform{
		location: gl.GetUniformLocation(p.ID(), nameStr),
	}
}
Example #22
0
func loadBoundingBox(f *Font, X1 Point, X2 Point) (b *BoundingBox, err error) {
	b = new(BoundingBox)
	b.font = f

	// create shader program and define attributes and uniforms
	b.program, err = NewProgram(boxVertexShaderSource, boxFragmentShaderSource)
	if err != nil {
		return b, err
	}

	// ebo, vbo data
	b.vboIndexCount = 4 * 2 // 4 indexes per bounding box (containing 2 position)
	b.eboIndexCount = 6     // each rune requires 6 triangle indices for a quad
	b.vboData = make([]float32, b.vboIndexCount, b.vboIndexCount)
	b.eboData = make([]int32, b.eboIndexCount, b.eboIndexCount)
	b.makeBufferData(X1, X2)
	if f.IsDebug {
		fmt.Printf("bounding %v %v\n", X1, X2)
		fmt.Printf("bounding vbo data\n%v\n", b.vboData)
		fmt.Printf("bounding ebo data\n%v\n", b.eboData)
	}

	// attributes
	b.centeredPosition = uint32(gl.GetAttribLocation(b.program, gl.Str("centered_position\x00")))

	// uniforms
	b.finalPositionUniform = gl.GetUniformLocation(b.program, gl.Str("final_position\x00"))
	b.orthographicMatrixUniform = gl.GetUniformLocation(b.program, gl.Str("orthographic_matrix\x00"))

	// size of glfloat
	glfloatSize := int32(4)

	gl.GenVertexArrays(1, &b.vao)
	gl.GenBuffers(1, &b.vbo)
	gl.GenBuffers(1, &b.ebo)

	// vao
	gl.BindVertexArray(b.vao)

	// vbo
	// specify the buffer for which the VertexAttribPointer calls apply
	gl.BindBuffer(gl.ARRAY_BUFFER, b.vbo)

	gl.EnableVertexAttribArray(b.centeredPosition)
	gl.VertexAttribPointer(
		b.centeredPosition,
		2,
		gl.FLOAT,
		false,
		0,
		gl.PtrOffset(0),
	)
	gl.BufferData(gl.ARRAY_BUFFER, int(glfloatSize)*b.vboIndexCount, gl.Ptr(b.vboData), gl.DYNAMIC_DRAW)

	gl.BindBuffer(gl.ELEMENT_ARRAY_BUFFER, b.ebo)
	gl.BufferData(gl.ELEMENT_ARRAY_BUFFER, int(glfloatSize)*b.eboIndexCount, gl.Ptr(b.eboData), gl.DYNAMIC_DRAW)
	gl.BindVertexArray(0)

	// not necesssary, but i just want to better understand using vertex arrays
	gl.BindBuffer(gl.ARRAY_BUFFER, 0)
	gl.BindBuffer(gl.ELEMENT_ARRAY_BUFFER, 0)

	return b, nil
}