コード例 #1
0
ファイル: gui.go プロジェクト: gordonklaus/gui
// must be called on the main goroutine, which will run on the main thread because glfw calls runtime.LockOSThread()
func Run(init func()) error {
	glfw.OnError(func(err error) {
		log.Println("GLFW: ", err)
	})
	if err := glfw.Init(); err != nil {
		return err
	}
	defer glfw.Terminate()
	if err := gl.Init(); err != nil {
		return err
	}
	go init()
	for len(windows) == 0 {
		(<-do)()
	}
	for len(windows) > 0 {
		glfw.WaitEvents()
		select {
		case f := <-do:
			f()
		default:
		}
	}
	return nil
}
コード例 #2
0
ファイル: gopher.go プロジェクト: sserafimescu/gogl
func main() {
	if err := glfw.Init(); err != nil {
		fmt.Fprintf(os.Stderr, "glfw: %s\n", err)
		return
	}
	defer glfw.Terminate()

	glfw.OpenWindowHint(glfw.WindowNoResize, 1)

	if err := glfw.OpenWindow(Width, Height, 0, 0, 0, 0, 0, 0, glfw.Windowed); err != nil {
		fmt.Fprintf(os.Stderr, "glfw: %s\n", err)
		return
	}
	defer glfw.CloseWindow()

	glfw.SetSwapInterval(1)
	glfw.SetWindowTitle(Title)

	if err := gl.Init(); err != nil {
		fmt.Fprintf(os.Stderr, "gl: %s\n", err)
	}

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

	for glfw.WindowParam(glfw.Opened) == 1 {
		drawScene()
		glfw.SwapBuffers()
	}
}
コード例 #3
0
ファイル: main.go プロジェクト: runningwild/jota
func main() {
	defer base.StackCatcher()
	sys.Startup()
	err := gl.Init()
	if err != nil {
		base.Error().Fatalf("%v", err)
	}

	render.Init()
	render.Queue(func() {
		sys.CreateWindow(10, 10, wdx, wdy)
		sys.EnableVSync(true)
	})
	base.InitShaders()
	runtime.GOMAXPROCS(10)
	sys.Think()

	base.LoadAllDictionaries()

	if Version() != "standard" {
		engine := debugHookup(Version())
		mainLoop(engine, "standard")
	} else {
		// TODO: Reimplement standard hookup
	}
}
コード例 #4
0
ファイル: main.go プロジェクト: runningwild/jbot
func main() {
	sys.Startup()
	err := gl.Init()
	if err != nil {
		base.Error().Fatalf("%v", err)
	}

	render.Init()
	render.Queue(func() {
		sys.CreateWindow(10, 10, wdx, wdy)
		sys.EnableVSync(true)
	})
	base.InitShaders()
	runtime.GOMAXPROCS(10)
	sys.Think()

	console := base.MakeConsole(wdx, wdy)
	controllers := getPlayers(console)
	base.Log().Printf("%v\n", controllers)
	go server.Main()

	base.LoadAllDictionaries()

	client, err := game.MakeClient("127.0.0.1", 1231)
	if err != nil {
		base.Error().Printf("Unable to connect to server: %v\n", err)
		return
	}
	mainLoop(client, controllers, console)
}
コード例 #5
0
ファイル: draw.go プロジェクト: jaredly/rocks
func RunGame(title string, width, height int, init, draw func()) {
	if err := glfw.Init(); err != nil {
		fmt.Fprintf(os.Stderr, "glfw: %s\n", err)
		return
	}
	defer glfw.Terminate()

	glfw.OpenWindowHint(glfw.WindowNoResize, 1)

	if err := glfw.OpenWindow(width, height, 0, 0, 0, 0, 16, 0, glfw.Windowed); err != nil {
		fmt.Fprintf(os.Stderr, "glfw: %s\n", err)
		return
	}
	defer glfw.CloseWindow()

	glfw.SetSwapInterval(1)
	glfw.SetWindowTitle(title)

	if err := gl.Init(); err != nil {
		fmt.Fprintf(os.Stderr, "gl: %s\n", err)
	}

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

	for glfw.WindowParam(glfw.Opened) == 1 {
		drawScene(draw)
		glfw.SwapBuffers()
	}
}
コード例 #6
0
ファイル: gameloop.go プロジェクト: kelly-ry4n/glGalaxy
func main() {
	if err := glfw.Init(); err != nil {
		fmt.Fprintf(os.Stderr, "glfw: %s\n", err)
		return
	}
	defer glfw.Terminate()

	glfw.OpenWindowHint(glfw.WindowNoResize, 0)

	if err := glfw.OpenWindow(Width, Height, 0, 0, 0, 0, 16, 0, glfw.Windowed); err != nil {
		fmt.Fprintf(os.Stderr, "glfw: %s\n", err)
		return
	}
	defer glfw.CloseWindow()

	glfw.SetSwapInterval(60)
	glfw.SetWindowTitle(Title)

	if err := gl.Init(); err != nil {
		fmt.Fprintf(os.Stderr, "gl: %s\n", err)
	}

	keybindings.BindKeyboard()

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

	GameLoop()

}
コード例 #7
0
ファイル: init.go プロジェクト: shenyp09/mx3
func InitGL(smooth bool, multisample int) {
	core.Fatal(gl.Init())

	gl.Enable(gl.LIGHTING)

	gl.Enable(gl.CULL_FACE)
	gl.CullFace(gl.BACK)

	if multisample != 0 {
		gl.Enable(gl.MULTISAMPLE)
	}

	if smooth {
		gl.ShadeModel(gl.SMOOTH)
	}
}
コード例 #8
0
ファイル: draw.go プロジェクト: velovix/paunch
func initDraw() error {

	runtime.LockOSThread()

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

	gl.ClearColor(0.0, 0.0, 0.0, 1.0)

	gl.Enable(gl.BLEND)
	gl.BlendFuncSeparate(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ZERO)

	return checkForErrors()
}
コード例 #9
0
ファイル: GOpenGL.go プロジェクト: knickers/GOpenGL
func (o *OpenGl) Init() {
	if err := glfw.Init(); err != nil {
		fmt.Fprintf(os.Stderr, "glfw: %s\n", err)
		return
	}
	defer glfw.Terminate()

	if err := glfw.OpenWindow(o.width, o.height, 0, 0, 0, 0, 16, 0, glfw.Windowed); err != nil {
		fmt.Fprintf(os.Stderr, "glfw: %s\n", err)
		return
	}
	defer glfw.CloseWindow()

	glfw.SetSwapInterval(1)
	glfw.SetWindowTitle(o.title)

	if err := gl.Init(); err != nil {
		fmt.Fprintf(os.Stderr, "gl: %s\n", err)
	}

	glfw.SetKeyCallback(glfw.KeyHandler(o.keyboard))
	glfw.SetMouseButtonCallback(glfw.MouseButtonHandler(o.mouseClick))
	glfw.SetMousePosCallback(glfw.MousePosHandler(o.mouseMove))
	glfw.SetMouseWheelCallback(glfw.MouseWheelHandler(o.mouseWheel))

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

	for glfw.WindowParam(glfw.Opened) == 1 {
		gl.Clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT)

		if o.display3d != nil {
			o.set3dView()
			o.display3d()
		}
		if o.display2d != nil {
			o.set2dView()
			o.display2d()
		}

		glfw.SwapBuffers()
		time.Sleep(20 * time.Millisecond)
		//<-o.redisplay
	}
}
コード例 #10
0
ファイル: bspview.go プロジェクト: jayschwa/groke
func main() {
	flag.Parse()

	if *cpuprofile != "" {
		f, err := os.Create(*cpuprofile)
		if err != nil {
			log.Fatal(err)
		}

		pprof.StartCPUProfile(f)
		defer pprof.StopCPUProfile()
	}

	if err := readModel(); err != nil {
		log.Fatal(err)
	}

	if err := glfw.Init(); err != nil {
		log.Fatal(err)
	}
	defer glfw.Terminate()

	glfw.OpenWindowHint(glfw.WindowNoResize, 1)

	if err := glfw.OpenWindow(Width, Height, 0, 0, 0, 0, 16, 0, glfw.Windowed); err != nil {
		log.Fatal(err)
		return
	}
	defer glfw.CloseWindow()

	glfw.SetSwapInterval(1)
	glfw.SetWindowTitle(Title)
	glfw.SetKeyCallback(onKey)

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

	initScene()
	defer destroyScene()

	for glfw.WindowParam(glfw.Opened) == 1 {
		applyMove()
		drawScene()
		glfw.SwapBuffers()
	}
}
コード例 #11
0
ファイル: main.go プロジェクト: runningwild/arkanoid
func initWindow(sys system.System, width int, height int) {
	sys.CreateWindow(10, 10, width, height)
	sys.EnableVSync(false)

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

	gl.Enable(gl.BLEND)
	gl.BlendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA)
	gl.EnableClientState(gl.VERTEX_ARRAY)
	gl.EnableClientState(gl.COLOR_ARRAY)
	gl.Enable(gl.CULL_FACE)
	gl.FrontFace(gl.CW)

	gl.ClearColor(0, 0, 0, 1)
}
コード例 #12
0
ファイル: webmplay.go プロジェクト: jacereda/webmplay
func (a *app) OnGLInit() {
	gl.Init()
	var ntex int
	if *blend {
		ntex = 6
	} else {
		ntex = 3
	}
	for i := 0; i < ntex; i++ {
		texinit(i + 1)
	}
	a.factorloc = shinit()
	initquad()
	gl.Enable(gl.TEXTURE_2D)
	gl.Disable(gl.DEPTH_TEST)
	a.tbase = time.Now()
	if *fullscreen {
		a.enterFullscreen()
	}
}
コード例 #13
0
ファイル: backend.go プロジェクト: ajhager/rog
func glInit(width, height int) {
	gl.Init()
	gl.Enable(gl.TEXTURE_2D)
	gl.PixelStorei(gl.UNPACK_ALIGNMENT, 1)
	gl.Viewport(0, 0, gl.Sizei(width), gl.Sizei(height))
	gl.MatrixMode(gl.PROJECTION)
	gl.LoadIdentity()
	gl.Ortho(0, gl.Double(width), gl.Double(height), 0, -1, 1)
	gl.MatrixMode(gl.MODELVIEW)
	gl.LoadIdentity()
	gl.Enable(gl.BLEND)
	gl.BlendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA)

	gl.EnableClientState(gl.VERTEX_ARRAY)
	gl.EnableClientState(gl.COLOR_ARRAY)
	gl.EnableClientState(gl.TEXTURE_COORD_ARRAY)
	gl.VertexPointer(2, gl.FLOAT, 0, gl.Pointer(&vs[0]))
	gl.ColorPointer(3, gl.UNSIGNED_BYTE, 0, gl.Pointer(&cs[0]))
	gl.TexCoordPointer(2, gl.FLOAT, 0, gl.Pointer(&ts[0]))
}
コード例 #14
0
ファイル: main.go プロジェクト: dskinner/cell
func main() {
	runtime.GOMAXPROCS(runtime.NumCPU())
	flag.Parse()

	if *flagListRules {
		for _, name := range automata.Rulers() {
			fmt.Println(name)
		}
		return
	}

	if err := glfw.Init(); err != nil {
		log.Fatal(err)
	}
	defer glfw.Terminate()

	glfw.OpenWindowHint(glfw.WindowNoResize, 1)

	if err := glfw.OpenWindow(Width, Height, 0, 0, 0, 0, 0, 0, glfw.Windowed); err != nil {
		log.Fatal(err)
	}
	defer glfw.CloseWindow()

	glfw.SetSwapInterval(1)
	glfw.SetWindowTitle(Title)

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

	initScene()
	defer destroyScene()

	for glfw.WindowParam(glfw.Opened) == 1 {
		drawScene()
		glfw.SwapBuffers()
	}
}
コード例 #15
0
ファイル: main.go プロジェクト: runningwild/magnus
func main() {
	defer base.StackCatcher()
	fmt.Printf("sys.Startup()...")
	sys.Startup()
	fmt.Printf("successful.\n")
	fmt.Printf("gl.Init()...")
	err := gl.Init()
	fmt.Printf("successful.\n")
	if err != nil {
		base.Error().Fatalf("%v", err)
	}

	fmt.Printf("render.Init()...")
	render.Init()
	fmt.Printf("successful.\n")
	render.Queue(func() {
		fmt.Printf("sys.CreateWindow()...")
		sys.CreateWindow(10, 10, wdx, wdy)
		fmt.Printf("successful.\n")
		sys.EnableVSync(true)
	})
	base.InitShaders()
	runtime.GOMAXPROCS(10)
	fmt.Printf("sys.Think()...")
	sys.Think()
	fmt.Printf("successful.\n")

	base.LoadAllDictionaries()

	if Version() != "standard" {
		engine, local := debugHookup(Version())
		mainLoop(engine, local, "standard")
	} else {
		standardHookup()
	}
}
コード例 #16
0
ファイル: gomandel.go プロジェクト: nsf/gomandel
func main() {
	runtime.LockOSThread()
	flag.Parse()
	if *workers <= 0 {
		*workers = 1
	}
	runtime.GOMAXPROCS(*workers + 1)
	buildPalette()
	sdl.Init(sdl.INIT_VIDEO)
	defer sdl.Quit()

	if !*noVSync {
		sdl.GL_SetAttribute(sdl.GL_SWAP_CONTROL, 1)
	}

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

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

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

	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 dnd3 bool = false
	var dndStart Point
	var dndEnd Point
	initialRect := Rect{-1.5, -1.5, 3, 3}
	rect := initialRect

	tm := NewTileManager(512, 512)
	tm.ZoomRequest(&rect)

	running := true
	for running {
		for {
			var event interface{}
			select {
			case event = <-sdl.Events:
			default:
			}

			if event == nil {
				break
			}

			switch e := event.(type) {
			case sdl.QuitEvent:
				running = false
			case sdl.MouseButtonEvent:
				if e.Type == sdl.MOUSEBUTTONDOWN {
					dndDragging = true
					dndStart.X = gl.Int(e.X)
					dndStart.Y = gl.Int(e.Y)
					dndEnd = dndStart
					if e.Button == 3 {
						dnd3 = true
					} else {
						dndDragging = true
					}
				} else {
					dndDragging = false
					dndEnd.X = gl.Int(e.X)
					dndEnd.Y = gl.Int(e.Y)

					switch e.Button {
					case 1:
						rect = rectFromSelection(dndStart, dndEnd, 512, 512, rect)
						tm.ZoomRequest(&rect)
					case 2:
						rect = initialRect
						tm.ZoomRequest(&rect)
					case 3:
						dnd3 = false
					}
				}
			case sdl.MouseMotionEvent:
				if dnd3 {
					dndEnd.X = gl.Int(e.X)
					dndEnd.Y = gl.Int(e.Y)
					rect = moveRectBy(rect, dndStart, dndEnd, 512, 512)
					tm.MoveRequest(rect)
					dndStart = dndEnd
				} else if dndDragging {
					dndEnd.X = gl.Int(e.X)
					dndEnd.Y = gl.Int(e.Y)
				}
			}
		}
		tm.Update()
		gl.Clear(gl.COLOR_BUFFER_BIT)
		tm.Draw()
		gl.BindTexture(gl.TEXTURE_2D, 0)
		if dndDragging {
			drawSelection(dndStart, dndEnd)
		}
		sdl.GL_SwapBuffers()
	}
}
コード例 #17
0
ファイル: main.go プロジェクト: dgthunder/magnus
func main() {
	fmt.Printf("%v\n", key_map)
	sys.Startup()
	err := gl.Init()
	if err != nil {
		panic(err)
	}

	render.Init()
	render.Queue(func() {
		sys.CreateWindow(10, 10, wdx, wdy)
		sys.EnableVSync(true)
		err := gl.Init()
		if err != nil {
			panic(err)
		}
	})
	base.InitShaders()
	runtime.GOMAXPROCS(2)
	ui, err = gui.Make(gin.In(), gui.Dims{wdx, wdy}, filepath.Join(datadir, "fonts", "skia.ttf"))
	if err != nil {
		panic(err)
	}
	sys.Think()
	for false && len(sys.GetActiveDevices()[gin.DeviceTypeController]) < 2 {
		time.Sleep(time.Millisecond * 100)
		sys.Think()
	}

	var ids []int
	var engine *cgf.Engine
	var room game.Room
	err = base.LoadJson(filepath.Join(base.GetDataDir(), "rooms/basic.json"), &room)
	if err != nil {
		panic(err)
	}
	if IsHost() {
		sys.Think()
		var g game.Game
		g.Rng = cmwc.MakeGoodCmwc()
		g.Rng.SeedWithDevRand()
		g.Dx = 900
		g.Dy = 600
		g.Friction = 0.97
		g.Friction_lava = 0.85
		g.Room = room
		var p game.Player
		p.Color.R = 255
		err := json.NewDecoder(bytes.NewBuffer([]byte(`
      {
        "Base": {
          "Max_turn": 0.07,
          "Max_acc": 0.2,
          "Mass": 750,
          "Max_rate": 10,
          "Influence": 75,
          "Health": 1000
        },
        "Dynamic": {
          "Health": 1000
        }
      }
    `))).Decode(&p.Stats)
		if err != nil {
			panic(err)
		}
		Nx := 2
		Ny := 1
		p.X = float64(g.Dx-Nx)/2 - 200
		p.Y = float64(g.Dy-Ny)/2 - 200
		for x := 0; x < Nx; x++ {
			for y := 0; y < Ny; y++ {
				p.X += float64(x * 25)
				p.Y += float64(y * 25)
				p.Gid++
				// p.Mass += float64(x+y) * 150
				p.Processes = make(map[int]game.Process)
				temp := p
				ids = append(ids, g.AddEnt(&temp))

				// p.Mass -= float64(x+y) * 150
				p.X -= float64(x * 25)
				p.Y -= float64(y * 25)
			}
		}
		g.Ents[0].(*game.Player).X = 500
		g.Ents[0].(*game.Player).Y = 300
		g.Ents[1].(*game.Player).X = 550
		g.Ents[1].(*game.Player).Y = 300
		g.SetLocalData()
		d := sys.GetActiveDevices()
		base.Log().Printf("%v\n", d)
		n := 0
		base.Log().Printf("%v\n", d[gin.DeviceTypeController])
		for _, index := range d[gin.DeviceTypeController] {
			// panic("ASD")
			g.SetLocalPlayer(g.Ents[n].(*game.Player), index)
			n++
			if n > 2 {
				break
			}
		}
		if len(d[gin.DeviceTypeController]) == 0 {
			g.SetLocalPlayer(g.Ents[0].(*game.Player), 0)
		}
		// g.Ents[0], g.Ents[(N*N)/2+(1-N%2)*N/2] = g.Ents[(N*N)/2+(1-N%2)*N/2], g.Ents[0]
		g.Init()
		// engine, err = cgf.NewLocalEngine(&g, 17, base.Log())
		engine, err = cgf.NewHostEngine(&g, 17, "", 1231, base.Log())
		if err != nil {
			panic(err.Error())
		}
		g.SetEngine(engine)
	} else {
		engine, err = cgf.NewClientEngine(17, "", 1231, base.Log())
		if err != nil {
			panic(err.Error())
		}
		engine.CopyState().(*game.Game).SetEngine(engine)
	}

	anchor := gui.MakeAnchorBox(gui.Dims{wdx, wdy})
	ui.AddChild(anchor)
	anchor.AddChild(&game.GameWindow{Engine: engine}, gui.Anchor{0.5, 0.5, 0.5, 0.5})
	var v float64
	var profile_output *os.File
	var num_mem_profiles int
	// ui.AddChild(base.MakeConsole())

	base.LoadAllDictionaries()

	for gin.In().GetKey(gin.AnyEscape).FramePressCount() == 0 {
		sys.Think()
		render.Queue(func() {
			ui.Draw()
		})
		render.Queue(func() {
			sys.SwapBuffers()
		})
		render.Purge()
		game.LocalThink()

		if IsHost() {
			for i := 0; i <= 0; i++ {
				// down_axis := gin.In().GetKeyFlat(gin.ControllerAxis0Positive+1, gin.DeviceTypeController, gin.DeviceIndexAny)
				// up_axis := gin.In().GetKeyFlat(gin.ControllerAxis0Negative+1, gin.DeviceTypeController, gin.DeviceIndexAny)
				// right_axis := gin.In().GetKeyFlat(gin.ControllerAxis0Positive, gin.DeviceTypeController, gin.DeviceIndexAny)
				// left_axis := gin.In().GetKeyFlat(gin.ControllerAxis0Negative, gin.DeviceTypeController, gin.DeviceIndexAny)
				// up := key_map[fmt.Sprintf("%dup", i)].FramePressAvg()
				// down := key_map[fmt.Sprintf("%ddown", i)].FramePressAvg()
				// left := key_map[fmt.Sprintf("%dleft", i)].FramePressAvg()
				// right := key_map[fmt.Sprintf("%dright", i)].FramePressAvg()
				// up = axisControl(up_axis.FramePressAmt())
				// down = axisControl(down_axis.FramePressAmt())
				// left = axisControl(left_axis.FramePressAmt())
				// right = axisControl(right_axis.FramePressAmt())
				// if up-down != 0 {
				// 	engine.ApplyEvent(game.Accelerate{ids[i], 2 * (up - down)})
				// }
				// if left-right != 0 {
				// 	engine.ApplyEvent(game.Turn{ids[i], (left - right)})
				// }

				// if key_map[fmt.Sprintf("%d-1", i)].FramePressCount() > 0 {
				// 	engine.ApplyEvent(game.Pull{ids[i], 0, 20000})
				// }
				// if key_map[fmt.Sprintf("%d-2", i)].FramePressCount() > 0 {
				// 	engine.ApplyEvent(game.MoonFire{ids[i], 1, 50, 50})
				// }
				// if gin.In().GetKeyFlat(gin.ControllerButton0, gin.DeviceTypeController, gin.DeviceTypeAny).FramePressCount() > 0 {
				// if key_map[fmt.Sprintf("%d-3", i)].FramePressCount() > 0 {
				// engine.ApplyEvent(game.Burst{ids[i], 2, 3, 100000})
				// }
			}
		}

		// TODO: Replace the 'P' key with an appropriate keybind
		if gin.In().GetKey(gin.AnyKeyP).FramePressCount() > 0 {
			if profile_output == nil {
				profile_output, err = os.Create(filepath.Join(datadir, "cpu.prof"))
				if err == nil {
					err = pprof.StartCPUProfile(profile_output)
					if err != nil {
						fmt.Printf("Unable to start CPU profile: %v\n", err)
						profile_output.Close()
						profile_output = nil
					}
					fmt.Printf("profout: %v\n", profile_output)
				} else {
					fmt.Printf("Unable to start CPU profile: %v\n", err)
				}
			} else {
				pprof.StopCPUProfile()
				profile_output.Close()
				profile_output = nil
			}
		}

		// TODO: Replace the 'M' key with an appropriate keybind
		if gin.In().GetKey(gin.AnyKeyM).FramePressCount() > 0 {
			f, err := os.Create(filepath.Join(datadir, fmt.Sprintf("mem.%d.prof", num_mem_profiles)))
			if err != nil {
				base.Error().Printf("Unable to write mem profile: %v", err)
			}
			pprof.WriteHeapProfile(f)
			f.Close()
			num_mem_profiles++
		}

		v += 0.01
	}
}
コード例 #18
0
ファイル: main.go プロジェクト: runningwild/shadertest
func main() {
	{
		f, err := os.Create("/Users/jwills/code/src/github.com/runningwild/shadertest/log.err")
		if err != nil {
			panic("shoot")
		}
		os.Stderr = f
		f, err = os.Create("/Users/jwills/code/src/github.com/runningwild/shadertest/log.out")
		if err != nil {
			panic("shoot")
		}
		os.Stdout = f
	}
	sys.Startup()
	err := gl.Init()
	if err != nil {
		panic(err)
	}
	fmt.Printf("RAWR!!!\n")
	render.Init()
	render.Queue(func() {
		sys.CreateWindow(10, 10, wdx, wdy)
		sys.EnableVSync(true)
		err := gl.Init()
		if err != nil {
			panic(err)
		}
	})
	base.InitShaders()
	runtime.GOMAXPROCS(2)
	ui, err = gui.Make(gin.In(), gui.Dims{wdx, wdy}, filepath.Join(datadir, "fonts", "skia.ttf"))
	if err != nil {
		panic(err)
	}

	anchor := gui.MakeAnchorBox(gui.Dims{wdx, wdy})
	ui.AddChild(anchor)
	var v float64
	// var profile_output *os.File
	// var num_mem_profiles int
	// ui.AddChild(base.MakeConsole())
	size := 19.0
	base.InitShaders()
	x := gl.Double(0.0)
	// y := 0.0
	// tex := texture.LoadFromPath(filepath.Join(base.GetDataDir(), "test/out.dff.small.png"))
	fmt.Printf("RAWR!\n")
	listener := Listener{}
	gin.In().RegisterEventListener(&listener)
	button := gin.In().GetKeyFlat(gin.ControllerButton0+6, gin.DeviceTypeController, gin.DeviceIndexAny)
	fmt.Printf("RAWR!\n")
	for button.FramePressCount() == 0 {
		sys.Think()
		// dsize := gin.In().GetKey(gin.MouseWheelVertical).FramePressAmt()
		// size += dsize
		// x -= float64(tex.Dx()) * dsize / 2
		// y -= float64(tex.Dy()) * dsize / 2
		// if gin.In().GetKey(gin.Down).FramePressAmt() > 0 {
		// 	y += 10
		// }
		// if gin.In().GetKey(gin.Up).FramePressAmt() > 0 {
		// 	y -= 10
		// }
		// if gin.In().GetKey(gin.Left).FramePressAmt() > 0 {
		// 	x += 10
		// }
		// if gin.In().GetKey(gin.Right).FramePressAmt() > 0 {
		// 	x -= 10
		// }
		render.Queue(func() {
			ui.Draw()
			gl.Enable(gl.BLEND)
			gl.BlendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA)
			gl.Disable(gl.TEXTURE_2D)
			gl.Color4ub(255, 0, 0, 255)
			gl.Begin(gl.QUADS)
			gl.Vertex2d(100+x, 20)
			gl.Vertex2d(100+x, gl.Double(size+20))
			gl.Vertex2d(200+x, gl.Double(size+20))
			gl.Vertex2d(200+x, 20)
			x += 1
			gl.End()
			gl.Enable(gl.TEXTURE_2D)
			gl.Color4ub(255, 255, 255, 255)
			// // str := "!@#$%^&*"
			// diff := 5.0 / (math.Log(size) + math.Pow(size, 0.7))

			// // Works for 1200
			// diff = 50 * math.Pow(base.GetDictionary("skia").Scale(), 2) / math.Pow(size, 1.0)

			// // Works for 3000
			// diff = 50 * math.Pow(base.GetDictionary("skia").Scale(), 1.5) / math.Pow(size, 0.8)
			// //0.340637
			// //0.159241
			// diff = 75 * math.Pow(base.GetDictionary("skia").Scale(), 1.0) / math.Pow(size, 1.0)
			// diff = 10 / math.Pow(size, 1.0)
			// diff = 20/math.Pow(size, 1.0) + 5*math.Pow(base.GetDictionary("skia").Scale(), 1.0)/math.Pow(size, 1.0)
			// if diff > 0.45 {
			//   diff = 0.45
			// }
			// base.EnableShader("distance_field")
			// base.SetUniformF("distance_field", "dist_min", float32(0.5-diff))
			// base.SetUniformF("distance_field", "dist_max", float32(0.5+diff))
			// base.GetDictionary("skia").RenderString(str, 100, 20, 0, dy, gui.Left)
			// base.GetDictionary("skia").RenderString(str, 100, 20+2*dy, 0, dy/4, gui.Left)
			// base.GetDictionary("skia").RenderString(str, 100, 20, 0, size, gui.Left)
			lorem := "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum"
			kk := gin.In().GetKeyFlat(gin.ControllerAxis0Positive+1, gin.DeviceTypeController, device_index)
			kl := gin.In().GetKeyFlat(gin.ControllerAxis0Positive+1, gin.DeviceTypeController, gin.DeviceIndexAny)
			s := fmt.Sprintf("%1.2f %1.2f - %1.2f %1.2f", kk.FramePressAvg(), kk.FramePressAmt(), kl.FramePressAvg(), kl.FramePressAmt())
			devices := sys.GetActiveDevices()
			y := 500.0
			for _, t := range []gin.DeviceType{gin.DeviceTypeController, gin.DeviceTypeKeyboard, gin.DeviceTypeMouse} {
				for _, d := range devices[t] {
					var s string
					switch t {
					case gin.DeviceTypeController:
						s = "controller"
					case gin.DeviceTypeKeyboard:
						s = "keyboard"
					case gin.DeviceTypeMouse:
						s = "mouse"
					}
					base.GetDictionary("skia").RenderString(fmt.Sprintf("%s: %d", s, d), 100, y, 0, 45, gui.Left)
					y -= 50
				}
			}
			base.GetDictionary("luxisr").RenderString(s, 50, 50, 0, size, gui.Left)
			// base.GetDictionary("luxisr").RenderString(lorem, 50, 50+size, 0, size, gui.Left)
			base.GetDictionary("skia").RenderString(lorem, 50, 50+2*size, 0, size, gui.Left)
			base.Log().Printf("Foo")
			//      base.EnableShader("")
			// gl.Enable(gl.ALPHA_TEST)
			// gl.AlphaFunc(gl.GREATER, 0.5)
			// tex := texture.LoadFromPath(filepath.Join(base.GetDataDir(), "ships/ship.png"))
			// tex.Bind()
			// tex.RenderAdvanced(x, y, float64(tex.Dx())*size, float64(tex.Dy())*size, 0, true)
			// tex.RenderNatural(300, 100)
			// gl.Disable(gl.ALPHA_TEST)
		})
		render.Queue(func() {
			sys.SwapBuffers()
		})
		render.Purge()

		// if key_map["cpu profile"].FramePressCount() > 0 {
		// 	if profile_output == nil {
		// 		profile_output, err = os.Create(filepath.Join(datadir, "cpu.prof"))
		// 		if err == nil {
		// 			err = pprof.StartCPUProfile(profile_output)
		// 			if err != nil {
		// 				fmt.Printf("Unable to start CPU profile: %v\n", err)
		// 				profile_output.Close()
		// 				profile_output = nil
		// 			}
		// 			fmt.Printf("profout: %v\n", profile_output)
		// 		} else {
		// 			fmt.Printf("Unable to start CPU profile: %v\n", err)
		// 		}
		// 	} else {
		// 		pprof.StopCPUProfile()
		// 		profile_output.Close()
		// 		profile_output = nil
		// 	}
		// }

		// if key_map["mem profile"].FramePressCount() > 0 {
		// 	f, err := os.Create(filepath.Join(datadir, fmt.Sprintf("mem.%d.prof", num_mem_profiles)))
		// 	if err != nil {
		// 		base.Error().Printf("Unable to write mem profile: %v", err)
		// 	}
		// 	pprof.WriteHeapProfile(f)
		// 	f.Close()
		// 	num_mem_profiles++
		// }

		v += 0.01
	}
}
コード例 #19
0
ファイル: Go.go プロジェクト: ReneSac/ParticleBench
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)
}
コード例 #20
0
ファイル: main.go プロジェクト: runningwild/tester
func main() {
	sys = system.Make(gos.GetSystemInterface())
	sys.Startup()
	wdx := 1000
	wdy := 500
	render.Init()
	var ui *gui.Gui
	render.Queue(func() {
		sys.CreateWindow(50, 150, wdx, wdy)
		sys.EnableVSync(true)
		err := gl.Init()
		if err != nil {
			f, err2 := os.Create(filepath.Join(datadir, "gl_log.txt"))
			if err2 != nil {
				fmt.Printf("Unable to write log to a file:%v\n%v\v", err, err2)
			} else {
				fmt.Fprintf(f, "%v\n", err)
				f.Close()
			}
		}
		ui, _ = gui.Make(gin.In(), gui.Dims{wdx, wdy}, filepath.Join(datadir, "fonts", "luxisr.ttf"))
		font, err := loadFont()
		if err != nil {
			panic(err.Error())
		}
		dict = gui.MakeDictionary(font, 15)
	})
	render.Purge()

	anchor := gui.MakeAnchorBox(gui.Dims{wdx, wdy})
	ui.AddChild(anchor)
	var event_handler handler
	gin.In().RegisterEventListener(&event_handler)
	actions_list := gui.MakeVerticalTable()
	keyname_list := gui.MakeVerticalTable()
	both_lists := gui.MakeHorizontalTable()
	both_lists.AddChild(actions_list)
	both_lists.AddChild(keyname_list)
	anchor.AddChild(both_lists, gui.Anchor{1, 0.5, 1, 0.5})
	var actions []string
	for action := range action_map {
		actions = append(actions, action)
	}
	sort.Strings(actions)
	for _, action := range actions {
		actions_list.AddChild(gui.MakeTextLine("standard", action, 150, 1, 1, 1, 1))
		keyname_list.AddChild(gui.MakeTextLine("standard", commands[action].Cmd, 100, 1, 1, 1, 1))
	}

	current_anim := gui.MakeTextLine("standard", "", 300, 1, 1, 1, 1)
	current_state := gui.MakeTextLine("standard", "", 300, 1, 1, 1, 1)
	frame_data := gui.MakeVerticalTable()
	frame_data.AddChild(current_anim)
	frame_data.AddChild(current_state)
	anchor.AddChild(frame_data, gui.Anchor{0, 1, 0, 1})

	speed := 100
	speed_text := gui.MakeTextLine("standard", "Speed: 100%", 150, 1, 1, 1, 1)
	anchor.AddChild(speed_text, gui.Anchor{0, 0, 0, 0})

	var box1, box2 boxdata

	box1.name = "box1"
	box1.sb = makeSpriteBox(nil)
	anchor.AddChild(box1.sb, gui.Anchor{0.5, 0.5, 0.25, 0.5})
	box1.load(GetStoreVal("box1"))
	box := box1

	box2.name = "box2"
	box2.sb = makeSpriteBox(nil)
	anchor.AddChild(box2.sb, gui.Anchor{0.5, 0.5, 0.45, 0.5})
	box2.load(GetStoreVal("box2"))
	box2.sb.top = true
	box_other := box2

	box2.sb.r, box2.sb.g, box2.sb.b = 0.2, 0.1, 0.4
	box1.sb.r, box1.sb.g, box1.sb.b = 0.4, 0.2, 0.8

	error_msg = gui.MakeTextLine("standard", "", wdx, 1, 0.5, 0.5, 1)
	anchor.AddChild(error_msg, gui.Anchor{0, 0, 0, 0.1})

	var chooser gui.Widget
	// curdir := GetStoreVal("curdir")
	// if curdir == "" {
	//   curdir = "."
	// } else {
	//   _,err := os.Stat(filepath.Join(datadir, curdir))
	//   if err == nil {
	//     go func() {
	//       anim, err := sprite.LoadSprite(filepath.Join(datadir, curdir))
	//       loaded <- loadResult{ anim, err }
	//     } ()
	//   } else {
	//     curdir = "."
	//   }
	// }
	// var profile_output *os.File
	then := time.Now()
	sys.Think()
	for key_map["quit"].FramePressCount() == 0 {
		event_handler.box1 = &box
		event_handler.box2 = &box_other
		now := time.Now()
		dt := (now.Nanosecond() - then.Nanosecond()) / 1000000
		then = now
		render.Queue(func() {
			sys.Think()
			if box1.sb.s != nil {
				box1.sb.s.Think(int64(float64(dt) * float64(speed) / 100))
			}
			if box2.sb.s != nil {
				box2.sb.s.Think(int64(float64(dt) * float64(speed) / 100))
			}
			gl.ClearColor(1, 0, 0, 1)
			gl.Clear(gl.COLOR_BUFFER_BIT)
			ui.Draw()
			sys.SwapBuffers()
		})
		render.Purge()
		select {
		case load := <-loaded:
			if load.err != nil {
				error_msg.SetText(load.err.Error())
				current_anim.SetText("")
			} else {
				box.sb.s = load.anim
				error_msg.SetText("")
			}
		default:
		}
		// if box.sb.s != nil {
		//   box.sb.s.Think()
		//   current_anim.SetText(fmt.Sprintf("%d: %s", box.sb.s.Facing(), box.sb.s.Anim()))
		//   current_state.SetText(box.sb.s.AnimState())
		// }

		if box.sb.s != nil {
			if key_map["reset"].FramePressCount() > 0 {
				box.load(box.dir)
				box_other.load(box_other.dir)
			}
		}

		// if key_map["profile"].FramePressCount() > 0 {
		//   if profile_output == nil {
		//     var err error
		//     profile_output, err = os.Create(filepath.Join(datadir, "cpu.prof"))
		//     if err == nil {
		//       err = pprof.StartCPUProfile(profile_output)
		//       if err != nil {
		//         fmt.Printf("Unable to start CPU profile: %v\n", err)
		//         profile_output.Close()
		//         profile_output = nil
		//       }
		//       fmt.Printf("profout: %v\n", profile_output)
		//     } else {
		//       fmt.Printf("Unable to open CPU profile: %v\n", err)
		//     }
		//   } else {
		//     pprof.StopCPUProfile()
		//     profile_output.Close()
		//     profile_output = nil
		//   }
		// }

		if key_map["load"].FramePressCount() > 0 && chooser == nil {
			anch := gui.MakeAnchorBox(gui.Dims{wdx, wdy})
			file_chooser := gui.MakeFileChooser(filepath.Join(datadir, box.dir),
				func(path string, err error) {
					if err == nil && len(path) > 0 {
						curpath, _ := filepath.Split(path)
						box.load(curpath)
					}
					ui.RemoveChild(chooser)
					chooser = nil
				},
				func(path string, is_dir bool) bool {
					return true
				})
			anch.AddChild(file_chooser, gui.Anchor{0.5, 0.5, 0.5, 0.5})
			chooser = anch
			ui.AddChild(chooser)
		}
		delta := key_map["speed up"].FramePressAmt() - key_map["slow down"].FramePressAmt()
		if delta != 0 {
			speed += int(delta)
			if speed < 1 {
				speed = 1
			}
			if speed > 100 {
				speed = 100
			}
			speed_text.SetText(fmt.Sprintf("Speed: %d%%", speed))
		}

		if key_map["select1"].FramePressCount() > 0 {
			box2.sb.r, box2.sb.g, box2.sb.b = 0.2, 0.1, 0.4
			box1.sb.r, box1.sb.g, box1.sb.b = 0.4, 0.2, 0.8
			box = box1
			box_other = box2
		}
		if key_map["select2"].FramePressCount() > 0 {
			box2.sb.r, box2.sb.g, box2.sb.b = 0.4, 0.2, 0.8
			box1.sb.r, box1.sb.g, box1.sb.b = 0.2, 0.1, 0.4
			box = box2
			box_other = box1
		}
	}
}
コード例 #21
0
ファイル: main.go プロジェクト: drasich/malus
func main() {
	if err := glfw.Init(); err != nil {
		fmt.Fprintf(os.Stderr, "glfw: %s\n", err)
		return
	}
	defer glfw.Terminate()

	glfw.OpenWindowHint(glfw.WindowNoResize, gl.TRUE)

	if err := glfw.OpenWindow(Width, Height, 0, 0, 0, 0, 32, 32, glfw.Windowed); err != nil {
		fmt.Fprintf(os.Stderr, "glfw: %s\n", err)
		return
	}
	defer glfw.CloseWindow()

	glfw.SetSwapInterval(1)
	glfw.SetWindowTitle(Title)

	if err := gl.Init(); err != nil {
		fmt.Fprintf(os.Stderr, "gl: %s\n", err)
	}

	var scene ry.Scene
	if err := scene.Init(); err != nil {
		fmt.Fprintf(os.Stderr, "init: %s\n", err)
		return
	}
	defer scene.Destroy()

	var player, wall ry.Object
	wall.Init()
	player.Init()
	player.Position.Z = -7
	player.Position.X = 3
	player.Orientation = ry.QuatAngleAxis(-45*ry.DegToRad, ry.Vec3{0, 0, 1})

	cc := newControlComponent(&player)
	mesh := ry.NewMeshComponent("model/tex.bin", &player)
	mesh.Init()
	player.AddComponent(*cc)
	player.Mesh = mesh

	mesh2 := ry.NewMeshComponent("model/tex.bin", &wall)
	mesh2.Init()
	wall.Mesh = mesh2
	wall.Position.Z = -10
	box := ry.NewBoxComponent(ry.Vec3{0, 0, 0}, ry.Vec3{10, 10, 10})
	wall.Box = box
	wall.Orientation = ry.QuatAngleAxis(-90*ry.DegToRad, ry.Vec3{0, 0, 1})

	scene.AddObject(&player)
	scene.AddObject(&wall)

	//plane := ry.Plane{ry.Vec3{0,0,0}, ry.Vec3{1,1,0}}
	ray := ry.Ray{ry.Vec3{15, -5, -5}, ry.Vec3{-100, 0, 0}}

	/*
	   b, hv := ry.IntersectionRayPlane(ray, plane)
	   if b {
	     fmt.Println("hv : ", hv)
	   } else { fmt.Println("no collision : ", hv) }
	*/

	//aabox := ry.AABox{ry.Vec3{0,0,0}, ry.Vec3{10,10,10}}
	//hit, _, pos, nor := ry.IntersectionRayAABox(ray, aabox)
	hit, _, pos, nor := ry.IntersectionRayObject(ray, &wall)
	if hit {
		fmt.Println("pos and normal : ", pos, nor)
	} else {
		fmt.Println("no intersection with box")

	}

	last_time = time.Now()
	for glfw.WindowParam(glfw.Opened) == 1 && !exit {
		/*
		   objects, positions := ry.LaunchRay( ry.Vec3{0,0,0}, ry.Vec3{0,0,-1}, 100, scene.Objects)

		    if objects != nil {
		      fmt.Println("collision with one or more objects", positions[0])
		    }
		*/

		scene.Update()
		scene.Draw()
		glfw.SwapBuffers()
		since := time.Since(last_time).Seconds()
		if since > 0.02 {
			fmt.Println("frame under 50fps:", since)
		}
		last_time = time.Now()
	}
}