Exemplo n.º 1
0
func (p *Program) createVAO() error {
	gl.GenVertexArrays(1, &p.vao)
	if e := gl.GetError(); e != 0 {
		return fmt.Errorf("ERROR gl.GenVertexArray %X", e)
	}
	gl.BindVertexArray(p.vao)
	if e := gl.GetError(); e != 0 {
		return fmt.Errorf("ERROR array.Bind %X", e)
	}
	return nil
}
Exemplo n.º 2
0
func CreateVAO() (array uint32, err error) {
	gl.GenVertexArrays(1, &array)
	if e := gl.GetError(); e != 0 {
		err = fmt.Errorf("ERROR gl.GenVertexArray %X", e)
		return
	}
	gl.BindVertexArray(array)
	if e := gl.GetError(); e != 0 {
		err = fmt.Errorf("ERROR array.Bind %X", e)
		return
	}
	return
}
Exemplo n.º 3
0
func (tr *TextRenderer) Unbind() error {
	gl.BindBuffer(gl.ARRAY_BUFFER, 0)
	if e := gl.GetError(); e != 0 {
		return fmt.Errorf("ERROR: %X", e)
	}
	return nil
}
Exemplo n.º 4
0
// Runs the visualization with a set of DelayedNoteData. The DelayedNote data is
// used to push information to the synth as well as represent the data visually.
func RunVisualization(notes *synth.NoteArrangement, oNoteChannel chan synth.DelayedNoteData) error {
	window, assets, err := initialize()
	if err != nil {
		return err
	}
	defer destroy(window, assets)

	// The main update loop.
	ct, lt, dt := 0.0, 0.0, 0.0
	for !window.ShouldClose() {
		// Keeping the current time.
		lt = ct
		ct = glfw.GetTime()
		dt = ct - lt

		// Real render loop.
		gl.Clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT)

		if config.DebugMode {
			glErr := gl.GetError()
			if glErr != gl.NO_ERROR {
				fmt.Printf("OpenGL error: %d\n", glErr)
			}
		}

		window.SwapBuffers()
		glfw.PollEvents()

		if dt < 1/1000.0 {
			// Delay the thread to keep up w/ updating?
		}
	}

	return nil
}
Exemplo n.º 5
0
func (lr *LinesRenderer) Draw(line *LineGeometry, mv mgl32.Mat4, style *LineStyle) (err error) {
	var (
		dataBytes    int   = len(line.Vertices) * int(lr.stride)
		indexBytes   int   = len(line.Indices) * int(lr.stride)
		elementCount int32 = int32(len(line.Indices))
		r, g, b, a         = style.Color.RGBA()
	)
	gl.Uniform1f(lr.thicknessLoc, style.Thickness)
	gl.Uniform1f(lr.innerLoc, style.Inner)
	gl.Uniform4f(lr.colorLoc, float32(r)/255.0, float32(g)/255.0, float32(b)/255.0, float32(a)/255.0)
	gl.UniformMatrix4fv(lr.modelviewLoc, 1, false, &mv[0])
	if dataBytes > lr.bufferBytes {
		lr.bufferBytes = dataBytes
		gl.BufferData(gl.ARRAY_BUFFER, dataBytes, gl.Ptr(line.Vertices), gl.STREAM_DRAW)
		gl.BufferData(gl.ELEMENT_ARRAY_BUFFER, indexBytes, gl.Ptr(line.Indices), gl.STREAM_DRAW)
	} else {
		gl.BufferSubData(gl.ARRAY_BUFFER, 0, dataBytes, gl.Ptr(line.Vertices))
		gl.BufferSubData(gl.ELEMENT_ARRAY_BUFFER, 0, indexBytes, gl.Ptr(line.Indices))
	}
	gl.DrawElements(gl.TRIANGLES, elementCount, gl.UNSIGNED_INT, gl.PtrOffset(0))
	if e := gl.GetError(); e != 0 {
		err = fmt.Errorf("ERROR: OpenGL error %X", e)
	}
	return
}
Exemplo n.º 6
0
func NewRenderer(bufferSize int) (r *Renderer, err error) {
	var (
		instance       renderInstance
		instanceStride = unsafe.Sizeof(instance)
	)
	r = &Renderer{
		shader:     core.NewProgram(),
		bufferSize: bufferSize,
		buffer:     make([]renderInstance, bufferSize),
		stride:     instanceStride,
	}
	if err = r.shader.Load(VERTEX, FRAGMENT); err != nil {
		return
	}
	r.shader.Bind()

	r.vbo = core.NewArrayBuffer()

	r.shader.Attrib("f_InstanceFrame", instanceStride).Float(unsafe.Offsetof(instance.frame), 1)
	r.shader.Attrib("m_Model", instanceStride).Mat4(unsafe.Offsetof(instance.model), 1)
	r.shader.Attrib("v_Color", instanceStride).Vec4(unsafe.Offsetof(instance.color), 1)

	r.textureData = r.shader.UniformBlock("TextureData", 1)

	r.uView = r.shader.Uniform("m_View")
	r.uProj = r.shader.Uniform("m_Projection")

	if e := gl.GetError(); e != 0 {
		err = fmt.Errorf("ERROR: OpenGL error %X", e)
	}
	return
}
Exemplo n.º 7
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
}
Exemplo n.º 8
0
func (lr *LinesRenderer) Unbind() (err error) {
	gl.BindBuffer(gl.ARRAY_BUFFER, 0)
	gl.BindBuffer(gl.ELEMENT_ARRAY_BUFFER, 0)
	if e := gl.GetError(); e != 0 {
		err = fmt.Errorf("ERROR: OpenGL error %X", e)
	}
	return
}
Exemplo n.º 9
0
func (lr *LinesRenderer) Delete() (err error) {
	gl.BindBuffer(gl.ARRAY_BUFFER, 0)
	gl.BindBuffer(gl.ELEMENT_ARRAY_BUFFER, 0)
	gl.DeleteBuffers(1, &lr.buffer)
	gl.DeleteBuffers(1, &lr.indexBuffer)
	if e := gl.GetError(); e != 0 {
		err = fmt.Errorf("ERROR: OpenGL error %X", e)
	}
	return
}
Exemplo n.º 10
0
func (r *Renderer) draw(geometry *Geometry, count int) (err error) {
	if count <= 0 {
		return
	}
	r.vbo.Upload(r.buffer, count*int(r.stride))
	gl.DrawArraysInstanced(gl.TRIANGLES, 0, int32(len(geometry.Points)), int32(count))
	if e := gl.GetError(); e != 0 {
		err = fmt.Errorf("ERROR: OpenGL error %X", e)
	}
	return
}
Exemplo n.º 11
0
func (tr *TextRenderer) Draw(tex *Texture, x, y, scale float32) (err error) {
	gl.ActiveTexture(gl.TEXTURE0)
	if e := gl.GetError(); e != 0 {
		return fmt.Errorf("ERROR: %X", e)
	}
	gl.BindTexture(gl.TEXTURE_2D, tex.Texture)
	if e := gl.GetError(); e != 0 {
		return fmt.Errorf("ERROR: %X", e)
	}
	gl.Uniform3f(tr.ScaleLoc, float32(tex.Width)*scale, float32(tex.Height)*scale, 1)
	if e := gl.GetError(); e != 0 {
		return fmt.Errorf("ERROR: %X", e)
	}
	gl.Uniform3f(tr.TransLoc, x, y, 0)
	if e := gl.GetError(); e != 0 {
		return fmt.Errorf("ERROR: %X", e)
	}
	gl.DrawArrays(gl.TRIANGLE_STRIP, 0, 4)
	if e := gl.GetError(); e != 0 {
		return fmt.Errorf("ERROR: %X", e)
	}
	gl.BindBuffer(gl.ARRAY_BUFFER, 0)
	if e := gl.GetError(); e != 0 {
		return fmt.Errorf("ERROR: %X", e)
	}
	return nil
}
Exemplo n.º 12
0
func (tr *TextRenderer) Bind() error {
	gl.UseProgram(tr.Program)
	if e := gl.GetError(); e != 0 {
		return fmt.Errorf("ERROR: %X", e)
	}
	gl.Uniform1i(tr.TextureUnitLoc, 0)
	if e := gl.GetError(); e != 0 {
		return fmt.Errorf("ERROR: %X", e)
	}
	gl.BindBuffer(gl.ARRAY_BUFFER, tr.VBO)
	if e := gl.GetError(); e != 0 {
		return fmt.Errorf("ERROR: %X", e)
	}
	gl.EnableVertexAttribArray(tr.PositionLoc)
	gl.VertexAttribPointer(tr.PositionLoc, 3, gl.FLOAT, false, 5*4, gl.PtrOffset(0))
	if e := gl.GetError(); e != 0 {
		return fmt.Errorf("ERROR: %X", e)
	}
	gl.EnableVertexAttribArray(tr.TextureLoc)
	gl.VertexAttribPointer(tr.TextureLoc, 2, gl.FLOAT, false, 5*4, gl.PtrOffset(3*4))
	if e := gl.GetError(); e != 0 {
		return fmt.Errorf("ERROR: %X", e)
	}
	gl.UniformMatrix4fv(tr.ProjectionLoc, 1, false, &tr.Renderer.Camera.Projection[0])
	if e := gl.GetError(); e != 0 {
		return fmt.Errorf("ERROR: %X", e)
	}
	return nil
}
Exemplo n.º 13
0
func CreateVBO(size int, data interface{}, usage uint32) (buffer uint32, err error) {
	gl.GenBuffers(1, &buffer)
	if e := gl.GetError(); e != 0 {
		err = fmt.Errorf("ERROR gl.GenBuffer %X", e)
		return
	}
	gl.BindBuffer(gl.ARRAY_BUFFER, buffer)
	if e := gl.GetError(); e != 0 {
		err = fmt.Errorf("ERROR buffer.Bind %X", e)
		return
	}
	gl.BufferData(gl.ARRAY_BUFFER, size, gl.Ptr(data), usage)
	if e := gl.GetError(); e != 0 {
		err = fmt.Errorf("ERROR gl.BufferData %X", e)
		return
	}
	gl.BindBuffer(gl.ARRAY_BUFFER, 0)
	if e := gl.GetError(); e != 0 {
		err = fmt.Errorf("ERROR buffer.Unbind %X", e)
		return
	}
	return
}
Exemplo n.º 14
0
func (lr *LinesRenderer) Bind() (err error) {
	gl.UseProgram(lr.program)
	gl.BindBuffer(gl.ARRAY_BUFFER, lr.buffer)
	gl.BindBuffer(gl.ELEMENT_ARRAY_BUFFER, lr.indexBuffer)
	gl.EnableVertexAttribArray(lr.positionLoc)
	gl.EnableVertexAttribArray(lr.normalLoc)
	gl.EnableVertexAttribArray(lr.miterLoc)
	gl.VertexAttribPointer(lr.positionLoc, 2, gl.FLOAT, false, lr.stride, lr.offPosition)
	gl.VertexAttribPointer(lr.normalLoc, 2, gl.FLOAT, false, lr.stride, lr.offNormal)
	gl.VertexAttribPointer(lr.miterLoc, 1, gl.FLOAT, false, lr.stride, lr.offMiter)
	gl.UniformMatrix4fv(lr.projectionLoc, 1, false, &lr.Renderer.Camera.Projection[0])
	if e := gl.GetError(); e != 0 {
		err = fmt.Errorf("ERROR: OpenGL error %X", e)
	}
	return
}
Exemplo n.º 15
0
func ForceCheck() {
	switch gl.GetError() {
	case gl.INVALID_ENUM:
		tlog.Panic("OpenGL Error: GL_INVALID_ENUM")
	case gl.INVALID_VALUE:
		tlog.Panic("OpenGL Error: GL_INVALID_VALUE")
	case gl.INVALID_OPERATION:
		tlog.Panic("OpenGL Error: GL_INVALID_OPERATION")
	case gl.STACK_OVERFLOW:
		tlog.Panic("OpenGL Error: GL_STACK_OVERFLOW")
	case gl.STACK_UNDERFLOW:
		tlog.Panic("OpenGL Error: GL_STACK_UNDERFLOW")
	case gl.OUT_OF_MEMORY:
		tlog.Panic("OpenGL Error: GL_OUT_OF_MEMORY")
	}
}
Exemplo n.º 16
0
func GetGLTexture(img image.Image, smoothing TextureSmoothing) (t uint32, err error) {
	var (
		data   *bytes.Buffer
		bounds image.Rectangle
		width  int
		height int
	)
	if data, err = imageBytes(img); err != nil {
		return
	}
	bounds = img.Bounds()
	width = bounds.Max.X - bounds.Min.X
	height = bounds.Max.Y - bounds.Min.Y
	gl.GenTextures(1, &t)
	if e := gl.GetError(); e != 0 {
		fmt.Printf("ggt1 ERROR: %s\n", e)
	}
	gl.BindTexture(gl.TEXTURE_2D, t)
	if e := gl.GetError(); e != 0 {
		fmt.Printf("ggt2 ERROR: %s\n", e)
	}
	gl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, int32(smoothing))
	if e := gl.GetError(); e != 0 {
		fmt.Printf("ggt3 ERROR: %s\n", e)
	}
	gl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, int32(smoothing))
	if e := gl.GetError(); e != 0 {
		fmt.Printf("ggt4 ERROR: %s\n", e)
	}
	gl.TexImage2D(gl.TEXTURE_2D, 0, gl.RGBA, int32(width), int32(height), 0, gl.RGBA, gl.UNSIGNED_INT_8_8_8_8, gl.Ptr(data.Bytes()))
	if e := gl.GetError(); e != 0 {
		fmt.Printf("ggt5 ERROR: %s\n", e)
	}
	gl.GenerateMipmap(gl.TEXTURE_2D)
	if e := gl.GetError(); e != 0 {
		fmt.Printf("ggt6 ERROR: %s\n", e)
	}
	gl.BindTexture(gl.TEXTURE_2D, 0)
	if e := gl.GetError(); e != 0 {
		fmt.Printf("ggt7 ERROR: %s\n", e)
	}
	return
}
Exemplo n.º 17
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
}
Exemplo n.º 18
0
func (c *Context) CreateWindow(w, h int, name string) (err error) {
	c.w = w
	c.h = h
	c.name = name
	c.createWindow()
	c.SetCursor(c.cursor)
	gl.Init()
	if e := gl.GetError(); e != 0 {
		if e != gl.INVALID_ENUM {
			err = fmt.Errorf("OpenGL glInit error: %X\n", e)
			return
		}
	}
	c.OpenGLVersion = glfw.GetVersionString()
	c.ShaderVersion = gl.GoStr(gl.GetString(gl.SHADING_LANGUAGE_VERSION))
	gl.Enable(gl.BLEND)
	gl.BlendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA)
	gl.ClearColor(0.0, 0.0, 0.0, 1.0)
	gl.Disable(gl.CULL_FACE)
	glfw.SwapInterval(1)
	return
}
Exemplo n.º 19
0
func (r *EffectsRenderer) GetError() error {
	if e := gl.GetError(); e != 0 {
		return fmt.Errorf("OpenGL error: %X", e)
	}
	var status = gl.CheckFramebufferStatus(gl.DRAW_FRAMEBUFFER)
	switch status {
	case gl.FRAMEBUFFER_COMPLETE:
		return nil
	case gl.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:
		return fmt.Errorf("Attachment point unconnected")
	case gl.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:
		return fmt.Errorf("Missing attachment")
	case gl.FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER:
		return fmt.Errorf("Draw buffer")
	case gl.FRAMEBUFFER_INCOMPLETE_READ_BUFFER:
		return fmt.Errorf("Read buffer")
	case gl.FRAMEBUFFER_UNSUPPORTED:
		return fmt.Errorf("Unsupported config")
	default:
		return fmt.Errorf("Unknown framebuffer error: %X", status)
	}
}
Exemplo n.º 20
0
func (p *Program) linkProgram(vertex uint32, fragment uint32) (program uint32, err error) {
	program = gl.CreateProgram()
	gl.AttachShader(program, vertex)
	gl.AttachShader(program, fragment)
	gl.BindFragDataLocation(program, 0, gl.Str("v_FragData\x00"))
	if e := gl.GetError(); e != 0 {
		err = fmt.Errorf("ERROR program.BindFragDataLocation %X", e)
		return
	}
	gl.LinkProgram(program)
	var status int32
	if gl.GetProgramiv(program, gl.LINK_STATUS, &status); status == gl.FALSE {
		var length int32
		gl.GetProgramiv(program, gl.INFO_LOG_LENGTH, &length)
		log := strings.Repeat("\x00", int(length+1))
		gl.GetProgramInfoLog(program, length, nil, gl.Str(log))
		err = fmt.Errorf("ERROR program link:\n%s", log)
	}
	gl.DeleteShader(vertex)
	gl.DeleteShader(fragment)
	return
}
Exemplo n.º 21
0
func MakeProgram(vert, frag string) (uint32, error) {
	vertexShader, err := compileShader(vert, gl.VERTEX_SHADER)
	if err != nil {
		return 0, err
	}

	fragmentShader, err := compileShader(frag, gl.FRAGMENT_SHADER)
	if err != nil {
		return 0, err
	}

	program := gl.CreateProgram()

	gl.AttachShader(program, vertexShader)
	gl.AttachShader(program, fragmentShader)
	gl.LinkProgram(program)

	var status int32
	gl.GetProgramiv(program, gl.LINK_STATUS, &status)
	if status == gl.FALSE {
		var logLength int32
		gl.GetProgramiv(program, gl.INFO_LOG_LENGTH, &logLength)

		log := strings.Repeat("\x00", int(logLength+1))
		gl.GetProgramInfoLog(program, logLength, nil, gl.Str(log))

		return 0, errors.New(fmt.Sprintf("failed to link program: %v", log))
	}

	gl.DeleteShader(vertexShader)
	gl.DeleteShader(fragmentShader)
	if ok := gl.GetError(); ok != gl.NO_ERROR {

		return 0, errors.New("Error in Make Program : " + string(ok))

	}
	return program, nil
}
Exemplo n.º 22
0
func (c *Context) CreateWindow(w, h int, name string) (err error) {
	c.w = w
	c.h = h
	c.name = name
	var monitor *glfw.Monitor
	if c.fullscreen == true {
		monitor = glfw.GetPrimaryMonitor()
	}
	if c.window, err = glfw.CreateWindow(c.w, c.h, c.name, monitor, nil); err != nil {
		return
	}
	if c.cursor == false {
		c.window.SetInputMode(glfw.CursorMode, glfw.CursorHidden)
	}
	c.window.MakeContextCurrent()
	gl.Init()
	if e := gl.GetError(); e != 0 {
		if e == gl.INVALID_ENUM {
			fmt.Printf("GL_INVALID_ENUM when calling glInit\n")
		} else {
			err = fmt.Errorf("OpenGL glInit error: %X\n", e)
			return
		}
	}
	c.OpenGLVersion = glfw.GetVersionString()
	c.ShaderVersion = gl.GoStr(gl.GetString(gl.SHADING_LANGUAGE_VERSION))
	gl.Enable(gl.BLEND)
	gl.BlendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA)
	gl.ClearColor(0.0, 0.0, 0.0, 1.0)
	gl.Disable(gl.CULL_FACE)
	glfw.SwapInterval(1)
	if c.VAO, err = CreateVAO(); err != nil {
		return
	}
	gl.BindVertexArray(c.VAO)
	c.Events = NewEventHandler(c.window)
	return
}
Exemplo n.º 23
0
func (r *Framerate) Render(camera *core.Camera) (err error) {
	r.data.Sample()
	var (
		modelView     = mgl32.Ident4()
		dataBytes int = int(r.data.Count) * int(r.stride)
	)
	gl.Uniform4f(r.locColor, 255.0/255.0, 0, 0, 255.0/255.0)
	gl.UniformMatrix4fv(r.locModelView, 1, false, &modelView[0])
	gl.UniformMatrix4fv(r.locProjection, 1, false, &camera.Projection[0])

	if dataBytes > r.vboBytes {
		r.vboBytes = dataBytes
		gl.BufferData(gl.ARRAY_BUFFER, dataBytes, gl.Ptr(r.data.Points), gl.STREAM_DRAW)
	} else {
		gl.BufferSubData(gl.ARRAY_BUFFER, 0, dataBytes, gl.Ptr(r.data.Points))
	}

	gl.DrawArrays(gl.POINTS, 0, r.data.Count)
	if e := gl.GetError(); e != 0 {
		err = fmt.Errorf("ERROR: OpenGL error %X", e)
	}
	return
}
Exemplo n.º 24
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
}
Exemplo n.º 25
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
}
Exemplo n.º 26
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
}
Exemplo n.º 27
0
func InitGL() error {
	defer tlog.FuncLog(tlog.Func("InitGL"))

	err := gl.Init()
	if err != nil {
		return err
	}
	gl.GetError() // cleanup gl error state

	version := gl.GoStr(gl.GetString(gl.VERSION))
	tlog.Println("OpenGL version", version)

	gl.PolygonMode(gl.FRONT_AND_BACK, gl.FILL)
	Check()
	gl.ReadBuffer(gl.BACK)
	Check()
	gl.DrawBuffer(gl.BACK)
	Check()

	gl.FrontFace(gl.CW)
	Check()
	gl.CullFace(gl.BACK)
	Check()
	gl.Disable(gl.CULL_FACE)
	Check()

	gl.ClearColor(1, 1, 0.5, 0)
	Check()
	gl.ClearDepth(1.0)
	Check()
	gl.ClearStencil(0)
	Check()

	gl.Disable(gl.STENCIL_TEST)
	Check()
	gl.StencilMask(0xFFFFFFFF)
	Check()
	gl.StencilFunc(gl.EQUAL, 0x00000000, 0x00000001)
	Check()
	gl.StencilOp(gl.KEEP, gl.KEEP, gl.KEEP)
	Check()

	gl.Disable(gl.DITHER)
	Check()

	gl.Enable(gl.DEPTH_TEST)
	Check()
	gl.DepthFunc(gl.LEQUAL)
	Check()
	gl.DepthMask(true)
	Check()
	gl.DepthRange(0., 1.)
	Check()
	gl.Enable(gl.DEPTH_CLAMP)
	Check()

	gl.Enable(gl.BLEND)
	Check()
	gl.BlendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA)

	ForceCheck()
	return nil
}
Exemplo n.º 28
0
// LoadDictionary reads a gobbed Dictionary object from r, registers its atlas texture with opengl,
// and returns a Dictionary that is ready to render text.
func LoadDictionary(r io.Reader) (*Dictionary, error) {
	errChan := make(chan error)
	initOnce.Do(func() {
		render.Queue(func() {
			// errChan <- render.RegisterShader("glop.font", []byte(font_vertex_shader), []byte(font_fragment_shader))
			errChan <- render.RegisterShader("glop.font", []byte(font_vshader), []byte(font_fshader))
		})
	})
	err := <-errChan
	if err != nil {
		return nil, err
	}

	var dict Dictionary
	dec := gob.NewDecoder(r)
	err = dec.Decode(&dict)
	if err != nil {
		return nil, err
	}

	render.Queue(func() {
		// Create the gl texture for the atlas
		gl.GenTextures(1, &dict.atlas.texture)
		glerr := gl.GetError()
		if glerr != 0 {
			errChan <- fmt.Errorf("Gl Error on gl.GenTextures: %v", glerr)
			return
		}

		// Send the atlas to opengl
		gl.BindTexture(gl.TEXTURE_2D, dict.atlas.texture)
		gl.PixelStorei(gl.UNPACK_ALIGNMENT, 1)
		gl.TexImage2D(
			gl.TEXTURE_2D,
			0,
			gl.RED,
			dict.Dx,
			dict.Dy,
			0,
			gl.RED,
			gl.UNSIGNED_BYTE,
			gl.Ptr(&dict.Pix[0]))
		glerr = gl.GetError()
		if glerr != 0 {
			errChan <- fmt.Errorf("Gl Error on creating texture: %v", glerr)
			return
		}

		// Create the atlas sampler and set the parameters we want for it
		gl.GenSamplers(1, &dict.atlas.sampler)
		gl.SamplerParameteri(dict.atlas.sampler, gl.TEXTURE_MIN_FILTER, gl.LINEAR)
		gl.SamplerParameteri(dict.atlas.sampler, gl.TEXTURE_MAG_FILTER, gl.LINEAR)
		gl.SamplerParameteri(dict.atlas.sampler, gl.TEXTURE_WRAP_S, gl.REPEAT)
		gl.SamplerParameteri(dict.atlas.sampler, gl.TEXTURE_WRAP_T, gl.REPEAT)
		glerr = gl.GetError()
		if glerr != 0 {
			errChan <- fmt.Errorf("Gl Error on creating sampler: %v", glerr)
			return
		}
		errChan <- nil
	})

	err = <-errChan
	if err != nil {
		return nil, err
	}

	return &dict, nil
}
Exemplo n.º 29
0
// Testing stuff to do with opening an OpenGL context.
func Testing() error {
	window, assets, err := initialize()
	if err != nil {
		return nil
	}
	defer destroy(window, assets)

	shaderProgram, _ := assets.GetProgram("res/shaders/texrenderer")
	texture, _ := assets.GetTexture("res/textures/texture.jpg")
	renderObject := CreateRenderObject(shaderProgram, texture, []float32{
		-1.0, -1.0, 0.0, 0.0,
		1.0, -1.0, 1.0, 0.0,
		1.0, 1.0, 1.0, 1.0,
		-1.0, 1.0, 0.0, 1.0,
	})
	defer renderObject.Destroy()

	// Testing a LineRender.
	lineShader, err := LoadShaderProgram("res/shaders/lineshader")
	if err != nil {
		fmt.Println("LSP: " + err.Error())
	}
	defer DestroyShaderProgram(lineShader)

	lineRenders := []*LineRender{
		NewLineRender(lineShader, GetPastel(1), true, 3.0, []Point{
			Point{-1.0, 0},
			Point{1.0, 0},
		}),

		NewLineRender(lineShader, GetPastel(2), true, 8.0, []Point{
			Point{-0.5, -0.5},
			Point{0.5, 0.5},
			Point{1, 0},
		}),
	}
	defer func() {
		for _, lr := range lineRenders {
			lr.Destroy()
		}
	}()

	// Creating a 2nd LineRender from DefaultGenerateSinePoints.
	var phase float32 = 0
	lineRender2 := NewLineRender(
		lineShader,
		GetPastel(0),
		false,
		4.0,
		DefaultGenerateSinePoints(440, phase))
	defer lineRender2.Destroy()

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

		// Rendering the outputs.
		renderObject.Render()
		for _, lr := range lineRenders {
			lr.Render()
		}
		lineRender2.Render()

		// Updating render for lineRender2.
		phase += 2 * math.Pi * (440.0 / 44100.0)
		if phase > 2*math.Pi {
			phase -= 2 * math.Pi
		}
		lineRender2.UpdatePoints(DefaultGenerateSinePoints(440, phase))

		if config.DebugMode {
			// Reporting OpenGL errors.
			glErr := gl.GetError()
			if glErr != gl.NO_ERROR {
				fmt.Printf("OpenGL error: %d\n", glErr)
			}
		}

		window.SwapBuffers()
		glfw.PollEvents()
		time.Sleep(10 * time.Millisecond)
	}

	return nil
}