func (s *Sim) Run() {
	for s.ui.running {

		start := time.Now()

		for e := sdl.PollEvent(); e != nil; e = sdl.PollEvent() {
			switch ev := e.(type) {
			case *sdl.QuitEvent:
				s.ui.running = false
			case *sdl.KeyboardEvent:
				if ev.Keysym.Sym == sdl.K_ESCAPE {
					s.ui.running = false
				} else if ev.Keysym.Sym == sdl.K_SPACE {
					if !s.running {
						s.running = true
						go s.Update()
					}
				}
			}
		}

		s.Draw()

		sdl.GL_SwapBuffers()

		fps := 1 / (float64(time.Since(start)) / float64(time.Second))
		_ = fps
		//fmt.Printf("%f\n", fps)
	}
}
Example #2
0
func HandleEvents() {
	ch := make(chan func(), 10)

	for Running {
		for ev := sdl.PollEvent(); ev != nil; ev = sdl.PollEvent() {
			switch e := ev.(type) {
			case *sdl.QuitEvent:
				Running = false
			case *sdl.MouseButtonEvent:
				if e.State == 1 {
					x, y := int(e.X), int(e.Y)
					switch e.Button {
					case 1:
						queue(ch, func() { ToggleCell(x/Scale, y/Scale) })
					case 2:
						queue(ch, func() { AddAcorn(x/Scale, y/Scale) })
					case 3:
						queue(ch, func() { AddGlider(x/Scale, y/Scale) })
					}
				}
			case *sdl.KeyboardEvent:
				if e.State == 1 {
					switch e.Keysym.Sym {
					case sdl.K_ESCAPE:
						Running = false
					case sdl.K_SPACE, sdl.K_p:
						TogglePause(ch)
					}
				}
			}
		}

		sdl.Delay(25)
	}
}
Example #3
0
func (world *World) HandleEvents() {
	for world.running {
		for ev := sdl.PollEvent(); ev != nil; ev = sdl.PollEvent() {
			switch e := ev.(type) {
			case *sdl.QuitEvent:
				world.running = false
			case *sdl.KeyboardEvent:
				switch sdl.GetKeyName(sdl.Key(e.Keysym.Sym)) {
				case "p":
					world.pause = !world.pause
				case "j":
					world.Paddle.Go(0, world.Paddle.vector.Y+world.Paddle.speed)
				case "k":
					world.Paddle.Go(0, world.Paddle.vector.Y-world.Paddle.speed)
				case "q":
					world.running = false
				}
			case *sdl.MouseMotionEvent:
				world.Paddle.Go(float64(e.X), float64(e.Y))
			}
		}

		sdl.Delay(25)
	}
}
Example #4
0
func gameOverScreen(
	screen *sdl.Surface,
	score string,
	bg *glh.Texture,
	font *gltext.Font) bool {

	for {
		gl.Clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT)
		for e := sdl.PollEvent(); e != nil; e = sdl.PollEvent() {
			switch e.(type) {
			case *sdl.ResizeEvent:
				resize(screen, e.(*sdl.ResizeEvent))
			case *sdl.QuitEvent:
				return true
			case *sdl.MouseButtonEvent:
				return false
			}
		}
		renderBackground(screen, bg)
		font.Printf(110, 50, "Game Over")
		font.Printf(110, 100, "Your score: "+score)
		font.Printf(110, 150, "Click to play again")
		sdl.GL_SwapBuffers()
		time.Sleep((1 / 30) * time.Second)
	}
	return false
}
func main() {
	if sdl.Init(sdl.INIT_VIDEO) < 0 {
		panic("Video initialization failed: " + sdl.GetError())
	}

	if sdl.EnableKeyRepeat(100, 25) != 0 {
		panic("Setting keyboard repeat failed: " + sdl.GetError())
	}

	videoFlags := sdl.OPENGL    // Enable OpenGL in SDL
	videoFlags |= sdl.DOUBLEBUF // Enable double buffering
	videoFlags |= sdl.HWPALETTE // Store the palette in hardware
	// FIXME: this causes segfault.
	// videoFlags |= sdl.RESIZABLE // Enable window resizing

	surface = sdl.SetVideoMode(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_BPP, uint32(videoFlags))

	if surface == nil {
		panic("Video mode set failed: " + sdl.GetError())
	}

	sdl.GL_SetAttribute(sdl.GL_DOUBLEBUFFER, 1)
	initGL()
	resizeWindow(SCREEN_WIDTH, SCREEN_HEIGHT)

	SetupWorld("data/world.txt")

	// wait for events
	running := true
	isActive := true
	for running {
		for ev := sdl.PollEvent(); ev != nil; ev = sdl.PollEvent() {
			switch e := ev.(type) {
			case *sdl.ActiveEvent:
				isActive = e.Gain != 0
			case *sdl.ResizeEvent:
				width, height := int(e.W), int(e.H)
				surface = sdl.SetVideoMode(width, height, SCREEN_BPP, uint32(videoFlags))
				if surface == nil {
					fmt.Println("Could not get a surface after resize:", sdl.GetError())
					Quit(1)
				}
				resizeWindow(width, height)
			case *sdl.KeyboardEvent:
				if e.Type == sdl.KEYDOWN {
					handleKeyPress(e.Keysym)
				}
			case *sdl.QuitEvent:
				running = false
			}
		}

		// draw the scene
		if isActive {
			drawGLScene(sector1)
		}
	}
}
Example #6
0
// Wrap the SDL into one single thread
func (s SdlWrap) wrap() {
	runtime.LockOSThread()

	if sdl.Init(sdl.INIT_EVERYTHING) != 0 {
		panic("Unable to init SDL. Cause: " + sdl.GetError())
	}
	sdl.EnableUNICODE(1)

	s.InitDone <- struct{}{}

	for {
		select {
		case t := <-s.Title:
			sdl.WM_SetCaption(t, t)
		case <-s.Quit:
			close(s.Events)
			sdl.Quit()
		case sz := <-s.Size:
			s.Surface <- sdl.SetVideoMode(int(sz.X), int(sz.Y), 32, sdl.HWSURFACE|sdl.DOUBLEBUF|sdl.RESIZABLE)
		default:
			e := sdl.PollEvent()
			if e != nil {
				s.Events <- e
			}
		}
	}
}
Example #7
0
func eventLoop(mouseC chan Point) {
	var p Point
EVENTLOOP:
	switch e := sdl.PollEvent().(type) {
	case *sdl.MouseButtonEvent:
		if e.Type == sdl.MOUSEBUTTONDOWN {
			p.X, p.Y = uint(e.X), uint(e.Y)
			mouseC <- p
		}
	case *sdl.KeyboardEvent:
		if e.State == 0 {
			break
		}

		keysym := e.Keysym.Sym
		if keysym == sdl.K_q {
			os.Exit(0)
		}
	case *sdl.QuitEvent:
		os.Exit(0)
	}

	runtime.Gosched()
	goto EVENTLOOP

}
Example #8
0
func (this *Listener) Update() {
	for e := sdl.PollEvent(); e != nil; e = sdl.PollEvent() {
		switch e.(type) {
		case *sdl.QuitEvent:
			this.quit = true
			break
		case *sdl.KeyboardEvent:
			ke := e.(*sdl.KeyboardEvent)
			if ke.Type == sdl.KEYDOWN {
				this.keys[ke.Keysym.Sym] = keyPressed
			} else if ke.Type == sdl.KEYUP {
				this.keys[ke.Keysym.Sym] = keyUp
			}
		}
	}
}
Example #9
0
func manageEvents(screen *sdl.Surface, movingUp *bool) bool {
	for e := sdl.PollEvent(); e != nil; e = sdl.PollEvent() {
		switch e.(type) {
		case *sdl.ResizeEvent:
			re := e.(*sdl.ResizeEvent)
			resize(screen, re)
			return false

		case *sdl.MouseButtonEvent:
			*movingUp = !*movingUp
			return false
		case *sdl.QuitEvent:
			return true
		}
	}
	return false
}
Example #10
0
func (win *window) eventLoop() {
	if win.ec == nil {
		win.ec = make(chan interface{})
	}

eloop:
	for win.events {
		for ev := sdl.PollEvent(); ev != nil; ev = sdl.PollEvent() {
			switch e := ev.(type) {
			case *sdl.KeyboardEvent:
				switch e.Type {
				case sdl.KEYUP:
					win.ec <- gui.KeyEvent{int(-e.Keysym.Sym)}
				case sdl.KEYDOWN:
					win.ec <- gui.KeyEvent{int(e.Keysym.Sym)}
				}
			case *sdl.MouseMotionEvent:
				win.ec <- gui.MouseEvent{
					Buttons: int(e.State),
					Loc:     image.Pt(int(e.X), int(e.Y)),
					Nsec:    time.Nanoseconds(),
				}
			case *sdl.MouseButtonEvent:
				win.ec <- gui.MouseEvent{
					Buttons: int(sdl.GetMouseState(nil, nil)),
					Loc:     image.Pt(int(e.X), int(e.Y)),
					Nsec:    time.Nanoseconds(),
				}
			case *sdl.ResizeEvent:
				win.ec <- gui.ConfigEvent{image.Config{
					win.Screen().ColorModel(),
					int(e.W),
					int(e.H),
				}}
			case *sdl.QuitEvent:
				break eloop
			}
		}
	}

	close(win.ec)
}
Example #11
0
func main() {
	var done bool

	sdl.Init(sdl.INIT_VIDEO)

	var screen = sdl.SetVideoMode(300, 300, 18, sdl.OPENGL|sdl.RESIZABLE)

	if screen == nil {
		sdl.Quit()
		panic("Couldn't set 300x300 GL video mode: " + sdl.GetError() + "\n")
	}
	gl.Init()
	//if gl.Init() != nil {
	//panic("gl error")
	//}
	init_()
	reshape(int32(screen.W), int32(screen.H))
	done = false
	for !done {
		for e := sdl.PollEvent(); e != nil; e = sdl.PollEvent() {
			switch e.(type) {
			case *sdl.ResizeEvent:
				re := e.(*sdl.ResizeEvent)
				screen = sdl.SetVideoMode(int(re.W), int(re.H), 16,
					sdl.OPENGL|sdl.RESIZABLE)
				if screen != nil {
					reshape(int32(screen.W), int32(screen.H))
				} else {
					panic("we couldn't set the new video mode??")
				}
				break
			case *sdl.QuitEvent:
				done = true
				break
			}
		}
		done = key_handler()
		draw()
	}
	sdl.Quit()
	return
}
Example #12
0
func loop(screen *sdl.Surface) {
	for {
		screen.Flip()
		event := sdl.PollEvent()
		if event != nil {
			if _, ok := event.(*sdl.QuitEvent); ok {
				log.Println("Caught quit event. Quiting SDL.")
				break
			}
		}
	}
}
Example #13
0
func eventLoop(c *Screen) {
EVENTLOOP:
	/* log.Printf("%#v\n", event) */
	switch e := sdl.PollEvent().(type) {
	case *sdl.QuitEvent:
		os.Exit(0)

	case *sdl.ResizeEvent:
		if opt.fullscreen {
			break
		}
		if err := c.setSurface(int(e.W), int(e.H)); err != nil {
			log.Fatal(err)
		}
		c.updateC <- 1

	case *sdl.KeyboardEvent:
		// Ignore key-up
		if e.State == 0 {
			break
		}

		keysym := e.Keysym.Sym
		if keysym == sdl.K_q {
			quitC <- true
			break
		}

		// tune timestamp
		if v, ok := kmVias[keysym]; ok {
			tsViasC <- v
			break
		}
		// tune font size
		if v, ok := kmFontSize[keysym]; ok {
			c.changeFontSize(v)
			break
		}

		// pause/resume
		if v, ok := kmNavScript[keysym]; ok {
			navC <- v
			break
		}
		log.Printf("Sim:%08x, Mod:%04x, Unicode:%02x, %t\n",
			e.Keysym.Sym, e.Keysym.Mod, e.Keysym.Unicode,
			e.Keysym.Unicode)
	} // end of switch

	runtime.Gosched()
	goto EVENTLOOP
}
Example #14
0
func main() {
	if sdl.Init(sdl.INIT_EVERYTHING) != 0 {
		panic(sdl.GetError())
	}

	if ttf.Init() != 0 {
		panic(sdl.GetError())
	}

	var screen = sdl.SetVideoMode(1400, 300, 32, 0)
	var video_info = sdl.GetVideoInfo()
	println("HW_available = ", video_info.HW_available)
	println("WM_available = ", video_info.WM_available)
	println("Video_mem = ", video_info.Video_mem, "kb")
	sdl.EnableUNICODE(1)

	font := ttf.OpenFont("euler.otf", 24)

	if font == nil {
		panic(sdl.GetError())
	}

	black := sdl.Color{0, 0, 0, 0}
	text := ttf.RenderUTF8_Blended(font, "!!", black)
	fmt.Println(text.Bounds())
	sdl.WM_SetCaption("Go-SDL SDL Test", "")
	running := true
	num := NewNumberShower("b+c", "", "euler.otf", 24, 0)
	denom := NewNumberShower("a", "", "euler.otf", 24, 0)
	testy := NewFractionShower(num, denom, "euler.otf", 24, 0)
	testy.CursorPosition = 3
	testy.RenderEmptyIndextxt = true
	str := ""
	for running {
		switch e := sdl.PollEvent().(type) {
		case *sdl.QuitEvent:
			running = false
			break
		case *sdl.KeyboardEvent:

			if e.State == 1 {
				str = handlekeypress2(e.Keysym, str)
				fmt.Println("rendering string", str)
				text = ttf.RenderUTF8_Blended(font, str, black)
			}
		}
		screen.FillRect(nil, 0xFFFFFF)
		screen.Blit(&sdl.Rect{23, 0, 0, 0}, testy.Render(), nil)
		screen.Flip()
		sdl.Delay(5)
	}
}
Example #15
0
func handleInput() {
	for e := sdl.PollEvent(); e != nil; {
		// just ignore for the moment
	}
	if globalState.speed < 1 {
		globalState.speed = 1
	}
	if speed < 0.5 {
		speed = 0.5
	} else if speed > 2 {
		speed = 2
	}
}
func ui_main() {

	if sdl.Init(sdl.INIT_VIDEO) != 0 {
		panic(sdl.GetError())
	}

	if screen == nil {
		panic(sdl.GetError())
	}

	sdl.EnableUNICODE(1)

	sdl.WM_SetCaption("Go-SDL SDL Test", "")

	running := true

	for running {
		for ev := sdl.PollEvent(); ev != nil; ev = sdl.PollEvent() {
			switch e := ev.(type) {
			case *sdl.QuitEvent:
				running = false
				break

			case *sdl.ResizeEvent:
				println("resize screen ", e.W, e.H)

				screen = sdl.SetVideoMode(int(e.W), int(e.H), 32, sdl.RESIZABLE)

				if screen == nil {
					panic(sdl.GetError())
				}
			}
		}

	}

	ttf.Quit()
	sdl.Quit()
}
Example #17
0
File: main.go Project: shogg/glvox
func mainLoop() {
	done := false
	for !done {
		for e := sdl.PollEvent(); e != nil; e = sdl.PollEvent() {
			switch e.(type) {
			case *sdl.QuitEvent:
				done = true
				break
			case *sdl.KeyboardEvent:
				keyEvent := e.(*sdl.KeyboardEvent)
				if keyEvent.Type == sdl.KEYDOWN {
					done = handleKey(keyEvent)
				}
			}
		}

		updateShaderParams()
		draw()
		drawOverlay()
		sdl.GL_SwapBuffers()
		checkShaders()
	}
}
Example #18
0
// Runs the games main loop.
func (g *game) main() (err error) {
	g.running = true

	for g.running {
		for e := sdl.PollEvent(); e != nil; e = sdl.PollEvent() {
			switch ev := e.(type) {
			case *sdl.KeyboardEvent:
				err = g.onKeyboardEvent(ev)
				if err != nil {
					return
				}
			case *sdl.MouseMotionEvent:
				err = g.onMouseMotionEvent(ev)
				if err != nil {
					return
				}
			case *sdl.MouseButtonEvent:
				err = g.onMouseButtonEvent(ev)
				if err != nil {
					return
				}
			case *sdl.QuitEvent:
				g.running = false
			}
		}

		g.screen.FillRect(nil, 0)
		err = g.draw()
		if err != nil {
			return
		}
		g.screen.Flip()
	}

	return
}
Example #19
0
File: gltoy.go Project: shogg/gltoy
func mainLoop() {
	done := false
	for !done {
		for e := sdl.PollEvent(); e != nil; e = sdl.PollEvent() {
			switch e.(type) {
			case *sdl.QuitEvent:
				done = true
				break
			case *sdl.KeyboardEvent:
				key := e.(*sdl.KeyboardEvent).Keysym.Sym
				if key == sdl.K_RETURN {
					done = true
					break
				} else {
					handleKey(key)
				}
			}
		}

		draw()
		drawOverlay()
		sdl.GL_SwapBuffers()
	}
}
Example #20
0
func main() {
	if sdl.Init(sdl.INIT_EVERYTHING) != 0 {
		panic(sdl.GetError())
	}

	// The actual resolution (screenspace)
	W := 800
	H := 600

	// The virtual resolution (worldspace)
	MAXX := 400
	MAXY := 300

	screen := sdl.SetVideoMode(W, H, 32, sdl.FULLSCREEN)
	if screen == nil {
		panic(sdl.GetError())
	}
	sdl.EnableUNICODE(1)
	sdl.ShowCursor(0)

	sdl.WM_SetCaption("Random Lines", "")

	red := sdl.Color{255, 0, 0, 255}
	color := red

	rand.Seed(time.Now().UnixNano())

	for {
		color = sdl.Color{uint8(rand.Intn(255)), uint8(rand.Intn(255)), uint8(rand.Intn(255)), 255}
		DoublePixelLine(screen, rand.Intn(MAXX), rand.Intn(MAXY), rand.Intn(MAXX), rand.Intn(MAXY), color)
		if escPressed() {
			break
		}
		screen.Flip()
		sdl.PollEvent()
		//sdl.Delay(10)
	}

	sdl.Quit()
}
Example #21
0
func (self *AppStateManager) HandleEvents() (done bool) {
	done = false

	running_state := self.GetRunningState()

	for event := sdl.PollEvent(); event != nil; event = sdl.PollEvent() {
		switch event.(type) {
		case *sdl.QuitEvent:
			done = true
			break
		case *sdl.ResizeEvent:
			re := event.(*sdl.ResizeEvent)
			self.Screen = sdl.SetVideoMode(int(re.W), int(re.H), 16,
				sdl.OPENGL|sdl.RESIZABLE)
			if self.Screen != nil {
				GetViewport().SetScreenSize(float32(self.Screen.W), float32(self.Screen.H))

				if running_state != nil {
					running_state.OnViewportResize(float32(self.Screen.W), float32(self.Screen.H))
				}

			} else {
				panic("we couldn't set the new video mode??")
			}
			break

		case *sdl.KeyboardEvent:
			if running_state != nil {
				kevent := event.(*sdl.KeyboardEvent)
				if kevent.State == 1 {
					running_state.OnKeyDown(&kevent.Keysym)
				} else {
					running_state.OnKeyUp(&kevent.Keysym)
				}
			}
			break
		case *sdl.MouseMotionEvent:
			if running_state != nil {
				mevent := event.(*sdl.MouseMotionEvent)
				dx, dy := float32(0), float32(0)
				fx, fy := float32(mevent.X), float32(mevent.Y)

				if self.MouseSampleTaken {
					dx = fx - self.LastMouseX
					dy = fy - self.LastMouseY
				} else {
					self.MouseSampleTaken = true
				}

				running_state.OnMouseMove(
					float32(mevent.X),
					float32(mevent.Y), dx, dy)

				if self.FPSMouseModeEnabled {
					sdl.EventState(sdl.MOUSEMOTION, sdl.IGNORE)
					sdl.WarpMouse(int(self.Screen.W/2), int(self.Screen.H/2))
					sdl.EventState(sdl.MOUSEMOTION, sdl.ENABLE)
					self.LastMouseX = float32(self.Screen.W / 2)
					self.LastMouseY = float32(self.Screen.H / 2)
				} else {
					self.LastMouseX = fx
					self.LastMouseY = fy
				}
			}
			break
		case *sdl.MouseButtonEvent:
			if running_state != nil {
				mevent := event.(*sdl.MouseButtonEvent)
				running_state.OnMouseClick(float32(mevent.X),
					float32(mevent.Y),
					int(mevent.Button),
					mevent.State == 1)
			}
			break
		default:
			if running_state != nil {
				running_state.OnSdlEvent(&event)
			}
			break
		}
	}
	return
}
Example #22
0
func main() {
	if sdl.Init(sdl.INIT_EVERYTHING) != 0 {
		panic(sdl.GetError())
	}
	defer sdl.Quit()

	image0 := sdl.Load(*file)
	if image0 == nil {
		panic(sdl.GetError())
	}

	factorx := float32(1)
	factory := float32(1)

	dstW := uint32(float32(image0.W) * factorx)
	dstH := uint32(float32(image0.H) * factory)

	screen := sdl.SetVideoMode(int(dstW), int(dstH), 32, sdl.DOUBLEBUF)

	if screen == nil {
		panic(sdl.GetError())
	}

	image := sdl.DisplayFormat(image0)
	format := image.Format

	err := initAndPrepCL()
	check(err)

	order := cl.RGBA
	elemSize := 4

	src, err := c.NewImage2D(cl.MEM_READ_ONLY|cl.MEM_USE_HOST_PTR, order, cl.UNSIGNED_INT8,
		uint32(image.W), uint32(image.H), uint32(image.Pitch), image.Pixels)
	check(err)

	dst, err := c.NewImage2D(cl.MEM_WRITE_ONLY, order, cl.UNSIGNED_INT8,
		dstW, dstH, 0, nil)
	check(err)

	angle := float32(0)
	for running := true; running; angle += 0.001 {
		for e := sdl.PollEvent(); e != nil; e = sdl.PollEvent() {
			switch ev := e.(type) {
			case *sdl.QuitEvent:
				running = false
				break
			case *sdl.KeyboardEvent:
				if ev.Keysym.Sym == sdl.K_ESCAPE {
					running = false
					break
				}
			}
		}

		//pixels, err := imageCall(dstW, dstH, "image_recscale", src, dst, 1/factorx, 1/factory)

		//pixels, err := imageCall(dstW, dstH, "image_rotate", src, dst, angle)
		m := mul(S(1.2, 1.2), R(angle))
		off := []float32{float32(dstW / 2), float32(dstH / 2)}
		pixels, err := imageCall(dstW, dstH, "image_affine2", src, dst,
			[]float32(m[0:2]), []float32(m[2:4]),
			off, off)
		check(err)

		news := sdl.CreateRGBSurfaceFrom(pixels,
			int(dstW), int(dstH), int(elemSize*8), int(elemSize)*int(dstW),
			format.Rmask, format.Gmask, format.Bmask, format.Amask,
		)

		if news == nil {
			log.Fatal(sdl.GetError())
		}

		screen.FillRect(nil, 0)
		screen.Blit(&sdl.Rect{0, 0, 0, 0}, news, nil)
		screen.Flip()
		sdl.Delay(25)
	}
}
Example #23
0
func main() {
	if sdl.Init(sdl.INIT_VIDEO) != 0 {
		panic(sdl.GetError())
	}

	v_info := sdl.GetVideoInfo()

	var screen = sdl.SetVideoMode(
		int(v_info.Current_w),
		int(v_info.Current_h),
		32,
		sdl.HWSURFACE|sdl.DOUBLEBUF)

	rows = v_info.Current_w / SIZE
	columns = v_info.Current_h / SIZE

	if v_info.Current_w%SIZE != 0 {
		rows += 1
	}

	if v_info.Current_h%SIZE != 0 {
		columns += 1
	}

	// Initialize our world
	world = make([][]Field, rows)
	for i := range world {
		world[i] = make([]Field, columns)
		for j := range world[i] {
			world[i][j].X = i
			world[i][j].Y = j
			world[i][j].T = OPEN
			world[i][j].lsize = 0
			world[i][j].rsize = 0
			world[i][j].o = false
			world[i][j].c = false
		}
	}

	// Once we're done, free screen object and quit sdl.
	defer sdl.Quit()
	defer screen.Free()

	if screen == nil {
		panic(sdl.GetError())
	}

	// Set window title
	sdl.WM_SetCaption("A* algorithm demo", "")

	// Give the screen an initially and update display
	screen.FillRect(nil, OPEN)
	screen.Flip()

	/* Draw the grid on our display */
	drawGrid(screen)

	/* Create the different channels we need */
	paint_chan = make(chan *Paint, 2000)
	read_field = make(chan *Field)
	field_chan = make(chan *Field)

	// Fillbox runs asynchronously, start it here
	go initFillBox(screen)

	// Getneighbours process runs all the time, starts here.
	go GetNeighbours(world, read_field)

	for true {
		for ev := sdl.PollEvent(); ev != nil; ev = sdl.PollEvent() {

			switch e := ev.(type) {
			case *sdl.QuitEvent:
				return
			case *sdl.KeyboardEvent:
				if e.Keysym.Sym == sdl.K_ESCAPE {
					/* Quit when escape is pressed */
					return
				} else if e.Keysym.Sym == sdl.K_r &&
					(e.Keysym.Mod&sdl.KMOD_LCTRL) != 0 &&
					(e.Keysym.Mod&sdl.KMOD_LSHIFT) != 0 {
					resetComplete()
				} else if e.Keysym.Sym == sdl.K_r && (e.Keysym.Mod&sdl.KMOD_LCTRL) != 0 {
					resetAllPaths()
				} else if e.Keysym.Sym == sdl.K_r {
					resetPaths()
				} else if e.Keysym.Sym == sdl.K_RETURN {
					/* If RETURN is pressed, run pathfinding */
					if start != nil && goal != nil {
						//resetPaths();
						go aStar(world, screen)
					}
				}
			case *sdl.MouseMotionEvent:
				if e.State == sdl.BUTTON_LEFT || e.State == sdl.BUTTON_WHEELUP {
					drawMouseMotion(world, screen, e)
				}
			case *sdl.MouseButtonEvent:
				if e.Type == sdl.MOUSEBUTTONDOWN {
					state := sdl.GetKeyState()
					if e.Button == sdl.BUTTON_LEFT {
						r := getRect(e)

						if state[sdl.K_s] == 1 {
							// Left mouse button with s, set new start point
							if start == nil {
								start = &world[int(r.X)/SIZE][int(r.Y)/SIZE]

								fillBox(start, START)
							} else {
								fillBox(start, OPEN)

								start = &world[int(r.X)/SIZE][int(r.Y)/SIZE]
								fillBox(start, START)
							}
						} else if state[sdl.K_g] == 1 {
							// Left mouse button with g, set new goal point
							if goal == nil {
								goal = &world[int(r.X)/SIZE][int(r.Y)/SIZE]

								fillBox(goal, GOAL)
							} else {
								fillBox(goal, OPEN)

								goal = &world[int(r.X)/SIZE][int(r.Y)/SIZE]
								fillBox(goal, GOAL)
							}
						} else {
							// No relevant modifiers were pressed, color the field.
							var f *Field = &world[(r.X / SIZE)][(r.Y / SIZE)]
							//fmt.Println("Click on", f);

							if f.T == OPEN {
								fillBox(f, WALL)
							} else {
								fillBox(f, OPEN)
							}
						}
					}
				}
			default:
			}
		}

		// Delay for 15 milliseconds
		sdl.Delay(30)
		screen.Flip()
	}

	fmt.Println("Exiting")
}
Example #24
0
func main() {
	// Initialize SDL
	if sdl.Init(sdl.INIT_VIDEO) < 0 {
		panic("Video initialization failed: " + sdl.GetError())
	}

	// To avoid cramps
	sdl.EnableKeyRepeat(250, 25)

	// Sets up OpenGL double buffering
	sdl.GL_SetAttribute(sdl.GL_DOUBLEBUFFER, 1)

	// flags to pass to sdl.SetVideoMode
	videoFlags := sdl.OPENGL    // Enable OpenGL in SDL
	videoFlags |= sdl.DOUBLEBUF // Enable double buffering
	videoFlags |= sdl.HWPALETTE // Store the palette in hardware
	// FIXME: this causes segfault.
	// videoFlags |= sdl.RESIZABLE // Enable window resizing

	// get a SDL surface
	surface = sdl.SetVideoMode(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_BPP, uint32(videoFlags))

	// verify there is a surface
	if surface == nil {
		panic("Video mode set failed: " + sdl.GetError())
		Quit(1)
	}

	// When this function is finished, clean up and exit.
	defer Quit(0)

	LoadGLTextures("data/glass.bmp")

	// Initialize OpenGL
	initGL()

	// Resize the initial window
	resizeWindow(SCREEN_WIDTH, SCREEN_HEIGHT)

	// wait for events
	running := true
	isActive := true
	for running {
		for ev := sdl.PollEvent(); ev != nil; ev = sdl.PollEvent() {
			switch e := ev.(type) {
			case *sdl.ActiveEvent:
				isActive = e.Gain != 0
			case *sdl.ResizeEvent:
				width, height := int(e.W), int(e.H)
				surface = sdl.SetVideoMode(width, height, SCREEN_BPP, uint32(videoFlags))
				if surface == nil {
					fmt.Println("Could not get a surface after resize:", sdl.GetError())
					Quit(1)
				}
				resizeWindow(width, height)
			case *sdl.KeyboardEvent:
				if e.Type == sdl.KEYDOWN {
					handleKeyPress(e.Keysym)
				}
			case *sdl.QuitEvent:
				running = false
			}
		}

		// draw the scene
		if isActive {
			drawGLScene()
		}
	}
}
Example #25
0
func gameLoop() {
	var startTime int64 = time.Now().UnixNano()
	var currentTime, accumulator int64 = 0, 0
	var t, dt int64 = 0, 1e9 / 40
	var drawFrame, computeFrame int64 = 0, 0

	update500ms := new(Timer)
	update500ms.interval = 500 * 1e6
	update500ms.Start()

	update150ms := new(Timer)
	update150ms.interval = 50 * 1e6
	update150ms.Start()

	update2000ms := new(Timer)
	update2000ms.interval = 2000 * 1e6
	update2000ms.Start()

	var interactingBlock *InteractingBlockFace

	done := false
	for !done {

		for e := sdl.PollEvent(); e != nil; e = sdl.PollEvent() {
			switch e.(type) {
			case *sdl.QuitEvent:
				done = true
			case *sdl.ResizeEvent:
				re := e.(*sdl.ResizeEvent)
				screen := sdl.SetVideoMode(int(re.W), int(re.H), 16,
					sdl.OPENGL|sdl.RESIZABLE)
				if screen != nil {
					viewport.Reshape(int(screen.W), int(screen.H))
				} else {
					panic("Could not set video mode")
				}
				break

			case *sdl.MouseButtonEvent:
				re := e.(*sdl.MouseButtonEvent)
				if inventory.visible {
					inventory.HandleMouseButton(re)
				} else {
					picker.HandleMouseButton(re)

					if re.Button == 1 && re.State == 1 { // LEFT, DOWN
						if ThePlayer.CanInteract() {
							selectedBlockFace := viewport.SelectedBlockFace()
							if selectedBlockFace != nil {
								if interactingBlock == nil || interactingBlock.blockFace.pos != selectedBlockFace.pos {
									interactingBlock = new(InteractingBlockFace)
									interactingBlock.blockFace = selectedBlockFace
									interactingBlock.hitCount = 0
								}
								ThePlayer.Interact(interactingBlock)
							}
							// println("Click:", re.X, re.Y, re.State, re.Button, re.Which)
						}
					}
				}

			case *sdl.KeyboardEvent:
				re := e.(*sdl.KeyboardEvent)

				if re.Keysym.Sym == sdl.K_ESCAPE {
					if re.Type == sdl.KEYDOWN {
						inventory.visible = false
						if pause.visible {
							pause.visible = false
							update2000ms.Unpause()
							update500ms.Unpause()
							update150ms.Unpause()
						} else {
							pause.visible = true
							update2000ms.Pause()
							update500ms.Pause()
							update150ms.Pause()
						}
					}
				}

				if re.Keysym.Sym == sdl.K_F3 {
					if re.Type == sdl.KEYDOWN {
						if console.visible == true {
							console.visible = false
						} else {
							console.visible = true
						}
					}
				}

				if !pause.visible {
					if re.Keysym.Sym == sdl.K_i {
						if re.Type == sdl.KEYDOWN {
							if inventory.visible == true {
								inventory.visible = false
							} else {
								inventory.visible = true
							}
						}
					}

					if inventory.visible {
						inventory.HandleKeyboard(re)
					}
				}
			}
		}

		keys := sdl.GetKeyState()

		if console.visible {
			console.HandleKeys(keys)
		}

		if pause.visible {
			pause.HandleKeys(keys)
		} else if inventory.visible {
			inventory.HandleKeys(keys)
		} else {
			viewport.HandleKeys(keys)
			ThePlayer.HandleKeys(keys)
			picker.HandleKeys(keys)
		}

		if update150ms.PassedInterval() {

			if !inventory.visible {
				// If player is breaking a block then allow them to hold mouse down to continue action
				if interactingBlock != nil && ThePlayer.currentAction == ACTION_BREAK {
					mouseState := sdl.GetMouseState(nil, nil)
					if mouseState == 1 {
						if ThePlayer.CanInteract() {
							selectedBlockFace := viewport.SelectedBlockFace()
							if selectedBlockFace != nil {
								if interactingBlock == nil || !interactingBlock.blockFace.pos.Equals(&selectedBlockFace.pos) {
									interactingBlock = new(InteractingBlockFace)
									interactingBlock.blockFace = selectedBlockFace
									interactingBlock.hitCount = 0
								}
								ThePlayer.Interact(interactingBlock)
							}
							// println("Click:", re.X, re.Y, re.State, re.Button, re.Which)
						}
					}
				}
			}

			PreloadChunks(50)
			update150ms.Start()
		}

		if update500ms.PassedInterval() {
			console.fps = float64(drawFrame) / (float64(update500ms.GetTicks()) / float64(1e9))
			console.Update()

			UpdateTimeOfDay()
			UpdateCampfires()
			PreloadChunks(220)

			drawFrame, computeFrame = 0, 0
			update500ms.Start()

		}

		if update2000ms.PassedInterval() {
			CullChunks()
			UpdatePlayerStats()
			update2000ms.Start()
		}

		if !pause.visible {
			newTime := time.Now().UnixNano()
			deltaTime := newTime - currentTime
			currentTime = newTime
			if deltaTime > 1e9/4 {
				deltaTime = 1e9 / 4
			}

			accumulator += deltaTime

			for accumulator > dt {
				accumulator -= dt

				TheWorld.ApplyForces(ThePlayer, float64(dt)/1e9)

				ThePlayer.Update(float64(dt) / 1e9)
				TheWorld.Simulate(float64(dt) / 1e9)

				computeFrame++
				t += dt
			}
		}
		//interpolate(previous, current, accumulator/dt)

		Draw(currentTime - startTime)
		drawFrame++
	}

}
Example #26
0
func main() {
	var running bool = true
	var width int = 800
	var height int = 600
	var t float32

	if sdl.Init(sdl.INIT_VIDEO) != 0 {
		panic(sdl.GetError())
	}

	sdl.WM_SetCaption("Horde3d Go SDL Example", "")

	//set sdl video mode
	if sdl.SetVideoMode(width, height, 32, sdl.OPENGL) == nil {
		panic(sdl.GetError())
	}

	if !horde3d.Init() {
		fmt.Println("Error initializing Horde3D")
		horde3d.DumpMessages()
		return
	}

	//horde3d.SetOption(horde3d.Options_DebugViewMode, 1)
	//horde3d.SetOption(horde3d.Options_WireframeMode, 1)
	fmt.Println("Version: ", horde3d.VersionString())

	//pipeline
	pipeRes := horde3d.AddResource(horde3d.ResTypes_Pipeline, "forward.pipeline.xml", 0)
	modelRes := horde3d.AddResource(horde3d.ResTypes_SceneGraph, "platform.scene.xml", 0)

	horde3d.LoadResourcesFromDisk("../content|" +
		"../content/pipelines|" +
		"../content/models|" +
		"../content/materials|" +
		"../content/shaders|" +
		"../content/textures|" +
		"../content/animations|" +
		"../content/particles|" +
		"../content/models/platform|" +
		"../content/effects")

	//add camera
	cam := horde3d.RootNode.AddCameraNode("Camera", pipeRes)
	//Setup Camera Viewport
	cam.SetNodeParamI(horde3d.Camera_ViewportXI, 0)
	cam.SetNodeParamI(horde3d.Camera_ViewportYI, 0)
	cam.SetNodeParamI(horde3d.Camera_ViewportWidthI, width)
	cam.SetNodeParamI(horde3d.Camera_ViewportHeightI, height)

	//add model
	model := horde3d.RootNode.AddNodes(modelRes)
	model.SetTransform(0, -30, -150, 0, 0, 0, 1, 1, 1)
	//add light
	light := horde3d.RootNode.AddLightNode("Light1", 0, "LIGHTING", "SHADOWMAP")
	light.SetTransform(0, 20, 0, 0, 0, 0, 1, 1, 1)
	light.SetNodeParamF(horde3d.Light_RadiusF, 0, 150)
	light.SetNodeParamF(horde3d.Light_FovF, 0, 90)
	//horde3d.SetNodeParamI(light, horde3d.Light_ShadowMapCountI, 3)
	light.SetNodeParamF(horde3d.Light_ShadowSplitLambdaF, 0, 0.9)
	//horde3d.SetNodeParamF(light, horde3d.Light_ShadowMapBiasF, 0, 0.001)
	light.SetNodeParamF(horde3d.Light_ColorF3, 0, 1.9)
	light.SetNodeParamF(horde3d.Light_ColorF3, 1, 1.7)
	light.SetNodeParamF(horde3d.Light_ColorF3, 2, 1.75)

	for running {
		t = 0
		//increase anim time
		t = t + 10.0*(1/60)
		//process SDL events / input
		switch event := sdl.PollEvent(); event.(type) {
		case *sdl.QuitEvent:
			running = false
			break
		}
		//horde3d.SetNodeTransform(model,
		//t*10, 0, 0,
		//0, 0, 0,
		//1, 1, 1)
		horde3d.Render(cam)
		horde3d.FinalizeFrame()
		horde3d.DumpMessages()
		sdl.GL_SwapBuffers()
	}
	horde3d.Release()
	sdl.Quit()

}
Example #27
0
func HandleUserInput() bool {
	for e := sdl.PollEvent(); e != nil; e = sdl.PollEvent() {
		switch e.(type) {
		case *sdl.QuitEvent:
			return true
		case *sdl.ResizeEvent:
			re := e.(*sdl.ResizeEvent)
			screen := sdl.SetVideoMode(int(re.W), int(re.H), 16,
				sdl.OPENGL|sdl.RESIZABLE)
			if screen != nil {
				viewport.Reshape(int(screen.W), int(screen.H))
			} else {
				panic("Could not set video mode")
			}
			break

		case *sdl.MouseButtonEvent:
			re := e.(*sdl.MouseButtonEvent)
			HandleMouseButton(re)

		case *sdl.KeyboardEvent:
			re := e.(*sdl.KeyboardEvent)

			if re.Keysym.Sym == sdl.K_ESCAPE && re.Type == sdl.KEYDOWN {
				if inventory.visible {
					inventory.Hide()
				} else {
					if pause.visible {
						pause.visible = false
					} else {
						pause.visible = true
					}
				}
			}

			if re.Keysym.Sym == sdl.K_F3 && re.Type == sdl.KEYDOWN {
				console.visible = !console.visible
			}

			if !pause.visible {
				if re.Keysym.Sym == sdl.K_i && re.Type == sdl.KEYDOWN {
					if inventory.visible {
						inventory.Hide()
					} else {
						inventory.Show(nil, nil)
					}
				}

				if inventory.visible {
					inventory.HandleKeyboard(re)
				}
			}
		}
	}

	keys := sdl.GetKeyState()

	if console.visible {
		console.HandleKeys(keys)
	}

	if pause.visible {
		pause.HandleKeys(keys)
	} else if inventory.visible {
		inventory.HandleKeys(keys)
	} else {
		viewport.HandleKeys(keys)
		ThePlayer.HandleKeys(keys)
		picker.HandleKeys(keys)
	}

	return false
}
Example #28
0
func main() {

	if sdl.Init(sdl.INIT_EVERYTHING) != 0 {
		panic(sdl.GetError())
	}

	if ttf.Init() != 0 {
		panic(sdl.GetError())
	}

	if mixer.OpenAudio(mixer.DEFAULT_FREQUENCY, mixer.DEFAULT_FORMAT,
		mixer.DEFAULT_CHANNELS, 4096) != 0 {
		panic(sdl.GetError())
	}

	var screen = sdl.SetVideoMode(640, 480, 32, sdl.RESIZABLE)

	if screen == nil {
		panic(sdl.GetError())
	}

	var video_info = sdl.GetVideoInfo()

	println("HW_available = ", video_info.HW_available)
	println("WM_available = ", video_info.WM_available)
	println("Video_mem = ", video_info.Video_mem, "kb")

	sdl.EnableUNICODE(1)

	sdl.WM_SetCaption("Go-SDL SDL Test", "")

	image := sdl.Load("test.png")

	if image == nil {
		panic(sdl.GetError())
	}

	sdl.WM_SetIcon(image, nil)

	running := true

	font := ttf.OpenFont("Fontin Sans.otf", 72)

	if font == nil {
		panic(sdl.GetError())
	}

	font.SetStyle(ttf.STYLE_UNDERLINE)
	white := sdl.Color{255, 255, 255, 0}
	text := ttf.RenderText_Blended(font, "Test (with music)", white)
	music := mixer.LoadMUS("test.ogg")
	sound := mixer.LoadWAV("sound.ogg")

	if music == nil || sound == nil {
		panic(sdl.GetError())
	}

	music.PlayMusic(-1)

	if sdl.GetKeyName(270) != "[+]" {
		panic("GetKeyName broken")
	}

	worm_in := make(chan Point)
	draw := make(chan Point, 64)

	var out chan Point
	var in chan Point

	out = worm_in

	in = out
	out = make(chan Point)
	go worm(in, out, draw)

	for running {
		for ev := sdl.PollEvent(); ev != nil; ev = sdl.PollEvent() {
			switch e := ev.(type) {
			case *sdl.QuitEvent:
				running = false
				break
			case *sdl.KeyboardEvent:
				println("")
				println(e.Keysym.Sym, ": ", sdl.GetKeyName(sdl.Key(e.Keysym.Sym)))

				if e.Keysym.Sym == 27 {
					running = false
				}

				fmt.Printf("%04x ", e.Type)

				for i := 0; i < len(e.Pad0); i++ {
					fmt.Printf("%02x ", e.Pad0[i])
				}
				println()

				fmt.Printf("Type: %02x Which: %02x State: %02x Pad: %02x\n", e.Type, e.Which, e.State, e.Pad0[0])
				fmt.Printf("Scancode: %02x Sym: %08x Mod: %04x Unicode: %04x\n", e.Keysym.Scancode, e.Keysym.Sym, e.Keysym.Mod, e.Keysym.Unicode)
			case *sdl.MouseButtonEvent:
				if e.Type == sdl.MOUSEBUTTONDOWN {
					println("Click:", e.X, e.Y)
					in = out
					out = make(chan Point)
					go worm(in, out, draw)
					sound.PlayChannel(-1, 0)
				}
			case *sdl.ResizeEvent:
				println("resize screen ", e.W, e.H)

				screen = sdl.SetVideoMode(int(e.W), int(e.H), 32, sdl.RESIZABLE)

				if screen == nil {
					panic(sdl.GetError())
				}
			}
		}

		screen.FillRect(nil, 0x302019)
		screen.Blit(&sdl.Rect{0, 0, 0, 0}, text, nil)

		loop := true

		for loop {

			select {
			case p := <-draw:
				screen.Blit(&sdl.Rect{int16(p.x), int16(p.y), 0, 0}, image, nil)
			case <-out:
			default:
				loop = false
			}

		}

		var p Point
		sdl.GetMouseState(&p.x, &p.y)
		worm_in <- p

		screen.Flip()
		sdl.Delay(25)
	}

	image.Free()
	music.Free()
	font.Close()

	ttf.Quit()
	sdl.Quit()
}
Example #29
0
func main() {
	runtime.LockOSThread()
	flag.Parse()
	buildPalette()
	sdl.Init(sdl.INIT_VIDEO)
	defer sdl.Quit()

	sdl.GL_SetAttribute(sdl.GL_SWAP_CONTROL, 1)

	if sdl.SetVideoMode(512, 512, 32, sdl.OPENGL) == nil {
		panic("sdl error")
	}

	if gl.Init() != 0 {
		panic("gl error")
	}

	sdl.WM_SetCaption("Gomandel", "Gomandel")

	gl.Enable(gl.TEXTURE_2D)
	gl.Viewport(0, 0, 512, 512)
	gl.MatrixMode(gl.PROJECTION)
	gl.LoadIdentity()
	gl.Ortho(0, 512, 512, 0, -1, 1)

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

	//-----------------------------------------------------------------------------
	var dndDragging bool = false
	var dndStart Point
	var dndEnd Point
	var tex gl.Texture
	var tc TexCoords
	var lastProgress int
	initialRect := Rect{-1.5, -1.5, 3, 3}
	rect := initialRect

	rc := new(MandelbrotRequest)
	rc.MakeRequest(512, 512, rect)
	rc.WaitFor(Small, &tex, &tc)

	running := true
	for running {
		for e := sdl.PollEvent(); e != nil; e = sdl.PollEvent() {
			switch e.(type) {
			case *sdl.QuitEvent:
				running = false
			case *sdl.MouseButtonEvent:
				mbe := e.(*sdl.MouseButtonEvent)
				if mbe.Type == sdl.MOUSEBUTTONDOWN {
					dndDragging = true
					sdl.GetMouseState(&dndStart.X, &dndStart.Y)
					dndEnd = dndStart
				} else {
					dndDragging = false
					sdl.GetMouseState(&dndEnd.X, &dndEnd.Y)
					if mbe.Which == 3 {
						rect = initialRect
					} else {
						rect = rectFromSelection(dndStart, dndEnd, 512, 512, rect)
						tc = texCoordsFromSelection(dndStart, dndEnd, 512, 512, tc)
					}

					// make request
					rc.MakeRequest(512, 512, rect)
				}
			case *sdl.MouseMotionEvent:
				if dndDragging {
					sdl.GetMouseState(&dndEnd.X, &dndEnd.Y)
				}
			}
		}

		// if we're waiting for a result, check if it's ready
		p := rc.Update(&tex, &tc)
		if p != -1 {
			lastProgress = p
		}

		gl.Clear(gl.COLOR_BUFFER_BIT)
		tex.Bind(gl.TEXTURE_2D)
		drawQuad(0, 0, 512, 512, tc.TX, tc.TY, tc.TX2, tc.TY2)
		tex.Unbind(gl.TEXTURE_2D)
		if dndDragging {
			drawSelection(dndStart, dndEnd)
		}
		drawProgress(512, 512, lastProgress, rc.Pending)
		sdl.GL_SwapBuffers()
	}
}
Example #30
0
func main() {

	flag.Parse()

	var done bool
	var keys []uint8

	sdl.Init(sdl.INIT_VIDEO)

	var screen = sdl.SetVideoMode(300, 300, 16, sdl.OPENGL|sdl.RESIZABLE)

	if screen == nil {
		sdl.Quit()
		panic("Couldn't set 300x300 GL video mode: " + sdl.GetError() + "\n")
	}

	if gl.Init() != 0 {
		panic("gl error")
	}

	sdl.WM_SetCaption("Gears", "gears")

	init_()
	reshape(int(screen.W), int(screen.H))
	done = false
	for !done {

		idle()
		for e := sdl.PollEvent(); e != nil; e = sdl.PollEvent() {
			switch e.(type) {
			case *sdl.ResizeEvent:
				re := e.(*sdl.ResizeEvent)
				screen = sdl.SetVideoMode(int(re.W), int(re.H), 16,
					sdl.OPENGL|sdl.RESIZABLE)
				if screen != nil {
					reshape(int(screen.W), int(screen.H))
				} else {
					panic("we couldn't set the new video mode??")
				}
				break

			case *sdl.QuitEvent:
				done = true
				break
			}
		}
		keys = sdl.GetKeyState()

		if keys[sdl.K_ESCAPE] != 0 {
			done = true
		}
		if keys[sdl.K_UP] != 0 {
			view_rotx += 5.0
		}
		if keys[sdl.K_DOWN] != 0 {
			view_rotx -= 5.0
		}
		if keys[sdl.K_LEFT] != 0 {
			view_roty += 5.0
		}
		if keys[sdl.K_RIGHT] != 0 {
			view_roty -= 5.0
		}
		if keys[sdl.K_z] != 0 {
			if (sdl.GetModState() & sdl.KMOD_RSHIFT) != 0 {
				view_rotz -= 5.0
			} else {
				view_rotz += 5.0
			}
		}

		draw()
	}
	sdl.Quit()
	return

}