Example #1
0
File: main.go Project: andrebq/exp
func main() {
	glfw.SetErrorCallback(glfwError)

	if !glfw.Init() {
		log.Printf("Unable to initializer glfw")
		return
	}
	defer glfw.Terminate()

	window, err := glfw.CreateWindow(Width, Height, Title, nil, nil)
	if err != nil {
		panic(err)
	}
	window.MakeContextCurrent()
	window.SetSizeCallback(fixProjection)

	err = initGL()
	if err != nil {
		log.Printf("Error initializing OpenGL. %v", err)
		panic(err)
	}

	glfw.SwapInterval(1)
	fixProjection(window, Width, Height)

	meshBuff := createMeshBuffer()

	for !window.ShouldClose() {
		timeDelta.Tick()
		log.Printf("Time: %v", timeDelta.Delta)
		window.SwapBuffers()
		glfw.PollEvents()
	}
}
Example #2
0
func main() {
	fmt.Println("Init GLFW3")
	if glfw3.Init() {
		fmt.Println("Init ok")
		defer closeGLFW()
	}

	// Create the window
	fmt.Println("Opening window")
	win, err := glfw3.CreateWindow(1024, 768, "Kunos Rulez", nil, nil)
	gl.Init()
	if err != nil {
		fmt.Println(err)
	} else {
		fmt.Println("ok", win)
	}

	win.MakeContextCurrent()

	for win.ShouldClose() == false {
		glfw3.PollEvents()
		gl.ClearColor(1.0, 0.0, 0.0, 1.0)
		gl.Clear(gl.COLOR_BUFFER_BIT)

		win.SwapBuffers()
	}

	fmt.Println("Destroying win")
	win.Destroy()
}
Example #3
0
func main() {

	if !glfw.Init() {
		log.Fatal("glfw failed to initialize")
	}
	defer glfw.Terminate()

	window, err := glfw.CreateWindow(640, 480, "Deformable", nil, nil)
	if err != nil {
		log.Fatal(err.Error())
	}

	window.MakeContextCurrent()
	glfw.SwapInterval(1)
	window.SetMouseButtonCallback(handleMouseButton)
	window.SetKeyCallback(handleKeyDown)
	window.SetInputMode(glfw.Cursor, glfw.CursorHidden)

	gl.Init()
	initGL()

	i := 16
	m = GenerateMap(1600/i, 1200/i, i)
	for running && !window.ShouldClose() {

		x, y := window.GetCursorPosition()

		if drawing != 0 {
			m.Add(int(x)+int(camera[0]), int(y)+int(camera[1]), drawing, brushSizes[currentBrushSize])
		}

		gl.Clear(gl.COLOR_BUFFER_BIT)
		gl.LoadIdentity()

		gl.PushMatrix()
		gl.PushAttrib(gl.CURRENT_BIT | gl.ENABLE_BIT | gl.LIGHTING_BIT | gl.POLYGON_BIT | gl.LINE_BIT)
		gl.Translatef(-camera[0], -camera[1], 0)
		m.Draw()
		gl.PopAttrib()
		gl.PopMatrix()

		gl.PushAttrib(gl.COLOR_BUFFER_BIT)
		gl.LineWidth(2)
		gl.Enable(gl.BLEND)
		gl.BlendFunc(gl.ONE_MINUS_DST_COLOR, gl.ZERO)
		// gl.Enable(gl.LINE_SMOOTH)
		// gl.Hint(gl.LINE_SMOOTH_HINT, gl.NICEST)

		gl.Translatef(float32(x), float32(y), 0)

		gl.EnableClientState(gl.VERTEX_ARRAY)
		gl.VertexPointer(2, gl.DOUBLE, 0, cursorVerts)
		gl.DrawArrays(gl.LINE_LOOP, 0, 24)
		gl.PopAttrib()

		window.SwapBuffers()
		glfw.PollEvents()
	}

}
Example #4
0
File: main.go Project: srm88/blocks
func main() {
	glfw.SetErrorCallback(errorCallback)

	if !glfw.Init() {
		panic("Can't init glfw")
	}
	defer glfw.Terminate()

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

	window.MakeContextCurrent()
	window.SetSizeCallback(copiedReshape)
	window.SetKeyCallback(keyHandler)

	copiedInit()
	running := true
	for running && !window.ShouldClose() {
		//copiedDrawCube(angle)
		redraw()
		window.SwapBuffers()
		glfw.PollEvents()
		running = window.GetKey(glfw.KeyEscape) == glfw.Release
	}
}
Example #5
0
func main() {
	glfw.SetErrorCallback(glfwErrorCallback)
	if !glfw.Init() {
		panic("failed to initialize glfw")
	}
	defer glfw.Terminate()

	glfw.WindowHint(glfw.Resizable, glfw.False)
	glfw.WindowHint(glfw.ContextVersionMajor, 2)
	glfw.WindowHint(glfw.ContextVersionMinor, 1)
	window, err := glfw.CreateWindow(800, 600, "Cube", nil, nil)
	if err != nil {
		panic(err)
	}
	window.MakeContextCurrent()

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

	texture = newTexture("square.png")
	defer gl.DeleteTextures(1, &texture)

	setupScene()
	for !window.ShouldClose() {
		drawScene()
		window.SwapBuffers()
		glfw.PollEvents()
	}
}
Example #6
0
func main() {
	glfw.SetErrorCallback(errorCallback)

	if !glfw.Init() {
		panic("Can't init glfw!")
	}
	defer glfw.Terminate()

	window, err := glfw.CreateWindow(Width, Height, Title, nil, nil)
	if err != nil {
		panic(err)
	}

	window.MakeContextCurrent()

	glfw.SwapInterval(1)

	gl.Init()

	if err := initScene(); err != nil {
		fmt.Fprintf(os.Stderr, "init: %s\n", err)
		return
	}
	defer destroyScene()

	for !window.ShouldClose() {
		drawScene()
		window.SwapBuffers()
		glfw.PollEvents()
	}
}
Example #7
0
func onTick(programState programState, dt uint64) (programState, bool) {
	glfw.PollEvents()
	keepTicking := !programState.Gl.Window.ShouldClose()
	if keepTicking {
		// Read raw inputs.
		keys := programState.Gl.glfwKeyEventList.Freeze()
		// Analyze the inputs, see what they mean.
		commands := commands(keys)
		// One of these commands may correspond to an action of the player's actor.
		// We take it out so that we can process it in the IA phase.
		// The remaining commands are kept for further processing.
		playerAction, commands := commandsToAction(commands, programState.World.Player_id)
		// Evolve the program one step.
		programState.World.Time += dt // No side effect, we own a copy.
		// $$$ THERE COULD BE SIDE EFFECTS HERE ACTUALLY:  IF I GAVE A POINTER
		// TO THE WORLD OR PROGRAM STATE TO SOMETHING.  NEED TO CORRECT THAT.
		programState = executeCommands(programState, commands)
		//
		programState.World = runAI(programState.World, playerAction)
		// render on screen.
		render(programState)
		programState.Gl.Window.SwapBuffers()
	}
	return programState, keepTicking
}
Example #8
0
func main() {
	runtime.LockOSThread()

	if !glfw.Init() {
		fmt.Fprintf(os.Stderr, "Can't open GLFW")
		return
	}
	defer glfw.Terminate()

	glfw.WindowHint(glfw.Samples, 4)
	glfw.WindowHint(glfw.ContextVersionMajor, 3)
	glfw.WindowHint(glfw.ContextVersionMinor, 3)
	glfw.WindowHint(glfw.OpenglProfile, glfw.OpenglCoreProfile)
	glfw.WindowHint(glfw.OpenglForwardCompatible, glfw.True) // needed for macs

	window, err := glfw.CreateWindow(1024, 768, "Tutorial 1", nil, nil)
	if err != nil {
		fmt.Fprintf(os.Stderr, "%v\n", err)
		return
	}

	window.MakeContextCurrent()

	gl.Init()
	gl.GetError() // Ignore error
	window.SetInputMode(glfw.StickyKeys, 1)

	gl.ClearColor(0., 0., 0.4, 0.)
	// Equivalent to a do... while
	for ok := true; ok; ok = (window.GetKey(glfw.KeyEscape) != glfw.Press && !window.ShouldClose()) {
		window.SwapBuffers()
		glfw.PollEvents()
	}

}
Example #9
0
File: main.go Project: andrebq/exp
func main() {
	glfw.SetErrorCallback(errorCallback)

	if !glfw.Init() {
		panic("Can't init glfw!")
	}
	defer glfw.Terminate()

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

	glfw.SwapInterval(1)
	gl.Init()

	mvp := prepareModelViewProjection(800, 640)

	prepareScene()
	dt := float64(0)
	glfw.SetTime(dt)

	for !window.ShouldClose() {
		dt = glfw.GetTime()
		glfw.SetTime(0)
		updateScene(dt)
		drawScene(mvp, dt)
		window.SwapBuffers()
		glfw.PollEvents()
	}
}
Example #10
0
func (a *Application) Continue() bool {
	glfw.PollEvents()
	if a.window.ShouldClose() {
		return false
	}
	a.update()
	return true
}
Example #11
0
func runGameLoop(window *glfw.Window) {
	for !window.ShouldClose() {
		// update objects
		updateObjects()

		// hit detection
		hitDetection()

		// ---------------------------------------------------------------
		// draw calls
		gl.Clear(gl.COLOR_BUFFER_BIT)

		drawCurrentScore()
		drawHighScore()

		if isGameWon() {
			drawWinningScreen()
		} else if isGameLost() {
			drawGameOverScreen()
		}

		// draw everything 9 times in a 3x3 grid stitched together for seamless clipping
		for x := -1.0; x < 2.0; x++ {
			for y := -1.0; y < 2.0; y++ {
				gl.MatrixMode(gl.MODELVIEW)
				gl.PushMatrix()
				gl.Translated(gameWidth*x, gameHeight*y, 0)

				drawObjects()

				gl.PopMatrix()
			}
		}

		gl.Flush()
		window.SwapBuffers()
		glfw.PollEvents()

		// switch resolution
		if altEnter {
			window.Destroy()

			fullscreen = !fullscreen
			var err error
			window, err = initWindow()
			if err != nil {
				panic(err)
			}

			altEnter = false

			gl.LineWidth(1)
			if fullscreen {
				gl.LineWidth(2)
			}
		}
	}
}
Example #12
0
func eventLoop(g *Game) {
	eventTicker := time.NewTicker(time.Millisecond * 10)

	for {
		select {
		case <-eventTicker.C:
			do(func() {
				glfw.PollEvents()
			})
		}
	}
}
Example #13
0
func (t *Testbed) UntilClose(drawingFunction func()) {

	for !t.window.ShouldClose() {

		glfw.PollEvents()

		gl.Clear(gl.COLOR_BUFFER_BIT)
		drawingFunction()
		t.window.SwapBuffers()
	}

	t.window.Destroy()
}
Example #14
0
// Run starts the main loop.
func (e *E) Run() error {
	if !e.IsInitialized() {
		return fmt.Errorf("not initialized")
	}

	if err := e.state.Init(e); err != nil {
		return err
	}

	if state, ok := e.state.(Resizer); ok {
		width, height := e.window.GetFramebufferSize()
		state.Resize(width, height)
	}

	const dt = 1.0 / 60.0
	for { // FIXME: lock graphics timestep
		var _ = mgl64.Clamp
		var _ = time.Now()

		if state, ok := e.state.(Updater); ok {
			if err := state.Update(dt); err != nil {
				return err
			}
		}

		if state, ok := e.state.(Renderer); ok {
			if err := state.Render(); err != nil {
				return err
			}
		}

		glfw3.PollEvents()

		if e.window.ShouldClose() {
			if state, ok := e.state.(Closer); ok {
				if err := state.Close(); err != nil {
					return err
				}
			}
			return nil
		}

		e.window.SwapBuffers()
	}

	return nil
}
Example #15
0
File: run.go Project: james4k/exp
// ListenForEvents should be called by your main function, and will
// block indefinitely. This is necessary because some platforms expect
// calls from the main thread.
func ListenForEvents() error {
	// ensure we have at least 2 procs, due to the thread conditions we
	// have to work with.
	procs := runtime.GOMAXPROCS(0)
	if procs < 2 {
		runtime.GOMAXPROCS(2)
	}

	glfw.Init()
	defer glfw.Terminate()
	setupGlfw()

	t0 := time.Now()
	for {
		select {
		case fn, ok := <-mainc:
			if !ok {
				return nil
			}
			fn()
		default:
			// when under heavy activity, sleep and poll instead to
			// lessen sysmon() churn in Go's scheduler. with this
			// method, OS X's Activity Monitor reports over 1000 sleeps
			// a second, which is ridiculous, but better than 3000.
			// haven't been able to create a minimal reproduction of
			// this, but when tweaking values in runtime/proc.c's sysmon
			// func, it is obvious this is a scheduler issue.
			// TODO: best workaround is probably to write this entire
			// loop in C, which should keep the sysmon thread from
			// waking up (from these syscalls, anyways).
			dt := time.Now().Sub(t0)
			if dt < 150*time.Millisecond {
				time.Sleep(15 * time.Millisecond)
				glfw.PollEvents()
			} else {
				t0 = time.Now()
				glfw.WaitEvents()
			}
		}
	}
	return nil
}
Example #16
0
func (self *Window) Start() chan bool {
	now := time.Now()
	// This is the ever important draw goroutine
	go func() {

		// super important
		runtime.LockOSThread()
		ctx := vg.NewContext()
		for !self.window.ShouldClose() {
			// gl.Enable(gl.BLEND)
			// gl.Enable(gl.LINE_SMOOTH)
			// gl.Hint(gl.LINE_SMOOTH_HINT, gl.NICEST)
			// gl.BlendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA)

			w, h := self.Size()
			self.SetBounds(0, 0, float64(w), float64(h))

			if time.Since(now) > 2*time.Second {
				debug = true

				self.Draw(ctx)
				debug = false
				now = time.Now()
			} else {
				self.Draw(ctx)
			}
			self.window.SwapBuffers()
			glfw.PollEvents()

			// var total gl.Int
			// gl.GetIntegerv(0x9048, &total)

			// var available gl.Int
			// gl.GetIntegerv(0x9049, &available)

			// fmt.Println(total, available)
		}
		glfw.Terminate()
		self.endchan <- true
	}()
	return self.endchan
}
Example #17
0
func main() {
	if !glfw.Init() {
		f.Println("Failed to init glfw")
		panic("Cannot initialize glfw library")
	}
	defer glfw.Terminate()

	//glfw.WindowHint(glfw.DepthBits, 16)
	window, err := glfw.CreateWindow(300, 300, "Wander", nil, nil)
	if err != nil {
		panic(err)
	}

	window.SetFramebufferSizeCallback(reshape)
	window.SetKeyCallback(key)
	window.MakeContextCurrent()
	glfw.SwapInterval(1)
	width, height := window.GetFramebufferSize()
	reshape(window, width, height)

	if gl.Init() != 0 {
		panic("Failed to init GL")
	}

	prog := setupProgram()
	defer prog.Delete()
	prog.Use()

	attr = prog.GetAttribLocation("offset")

	setup()
	for !window.ShouldClose() {
		if shouldRender() {
			draw()
		}
		animate()
		window.SwapBuffers()
		glfw.PollEvents()
	}

}
Example #18
0
func main() {
	glfw.SetErrorCallback(errorCallback)

	if !glfw.Init() {
		panic("Can't init glfw!")
	}
	defer glfw.Terminate()

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

	window.MakeContextCurrent()

	for !window.ShouldClose() {
		//Do OpenGL stuff
		window.SwapBuffers()
		glfw.PollEvents()
	}
}
Example #19
0
func main() {
	if !glfw.Init() {
		panic("Failed to initialize GLFW")
	}

	defer glfw.Terminate()

	glfw.WindowHint(glfw.DepthBits, 16)

	window, err := glfw.CreateWindow(300, 300, "Gears", nil, nil)
	if err != nil {
		panic(err)
	}

	// Set callback functions
	window.SetFramebufferSizeCallback(reshape)
	window.SetKeyCallback(key)

	window.MakeContextCurrent()
	glfw.SwapInterval(1)

	width, height := window.GetFramebufferSize()
	reshape(window, width, height)

	// Parse command-line options
	Init()

	// Main loop
	for !window.ShouldClose() {
		// Draw gears
		draw()

		// Update animation
		animate()

		// Swap buffers
		window.SwapBuffers()
		glfw.PollEvents()
	}
}
Example #20
0
func RunGamehost() {
	if !glfw.Init() {
		panic("Cannot init GLFW")
	}

	defer glfw.Terminate()

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

	window.MakeContextCurrent()
	gamehost_Window = window

	gl.ClearColor(1, 1, 1, 1)
	glu.LookAt(0, 1.5, 5, 0, 0, 0, 0, 1, 0)
	frame := 0

	EvaluateString("(trigger GAMEHOST Init!)", MainContext)

	gamehost_world.Create(CreateCube(0, 0, 0))

	for !gamehost_Window.ShouldClose() {
		gl.Clear(gl.COLOR_BUFFER_BIT)
		gl.LoadIdentity()
		gamehost_Window.SetTitle(fmt.Sprintf("Frame #%v", frame))
		frame++

		EvaluateString("(gameloop 0.016)", MainContext)

		gamehost_world.Render()
		graphicsQueue.Process()

		gamehost_Window.SwapBuffers()
		glfw.PollEvents()
	}

	EvaluateString("(trigger GAMEHOST Shutdown!)", MainContext)
}
Example #21
0
func main() {
	// initialize glfw
	if !glfw.Init() {
		panic("Failed to initialize GLFW")
	}
	defer glfw.Terminate()

	// create window
	window, err := glfw.CreateWindow(600, 600, os.Args[0], nil, nil)
	if err != nil {
		panic(err)
	}
	window.SetFramebufferSizeCallback(onResize)

	window.MakeContextCurrent()
	// set up opengl context
	onResize(window, 600, 600)

	// set up physics
	createBodies()

	runtime.LockOSThread()
	glfw.SwapInterval(1)

	ticksToNextBall := 10
	ticker := time.NewTicker(time.Second / 60)
	for !window.ShouldClose() {
		ticksToNextBall--
		if ticksToNextBall == 0 {
			ticksToNextBall = rand.Intn(100) + 1
			addBall()
		}
		draw()
		step(1.0 / 60.0)
		window.SwapBuffers()
		glfw.PollEvents()

		<-ticker.C // wait up to 1/60th of a second
	}
}
Example #22
0
func main() {
	flag.Parse()
	glfw.SetErrorCallback(errorCallback)
	if !glfw.Init() {
		println("glfw init failure")
	}
	defer glfw.Terminate()
	glfw.WindowHint(glfw.ClientApi, glfw.OpenglEsApi)
	glfw.WindowHint(glfw.ContextVersionMajor, 2)
	glfw.WindowHint(glfw.ContextVersionMinor, 0)
	window, err := glfw.CreateWindow(Width, Height, Title, nil, nil)
	if err != nil {
		panic(err)
	}
	defer window.Destroy()
	window.MakeContextCurrent()
	glfw.SwapInterval(1)
	window.SetSizeCallback(reshape)
	window.SetKeyCallback(keyEvent)
	gl.Viewport(0, 0, Width, Height)
	initScene()

	if *debug {
		go func() {
			tick := time.Tick(1 * time.Second)
			for {
				<-tick
				fmt.Printf("FPS:%v\tGOROUTINE:%v\r", atomic.LoadUint64(fps), runtime.NumGoroutine())
				atomic.StoreUint64(fps, 0)
			}
		}()
	}
	for !window.ShouldClose() {
		drawScene()
		window.SwapBuffers()
		glfw.PollEvents()
		atomic.AddUint64(fps, 1)
	}
}
Example #23
0
File: gon.go Project: jimarnold/gon
func main() {
	initGlfw()
	defer terminateGlfw()
	window := createWindow(int(width), int(height))
	game := NewGame(window)
	profiler := NewProfiler(game.text)
	defer game.delete()

	previousFrameTime := glfw.GetTime()
	profiler.start()
	for !window.ShouldClose() {
		now := glfw.GetTime()
		elapsed := now - previousFrameTime
		previousFrameTime = now
		game.update(elapsed)
		game.render()
		profiler.update()
		profiler.render()
		window.SwapBuffers()
		glfw.PollEvents()
	}
}
Example #24
0
func main() {
	fmt.Printf("Launching cardgame...\n")

	glfw.SetErrorCallback(onError)

	if !glfw.Init() {
		panic("OpenGL initialization failed.")
	}

	defer glfw.Terminate()

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

	window.MakeContextCurrent()
	window.SetTitle("Cardgame")

	screenWidth, screenHeight := GetScreenSize()
	window.SetPosition(screenWidth/2-400, screenHeight/2-300)

	gl.Init()
	gl.ClearColor(0.5, 0.5, 0.75, 0)
	gl.Ortho(0, 800, 0, 600, 0, 1)

	playfield := NewPlayfield()

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

		playfield.Draw()

		window.SwapBuffers()
		glfw.PollEvents()
	}
}
Example #25
0
func main() {
	go m.Do(func() {
		defer m.Exit()
		runtime.LockOSThread()
		glfw.SetErrorCallback(errorCallback)

		if !glfw.Init() {
			panic("Can't init glfw!")
		}
		defer glfw.Terminate()

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

		window.MakeContextCurrent()
		gl.Init()
		sgl.Init()
		canv := sgl.NewCanvas(w, h)
		pa := sgl.NewPath().StartAt(sgl.Pt(50, 50))
		pa.QuadraticTo(sgl.Pt(80, 50), sgl.Pt(150, 0))
		pa.QuadraticTo(sgl.Pt(300, 300), sgl.Pt(800, 100))
		pa.QuadraticTo(sgl.Pt(100, 600), sgl.Pt(0, 300))
		pa.BezierTo(sgl.Pt(50, 50), sgl.Pt(-100, 200), sgl.Pt(100, 100))
		for !window.ShouldClose() {
			gl.ClearColor(1, 1, 1, 1)
			gl.Clear(gl.COLOR_BUFFER_BIT)
			pa.DrawFill(canv, sgl.NewPaint().SetFill(color.RGBA{89, 184, 239, 100}))
			//Do OpenGL stuff
			window.SwapBuffers()
			glfw.PollEvents()
			time.Sleep(100 * time.Millisecond)
		}
	})
	m.Main()
}
Example #26
0
File: 09.go Project: nzlov/gogl
func main() {
	glfw.SetErrorCallback(errorCallback)

	if !glfw.Init() {
		panic("Can't init glfw!")
	}
	defer glfw.Terminate()

	glfw.WindowHint(glfw.DepthBits, 16)

	window, err := glfw.CreateWindow(Width, Height, Title, nil, nil)
	if err != nil {
		panic(err)
	}

	window.SetFramebufferSizeCallback(reshape)
	window.SetKeyCallback(key)

	window.MakeContextCurrent()

	glfw.SwapInterval(1000 / 60)

	width, height := window.GetFramebufferSize()
	reshape(window, width, height)

	if err := initGL(); err != nil {
		fmt.Fprintf(os.Stderr, "init: %s\n", err)
		return
	}
	defer destroyGL()

	for !window.ShouldClose() {
		drawScene()
		window.SwapBuffers()
		glfw.PollEvents()
	}
}
Example #27
0
func main() {
	window, err := glfw.CreateWindow(800, 600, "Golang SFML Pong", nil, nil)
	if err != nil {
		panic(err)
	}
	window.MakeContextCurrent()
	window.SetFramebufferSizeCallback(onResize)
	window.SetKeyCallback(onKey)

	target = sf.NewRenderTarget(sf.Vector2{float32(800), float32(600)})

	p1 = NewObject(5, 5, 16, 64)
	p2 = NewObject(795-16, 5, 16, 64)
	ball = NewObject(400-8, 300-8, 16, 16)

	ball.vel = sf.Vector2{300, 300}

	clock := sf.NewClock()
	for !window.ShouldClose() {
		glfw.PollEvents()

		dt := float32(clock.Restart().Seconds())

		if ball.pos.X < 0 {
			ball.vel.X = 300
			p2Score++
			fmt.Println("Player 1: ", p1Score)
			fmt.Println("Player 2: ", p2Score)
			fmt.Println()
		}
		if ball.pos.X+ball.dim.X >= 800 {
			ball.vel.X = -300
			p1Score++
			fmt.Println("Player 1: ", p1Score)
			fmt.Println("Player 2: ", p2Score)
			fmt.Println()
		}
		if ball.pos.Y < 0 {
			ball.vel.Y = 300
		}
		if ball.pos.Y+ball.dim.Y >= 600 {
			ball.vel.Y = -300
		}

		if p1.Collision(ball) {
			ball.vel.X = 300
		}
		if p2.Collision(ball) {
			ball.vel.X = -300
		}

		p1.pos.X += p1.vel.X * dt
		p1.pos.Y += p1.vel.Y * dt
		p2.pos.X += p2.vel.X * dt
		p2.pos.Y += p2.vel.Y * dt
		ball.pos.X += ball.vel.X * dt
		ball.pos.Y += ball.vel.Y * dt

		// Render
		target.Clear(sf.Color{0, 0, 0, 0})
		p1.Render()
		p2.Render()
		ball.Render()
		window.SwapBuffers()
	}
}
Example #28
0
func main() {
	runtime.LockOSThread()

	if !glfw.Init() {
		fmt.Fprintf(os.Stderr, "Can't open GLFW")
		return
	}
	defer glfw.Terminate()

	glfw.WindowHint(glfw.Samples, 4)
	glfw.WindowHint(glfw.ContextVersionMajor, 3)
	glfw.WindowHint(glfw.ContextVersionMinor, 3)
	glfw.WindowHint(glfw.OpenglProfile, glfw.OpenglCoreProfile)
	glfw.WindowHint(glfw.OpenglForwardCompatible, glfw.True) // needed for macs

	window, err := glfw.CreateWindow(1024, 768, "Tutorial 6", nil, nil)
	if err != nil {
		fmt.Fprintf(os.Stderr, "%v\n", err)
		return
	}

	window.MakeContextCurrent()

	gl.Init()
	gl.GetError() // Ignore error
	window.SetInputMode(glfw.StickyKeys, 1)
	window.SetCursorPosition(1024/2, 768/2)
	window.SetInputMode(glfw.Cursor, glfw.CursorHidden)

	gl.ClearColor(0., 0., 0.4, 0.)

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

	gl.Enable(gl.CULL_FACE)

	camera := input.NewCamera(window)

	vertexArray := gl.GenVertexArray()
	defer vertexArray.Delete()
	vertexArray.Bind()

	prog := helper.MakeProgram("TransformVertexShader.vertexshader", "TextureFragmentShader.fragmentshader")
	defer prog.Delete()

	matrixID := prog.GetUniformLocation("MVP")

	texture, err := helper.TextureFromDDS("uvtemplate.DDS")
	if err != nil {
		fmt.Printf("Couldn't make texture: %v\n", err)
		return
	}
	defer texture.Delete()
	texSampler := prog.GetUniformLocation("myTextureSampler")

	vBufferData := [...]float32{
		-1.0, -1.0, -1.0,
		-1.0, -1.0, 1.0,
		-1.0, 1.0, 1.0,
		1.0, 1.0, -1.0,
		-1.0, -1.0, -1.0,
		-1.0, 1.0, -1.0,
		1.0, -1.0, 1.0,
		-1.0, -1.0, -1.0,
		1.0, -1.0, -1.0,
		1.0, 1.0, -1.0,
		1.0, -1.0, -1.0,
		-1.0, -1.0, -1.0,
		-1.0, -1.0, -1.0,
		-1.0, 1.0, 1.0,
		-1.0, 1.0, -1.0,
		1.0, -1.0, 1.0,
		-1.0, -1.0, 1.0,
		-1.0, -1.0, -1.0,
		-1.0, 1.0, 1.0,
		-1.0, -1.0, 1.0,
		1.0, -1.0, 1.0,
		1.0, 1.0, 1.0,
		1.0, -1.0, -1.0,
		1.0, 1.0, -1.0,
		1.0, -1.0, -1.0,
		1.0, 1.0, 1.0,
		1.0, -1.0, 1.0,
		1.0, 1.0, 1.0,
		1.0, 1.0, -1.0,
		-1.0, 1.0, -1.0,
		1.0, 1.0, 1.0,
		-1.0, 1.0, -1.0,
		-1.0, 1.0, 1.0,
		1.0, 1.0, 1.0,
		-1.0, 1.0, 1.0,
		1.0, -1.0, 1.0,
	}

	uvBufferData := [...]float32{
		0.000059, 1.0 - 0.000004,
		0.000103, 1.0 - 0.336048,
		0.335973, 1.0 - 0.335903,
		1.000023, 1.0 - 0.000013,
		0.667979, 1.0 - 0.335851,
		0.999958, 1.0 - 0.336064,
		0.667979, 1.0 - 0.335851,
		0.336024, 1.0 - 0.671877,
		0.667969, 1.0 - 0.671889,
		1.000023, 1.0 - 0.000013,
		0.668104, 1.0 - 0.000013,
		0.667979, 1.0 - 0.335851,
		0.000059, 1.0 - 0.000004,
		0.335973, 1.0 - 0.335903,
		0.336098, 1.0 - 0.000071,
		0.667979, 1.0 - 0.335851,
		0.335973, 1.0 - 0.335903,
		0.336024, 1.0 - 0.671877,
		1.000004, 1.0 - 0.671847,
		0.999958, 1.0 - 0.336064,
		0.667979, 1.0 - 0.335851,
		0.668104, 1.0 - 0.000013,
		0.335973, 1.0 - 0.335903,
		0.667979, 1.0 - 0.335851,
		0.335973, 1.0 - 0.335903,
		0.668104, 1.0 - 0.000013,
		0.336098, 1.0 - 0.000071,
		0.000103, 1.0 - 0.336048,
		0.000004, 1.0 - 0.671870,
		0.336024, 1.0 - 0.671877,
		0.000103, 1.0 - 0.336048,
		0.336024, 1.0 - 0.671877,
		0.335973, 1.0 - 0.335903,
		0.667969, 1.0 - 0.671889,
		1.000004, 1.0 - 0.671847,
		0.667979, 1.0 - 0.335851,
	}

	// Invert V because we're using a compressed texture
	for i := 1; i < len(uvBufferData); i += 2 {
		uvBufferData[i] = 1.0 - uvBufferData[i]
	}

	vertexBuffer := gl.GenBuffer()
	defer vertexBuffer.Delete()
	vertexBuffer.Bind(gl.ARRAY_BUFFER)
	gl.BufferData(gl.ARRAY_BUFFER, len(vBufferData)*4, &vBufferData, gl.STATIC_DRAW)

	uvBuffer := gl.GenBuffer()
	defer uvBuffer.Delete()
	uvBuffer.Bind(gl.ARRAY_BUFFER)
	gl.BufferData(gl.ARRAY_BUFFER, len(uvBufferData)*4, &uvBufferData, gl.STATIC_DRAW)

	// Equivalent to a do... while
	for ok := true; ok; ok = (window.GetKey(glfw.KeyEscape) != glfw.Press && !window.ShouldClose()) {
		func() {
			gl.Clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT)

			prog.Use()
			defer gl.ProgramUnuse()

			view, proj := camera.ComputeViewPerspective()
			model := mgl32.Ident4()

			MVP := proj.Mul4(view).Mul4(model)
			//mvpArray := mvp.AsCMOArray(mathgl.FLOAT32).([16]float32)

			matrixID.UniformMatrix4fv(false, MVP)

			gl.ActiveTexture(gl.TEXTURE0)
			texture.Bind(gl.TEXTURE_2D)
			defer texture.Unbind(gl.TEXTURE_2D)
			texSampler.Uniform1i(0)

			vertexAttrib := gl.AttribLocation(0)
			vertexAttrib.EnableArray()
			defer vertexAttrib.DisableArray()
			vertexBuffer.Bind(gl.ARRAY_BUFFER)
			defer vertexBuffer.Unbind(gl.ARRAY_BUFFER)
			vertexAttrib.AttribPointer(3, gl.FLOAT, false, 0, nil)

			uvAttrib := gl.AttribLocation(1)
			uvAttrib.EnableArray()
			defer uvAttrib.DisableArray()
			uvBuffer.Bind(gl.ARRAY_BUFFER)
			defer uvBuffer.Unbind(gl.ARRAY_BUFFER)
			uvAttrib.AttribPointer(2, gl.FLOAT, false, 0, nil)

			gl.DrawArrays(gl.TRIANGLES, 0, 12*3)

			window.SwapBuffers()
			glfw.PollEvents()
		}() // Defers unbinds and disables to here, end of the loop
	}

}
Example #29
0
func main() {
	f, err := os.Create("Go.pprof") // Create file for profiling
	if err != nil {
		panic(err)
	}

	glfw.SetErrorCallback(errorCallback)
	if !glfw.Init() {
		panic("Can't init glfw!")
	}
	defer glfw.Terminate()
	glfw.WindowHint(glfw.Samples, 2)
	glfw.WindowHint(glfw.ContextVersionMajor, 2)
	glfw.WindowHint(glfw.ContextVersionMinor, 1)
	window, err := glfw.CreateWindow(Width, Height, Title, nil, nil)
	if err != nil {
		panic(err)
	}
	window.MakeContextCurrent()

	glfw.SwapInterval(0) // No limit on FPS
	gl.Init()
	initScene()
	loadCubeToGPU()
	for !window.ShouldClose() {
		frameInitT = time.Now()
		movPts(frameDur)
		doWind()
		if spwnTmr >= SpawnInterval {
			spwnPts(SpawnInterval)
			spwnTmr -= SpawnInterval
		}
		if cleanupTmr >= float64(MaxLife)/1000 {
			cleanupPtPool()
			cleanupTmr = 0
		}
		checkColls()
		gl.Clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT)

		gpuInitT = time.Now()
		renderPts()
		window.SwapBuffers()
		gpuEndT = time.Now()
		glfw.PollEvents()

		frameEndT = time.Now()
		frameDur = frameEndT.Sub(frameInitT).Seconds() // Calculate the length of the previous frame
		spwnTmr += frameDur
		cleanupTmr += frameDur
		runTmr += frameDur
		if runTmr > MaxLife/1000 { // Start collecting framerate data and profiling after a full MaxLife worth of particles have been spawned
			frames[curFrame] = frameDur
			gpuTimes[curFrame] = gpuEndT.Sub(gpuInitT).Seconds()
			curFrame += 1
			pprof.StartCPUProfile(f)
		}
		if runTmr >= RunningTime { // Animation complete; calculate framerate mean and standard deviation
			pprof.StopCPUProfile()
			var sum float64
			var i uint64
			for i = 0; i < curFrame; i++ {
				sum += frames[i]
			}
			frameTimeMean := sum / float64(curFrame)
			fmt.Println("Average framerate was:", 1/frameTimeMean, "frames per second.")

			sum = 0
			for i = 0; i < curFrame; i++ {
				sum += gpuTimes[i]
			}
			gpuTimeMean := sum / float64(curFrame)
			fmt.Println("Average cpu time was-", frameTimeMean-gpuTimeMean, "seconds per frame.")

			sumDiffs := 0.0
			for i = 0; i < curFrame; i++ {
				sumDiffs += math.Pow(1/frames[i]-1/frameTimeMean, 2)
			}
			variance := sumDiffs / float64(curFrame)
			sd := math.Sqrt(variance)
			fmt.Println("The standard deviation was:", sd, "frames per second.")
			if PrintFrames == true {
				fmt.Print("--:")
				for i = 0; i < curFrame; i++ {
					fmt.Print(1 / frames[i])
					fmt.Print(",")
				}
				fmt.Print(".--")
			}
			break
		}

	}
	gl.DisableClientState(gl.NORMAL_ARRAY)
	gl.DisableClientState(gl.VERTEX_ARRAY)
}
Example #30
0
// Swap swaps buffers and polls events.
func (w *Window) Swap() {
	w.window.SwapBuffers()
	glfw.PollEvents()
}