Esempio n. 1
0
func (s *MainState) Resize(width, height int) {
	aspect := float32(width) / float32(height)
	if width > height {
		s.projection = mgl32.Ortho2D(-aspect, aspect, -1, 1)
	} else {
		s.projection = mgl32.Ortho2D(-1, 1, -1/aspect, 1/aspect)
	}
	gl.Viewport(0, 0, int32(width), int32(height))
}
Esempio n. 2
0
func (s *MainState) Resize(width int, height int) {
	println("resize!", width, height)
	aspect := float32(width) / float32(height)
	if width > height {
		projection = mgl32.Ortho2D(-aspect, aspect, -1, 1)
	} else {
		projection = mgl32.Ortho2D(-1, 1, -1/aspect, 1/aspect)
	}
	gl.Viewport(0, 0, int32(width), int32(height))

	return
}
// NewBasicRenderContext returns a render context for the provided parameters.
func NewBasicRenderContext(width, height int, viewMatrix mgl32.Mat4) *RenderContext {
	return &RenderContext{
		viewportWidth:    width,
		viewportHeight:   height,
		viewMatrix:       viewMatrix,
		projectionMatrix: mgl32.Ortho2D(0, float32(width), float32(height), 0)}
}
Esempio n. 4
0
File: gl.go Progetto: gmacd/rt
func (glr *GlRenderer) initScreen() {
	var err error
	glr.program, err = createScreenShader()
	if err != nil {
		panic(err)
	}

	gl.UseProgram(glr.program)

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

	textureUniform := gl.GetUniformLocation(glr.program, gl.Str("tex\x00"))
	gl.Uniform1i(textureUniform, 0)

	glr.texture = createScreenTexture(glr.width, glr.height)

	gl.GenVertexArrays(1, &glr.vao)
	gl.BindVertexArray(glr.vao)

	var quadVertices = []float32{
		//  X, Y, Z, U, V
		1.0, -1.0, 0.0, 1.0, 0.0,
		-1.0, -1.0, 0.0, 0.0, 0.0,
		1.0, 1.0, 0.0, 1.0, 1.0,
		-1.0, -1.0, 0.0, 0.0, 0.0,
		-1.0, 1.0, 0.0, 0.0, 1.0,
		1.0, 1.0, 0.0, 1.0, 1.0,
	}

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

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

	texCoordAttrib := uint32(gl.GetAttribLocation(glr.program, gl.Str("vertTexCoord\x00")))
	gl.EnableVertexAttribArray(texCoordAttrib)
	gl.VertexAttribPointer(texCoordAttrib, 2, gl.FLOAT, false, 5*4, gl.PtrOffset(3*4))

	gl.Enable(gl.DEPTH_TEST)
	gl.ClearColor(1.0, 1.0, 1.0, 1.0)
}
Esempio n. 5
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}
}
Esempio n. 6
0
func main() {
	glfw.SetErrorCallback(errorCallback)
	// lock glfw/gl calls to a single thread
	runtime.LockOSThread()
	runtime.GOMAXPROCS(8) // Render, read commands, send input, extra for file loading, etc

	if !glfw.Init() {
		panic("Could not init glfw!")
	}

	defer glfw.Terminate()

	glfw.WindowHint(glfw.ContextVersionMajor, 3)
	glfw.WindowHint(glfw.ContextVersionMinor, 3)
	glfw.WindowHint(glfw.OpenglForwardCompatible, glfw.True)
	glfw.WindowHint(glfw.OpenglProfile, glfw.OpenglCoreProfile)

	window, err := glfw.CreateWindow(800, 600, "Example", nil, nil)
	if err != nil {
		panic(err)
	}

	window.SetFramebufferSizeCallback(func(w *glfw.Window, width, height int) {
		fmt.Printf("Framebuffer size is now %vx%v\n", width, height)
		// Keep aspect ratio from camwidth/camheight
		camRatio := camWidth / camHeight
		bufRatio := float32(width) / float32(height)
		var newWidth, newHeight float32

		switch {
		case camRatio > bufRatio:
			newHeight = float32(width) / camRatio
			newWidth = float32(width)
		case bufRatio > camRatio:
			newWidth = float32(height) * camRatio
			newHeight = float32(height)
		}

		fmt.Printf("Viewport size is now %vx%v; cam ratio is %v; viewport ratio is %v;\n", newWidth, newHeight, camRatio, newWidth/newHeight)

		gl.Viewport((width-int(newWidth))/2, (height-int(newHeight))/2, int(newWidth), int(newHeight))
	})

	defer window.Destroy()

	window.MakeContextCurrent()
	glfw.SwapInterval(1)

	gl.Init()

	// Enable blending
	gl.Enable(gl.BLEND)
	gl.BlendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA)

	vao := gl.GenVertexArray()
	vao.Bind()

	vbo := gl.GenBuffer()
	vbo.Bind(gl.ARRAY_BUFFER)

	verticies := []float32{-0.5, 0.5,
		0.5, 0.5,
		0.5, -0.5,
		-0.5, -0.5}

	gl.BufferData(gl.ARRAY_BUFFER, len(verticies)*4, verticies, gl.STATIC_DRAW)

	vertex_shader := gl.CreateShader(gl.VERTEX_SHADER)
	vertex_shader.Source(vertex)
	vertex_shader.Compile()
	fmt.Println(vertex_shader.GetInfoLog())
	defer vertex_shader.Delete()

	fragment_shader := gl.CreateShader(gl.FRAGMENT_SHADER)
	fragment_shader.Source(fragment)
	fragment_shader.Compile()
	fmt.Println(fragment_shader.GetInfoLog())
	defer fragment_shader.Delete()

	program := gl.CreateProgram()
	program.AttachShader(vertex_shader)
	program.AttachShader(fragment_shader)

	program.BindFragDataLocation(0, "outColor")
	program.Link()
	program.Use()
	defer program.Delete()

	positionAttrib := program.GetAttribLocation("position")
	positionAttrib.AttribPointer(2, gl.FLOAT, false, 0, nil)
	positionAttrib.EnableArray()
	defer positionAttrib.DisableArray()

	modelMat := program.GetUniformLocation("modelView")
	projMat := program.GetUniformLocation("projection")
	spriteSize := program.GetUniformLocation("size")

	cmd := exec.Command(os.Args[1], os.Args[2:]...)
	stdoutReader, stdoutWriter := io.Pipe()
	cmd.Stdout = stdoutWriter
	input := bufio.NewReader(stdoutReader)

	stdinReader, stdinWriter := io.Pipe()
	cmd.Stdin = stdinReader

	stderr, err := cmd.StderrPipe()
	chkErr(err)

	go io.Copy(os.Stderr, stderr)

	err = cmd.Start()
	chkErr(err)

	window.SetKeyCallback(handleKey)

	go func() {
		runtime.LockOSThread()
		for !window.ShouldClose() {
			sendInput(stdinWriter)
			//fmt.Fprintf(stdinWriter, "T %v\n", time.Now())
			<-ticks
			readCommands(input)
		}
	}()

	frameCnt := 0
	queueDepth := 0
	then := time.Now()

	for !window.ShouldClose() {
		frameCnt++
		queueDepth += len(commandBus)
		if frameCnt%120 == 0 {
			fmt.Printf("Queue depth: %v. Render time: %v. Decode time: %v.\n", queueDepth/120, time.Since(then)/120, decodeTime/time.Duration(decodes))
			queueDepth = 0
			then = time.Now()
			decodeTime = time.Duration(0)
			decodes = 0
		}

		for len(commandBus) > 0 {
			(<-commandBus)()
		}

		halfwidth := camWidth / 2.0
		halfheight := camHeight / 2.0
		projection := mathgl.Ortho2D(camera.x-halfwidth, camera.x+halfwidth, camera.y+halfheight, camera.y-halfheight)
		projection = mathgl.Scale3D(camera.sx, camera.sy, 1).Mul4(projection)
		projection = mathgl.HomogRotate3DZ(camera.rot).Mul4(projection)

		projMat.UniformMatrix4f(false, (*[16]float32)(&projection))

		gl.Clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT)

		for _, sprite := range sprites {
			sMat := mathgl.Scale3D(sprite.sx, sprite.sy, 1)
			sMat = mathgl.HomogRotate3DZ(sprite.rot).Mul4(sMat)
			sMat = mathgl.Translate3D(sprite.x, sprite.y, sprite.z).Mul4(sMat)

			// temp hack bank in
			sprite.bank = 1

			sMap := findSMap(sprite.smap)

			spriteSize.Uniform2f(float32(sMap.getWidth()*sprite.cellwidth), float32(sMap.getHeight()*sprite.cellheight))

			modelMat.UniformMatrix4f(false, (*[16]float32)(&sMat))
			gl.DrawArrays(gl.TRIANGLE_FAN, 0, 4)
		}

		window.SwapBuffers()
		glfw.PollEvents()

		if window.GetKey(glfw.KeyEscape) == glfw.Press {
			window.SetShouldClose(true)
		}
	}
}
Esempio n. 7
0
func (f *Font) ResizeWindow(width float32, height float32) {
	f.WindowWidth = width
	f.WindowHeight = height
	f.OrthographicMatrix = mgl32.Ortho2D(-f.WindowWidth/2, f.WindowWidth/2, -f.WindowHeight/2, f.WindowHeight/2)
}
Esempio n. 8
0
func (glRenderer *OpenglRenderer) DrawGeometry(geometry *renderer.Geometry, transform mgl32.Mat4) {
	glRenderer.enableShader()
	glRenderer.enableMaterial()
	glRenderer.enableCubeMap()

	if glRenderer.activeShader == nil {
		panic("ERROR: No shader is configured.")
	}

	shader := glRenderer.activeShader
	program := shader.Program
	params := glRenderer.rendererParams

	glRenderer.enableDepthTest(params.DepthTest)
	glRenderer.enableDepthMask(params.DepthMask)
	glRenderer.enableCullFace(params.CullBackface)
	glRenderer.enableUnlit(params.Unlit)
	glRenderer.setTransparency(params.Transparency)

	// set buffers
	gl.BindBuffer(gl.ARRAY_BUFFER, geometry.VboId)
	gl.BindBuffer(gl.ELEMENT_ARRAY_BUFFER, geometry.IboId)

	// update buffers
	if geometry.VboDirty && len(geometry.Verticies) > 0 && len(geometry.Indicies) > 0 {
		gl.BufferData(gl.ARRAY_BUFFER, len(geometry.Verticies)*4, gl.Ptr(geometry.Verticies), gl.DYNAMIC_DRAW)
		gl.BufferData(gl.ELEMENT_ARRAY_BUFFER, len(geometry.Indicies)*4, gl.Ptr(geometry.Indicies), gl.DYNAMIC_DRAW)
		geometry.VboDirty = false
	}

	// set uniforms
	modelNormal := transform.Inv().Transpose()
	shader.Uniforms["model"] = transform
	shader.Uniforms["modelNormal"] = modelNormal

	// set camera uniforms
	cam := glRenderer.camera
	win := glRenderer.WindowDimensions()
	shader.Uniforms["cameraTranslation"] = cam.Translation
	if cam.Ortho {
		shader.Uniforms["projection"] = mgl32.Ortho2D(0, win.X(), win.Y(), 0)
		shader.Uniforms["camera"] = mgl32.Ident4()
	} else {
		shader.Uniforms["projection"] = mgl32.Perspective(mgl32.DegToRad(cam.Angle), win.X()/win.Y(), cam.Near, cam.Far)
		shader.Uniforms["camera"] = mgl32.LookAtV(cam.Translation, cam.Lookat, cam.Up)
	}

	shader.Uniforms["unlit"] = glRenderer.unlit
	shader.Uniforms["useTextures"] = glRenderer.useTextures

	shader.Uniforms["ambientLightValue"] = glRenderer.ambientLightValue

	shader.Uniforms["nbPointLights"] = glRenderer.nbPointLights
	shader.Uniforms["pointLightValues"] = glRenderer.pointLightValues
	shader.Uniforms["pointLightPositions"] = glRenderer.pointLightPositions

	shader.Uniforms["nbDirectionalLights"] = glRenderer.nbDirectionalLights
	shader.Uniforms["directionalLightValues"] = glRenderer.directionalLightValues
	shader.Uniforms["directionalLightVectors"] = glRenderer.directionalLightVectors

	// set custom uniforms
	setupUniforms(shader)

	// set verticies attribute
	vertAttrib := uint32(gl.GetAttribLocation(program, gl.Str("vert\x00")))
	gl.EnableVertexAttribArray(vertAttrib)
	gl.VertexAttribPointer(vertAttrib, 3, gl.FLOAT, false, renderer.VertexStride*4, gl.PtrOffset(0))
	// set normals attribute
	normAttrib := uint32(gl.GetAttribLocation(program, gl.Str("normal\x00")))
	gl.EnableVertexAttribArray(normAttrib)
	gl.VertexAttribPointer(normAttrib, 3, gl.FLOAT, false, renderer.VertexStride*4, gl.PtrOffset(3*4))
	// set texture coord attribute
	texCoordAttrib := uint32(gl.GetAttribLocation(program, gl.Str("texCoord\x00")))
	gl.EnableVertexAttribArray(texCoordAttrib)
	gl.VertexAttribPointer(texCoordAttrib, 2, gl.FLOAT, false, renderer.VertexStride*4, gl.PtrOffset(6*4))
	// vertex color attribute
	colorAttrib := uint32(gl.GetAttribLocation(program, gl.Str("color\x00")))
	gl.EnableVertexAttribArray(colorAttrib)
	gl.VertexAttribPointer(colorAttrib, 4, gl.FLOAT, false, renderer.VertexStride*4, gl.PtrOffset(8*4))

	gl.DrawElements(gl.TRIANGLES, (int32)(len(geometry.Indicies)), gl.UNSIGNED_INT, gl.PtrOffset(0))
}