Replaced kingping with flag package

This commit is contained in:
Intyre 2020-12-16 08:11:28 +01:00
parent 6497493d57
commit add41494be
7 changed files with 75 additions and 119 deletions

View File

@ -6,6 +6,7 @@ import (
"container/ring" "container/ring"
"encoding/json" "encoding/json"
"errors" "errors"
"flag"
"fmt" "fmt"
"image" "image"
"image/gif" "image/gif"
@ -24,7 +25,6 @@ import (
"github.com/pkg/profile" "github.com/pkg/profile"
"golang.org/x/image/colornames" "golang.org/x/image/colornames"
"gopkg.in/alecthomas/kingpin.v2"
"github.com/OpenDiablo2/OpenDiablo2/d2common/d2interface" "github.com/OpenDiablo2/OpenDiablo2/d2common/d2interface"
"github.com/OpenDiablo2/OpenDiablo2/d2common/d2math" "github.com/OpenDiablo2/OpenDiablo2/d2common/d2math"
@ -85,11 +85,10 @@ type App struct {
// Options is used to store all of the app options that can be set with arguments // Options is used to store all of the app options that can be set with arguments
type Options struct { type Options struct {
printVersion *bool Debug *bool
Debug *bool profiler *string
profiler *string Server *d2networking.ServerOptions
Server *d2networking.ServerOptions LogLevel *d2util.LogLevel
LogLevel *d2util.LogLevel
} }
type bindTerminalEntry struct { type bindTerminalEntry struct {
@ -110,21 +109,24 @@ const (
// Create creates a new instance of the application // Create creates a new instance of the application
func Create(gitBranch, gitCommit string) *App { func Create(gitBranch, gitCommit string) *App {
assetManager, assetError := d2asset.NewAssetManager() logger := d2util.NewLogger()
logger.SetPrefix(appLoggerPrefix)
app := &App{ app := &App{
Logger: logger,
gitBranch: gitBranch, gitBranch: gitBranch,
gitCommit: gitCommit, gitCommit: gitCommit,
asset: assetManager,
Options: &Options{ Options: &Options{
Server: &d2networking.ServerOptions{}, Server: &d2networking.ServerOptions{},
}, },
errorMessage: assetError,
} }
app.Infof("OpenDiablo2 - Open source Diablo 2 engine")
app.Logger = d2util.NewLogger() app.parseArguments()
app.Logger.SetPrefix(appLoggerPrefix)
app.Logger.SetLevel(d2util.LogLevelDefault) app.SetLevel(*app.Options.LogLevel)
app.asset, app.errorMessage = d2asset.NewAssetManager(*app.Options.LogLevel)
return app return app
} }
@ -140,7 +142,7 @@ func (a *App) startDedicatedServer() error {
srvChanIn := make(chan int) srvChanIn := make(chan int)
srvChanLog := make(chan string) srvChanLog := make(chan string)
srvErr := d2networking.StartDedicatedServer(a.asset, srvChanIn, srvChanLog, a.config.LogLevel, maxPlayers) srvErr := d2networking.StartDedicatedServer(a.asset, srvChanIn, srvChanLog, *a.Options.LogLevel, maxPlayers)
if srvErr != nil { if srvErr != nil {
return srvErr return srvErr
} }
@ -173,15 +175,7 @@ func (a *App) loadEngine() error {
return a.renderer.Run(a.updateInitError, updateNOOP, 800, 600, "OpenDiablo2") return a.renderer.Run(a.updateInitError, updateNOOP, 800, 600, "OpenDiablo2")
} }
// if the log level was specified at the command line, use it audio := ebiten2.CreateAudio(*a.Options.LogLevel, a.asset)
logLevel := *a.Options.LogLevel
if logLevel == d2util.LogLevelUnspecified {
logLevel = a.config.LogLevel
}
a.asset.SetLogLevel(logLevel)
audio := ebiten2.CreateAudio(a.config.LogLevel, a.asset)
inputManager := d2input.NewInputManager() inputManager := d2input.NewInputManager()
@ -197,7 +191,7 @@ func (a *App) loadEngine() error {
scriptEngine := d2script.CreateScriptEngine() scriptEngine := d2script.CreateScriptEngine()
uiManager := d2ui.NewUIManager(a.asset, renderer, inputManager, a.config.LogLevel, audio) uiManager := d2ui.NewUIManager(a.asset, renderer, inputManager, *a.Options.LogLevel, audio)
a.inputManager = inputManager a.inputManager = inputManager
a.terminal = term a.terminal = term
@ -206,51 +200,48 @@ func (a *App) loadEngine() error {
a.ui = uiManager a.ui = uiManager
a.tAllocSamples = createZeroedRing(nSamplesTAlloc) a.tAllocSamples = createZeroedRing(nSamplesTAlloc)
if a.gitBranch == "" {
a.gitBranch = "Local Build"
}
return nil return nil
} }
func (a *App) parseArguments() { func (a *App) parseArguments() {
const ( const (
versionArg = "version" descProfile = "Profiles the program,\none of (cpu, mem, block, goroutine, trace, thread, mutex)"
versionShort = 'v' descPlayers = "Sets the number of max players for the dedicated server"
versionDesc = "Prints the version of the app" descLogging = "Enables verbose logging. Log levels will include those below it.\n" +
" 0 disables log messages\n" +
profilerArg = "profile" " 1 shows fatal\n" +
profilerDesc = "Profiles the program, one of (cpu, mem, block, goroutine, trace, thread, mutex)" " 2 shows error\n" +
" 3 shows warning\n" +
serverArg = "dedicated" " 4 shows info\n" +
serverShort = 'd' " 5 shows debug\n"
serverDesc = "Starts a dedicated server"
playersArg = "players"
playersDesc = "Sets the number of max players for the dedicated server"
loggingArg = "loglevel"
loggingShort = 'l'
loggingDesc = "Enables verbose logging. Log levels will include those below it. " +
"0 disables log messages, " +
"1 shows fatal errors, " +
"2 shows errors, " +
"3 shows warnings, " +
"4 shows info, " +
"5 shows debug" +
"6 uses value from config file (default)"
) )
a.Options.profiler = kingpin.Flag(profilerArg, profilerDesc).String() a.Options.profiler = flag.String("profile", "", descProfile)
a.Options.Server.Dedicated = kingpin.Flag(serverArg, serverDesc).Short(serverShort).Bool() a.Options.Server.Dedicated = flag.Bool("dedicated", false, "Starts a dedicated server")
a.Options.printVersion = kingpin.Flag(versionArg, versionDesc).Short(versionShort).Bool() a.Options.Server.MaxPlayers = flag.Int("players", 0, descPlayers)
a.Options.Server.MaxPlayers = kingpin.Flag(playersArg, playersDesc).Int() a.Options.LogLevel = flag.Int("l", d2util.LogLevelDefault, descLogging)
a.Options.LogLevel = kingpin.Flag(loggingArg, loggingDesc). showVersion := flag.Bool("v", false, "Show version")
Short(loggingShort). showHelp := flag.Bool("h", false, "Show help")
Default(strconv.Itoa(d2util.LogLevelUnspecified)).
Int()
kingpin.Parse() flag.Usage = func() {
fmt.Printf("usage: %s [<flags>]\n\nFlags:\n", os.Args[0])
flag.PrintDefaults()
}
flag.Parse()
if *a.Options.LogLevel >= d2util.LogLevelUnspecified {
*a.Options.LogLevel = d2util.LogLevelDefault
}
if *showVersion {
a.Infof("version: OpenDiablo2 (%s %s)", a.gitBranch, a.gitCommit)
os.Exit(0)
}
if *showHelp {
flag.Usage()
os.Exit(0)
}
} }
// LoadConfig loads the OpenDiablo2 config file // LoadConfig loads the OpenDiablo2 config file
@ -288,42 +279,15 @@ func (a *App) LoadConfig() (*d2config.Configuration, error) {
} }
// Run executes the application and kicks off the entire game process // Run executes the application and kicks off the entire game process
func (a *App) Run() error { func (a *App) Run() (err error) {
a.parseArguments()
// add our possible config directories // add our possible config directories
_, _ = a.asset.AddSource(filepath.Dir(d2config.LocalConfigPath())) _, _ = a.asset.AddSource(filepath.Dir(d2config.LocalConfigPath()))
_, _ = a.asset.AddSource(filepath.Dir(d2config.DefaultConfigPath())) _, _ = a.asset.AddSource(filepath.Dir(d2config.DefaultConfigPath()))
config, err := a.LoadConfig() if a.config, err = a.LoadConfig(); err != nil {
if err != nil {
return err return err
} }
a.config = config
a.asset.SetLogLevel(config.LogLevel)
// print version and exit if `--version` was supplied
if *a.Options.printVersion {
fmtVersion := "OpenDiablo2 (%s %s)"
if a.gitBranch == "" {
a.gitBranch = "local"
}
if a.gitCommit == "" {
a.gitCommit = "build"
}
a.Errorf(fmtVersion, a.gitBranch, a.gitCommit)
os.Exit(0)
}
logLevel := *a.Options.LogLevel
a.asset.SetLogLevel(logLevel)
// start profiler if argument was supplied // start profiler if argument was supplied
if len(*a.Options.profiler) > 0 { if len(*a.Options.profiler) > 0 {
profiler := enableProfiler(*a.Options.profiler, a) profiler := enableProfiler(*a.Options.profiler, a)
@ -409,14 +373,14 @@ func (a *App) initialize() error {
} }
} }
gui, err := d2gui.CreateGuiManager(a.asset, a.config.LogLevel, a.inputManager) gui, err := d2gui.CreateGuiManager(a.asset, *a.Options.LogLevel, a.inputManager)
if err != nil { if err != nil {
return err return err
} }
a.guiManager = gui a.guiManager = gui
a.screen = d2screen.NewScreenManager(a.ui, a.config.LogLevel, a.guiManager) a.screen = d2screen.NewScreenManager(a.ui, *a.Options.LogLevel, a.guiManager)
a.audio.SetVolumes(a.config.BgmVolume, a.config.SfxVolume) a.audio.SetVolumes(a.config.BgmVolume, a.config.SfxVolume)
@ -840,7 +804,7 @@ func (a *App) quitGame() {
} }
func (a *App) enterGuiPlayground() { func (a *App) enterGuiPlayground() {
a.screen.SetNextScreen(d2gamescreen.CreateGuiTestMain(a.renderer, a.guiManager, a.config.LogLevel, a.asset)) a.screen.SetNextScreen(d2gamescreen.CreateGuiTestMain(a.renderer, a.guiManager, *a.Options.LogLevel, a.asset))
} }
func createZeroedRing(n int) *ring.Ring { func createZeroedRing(n int) *ring.Ring {
@ -909,7 +873,7 @@ func (a *App) ToMainMenu(errorMessageOptional ...string) {
buildInfo := d2gamescreen.BuildInfo{Branch: a.gitBranch, Commit: a.gitCommit} buildInfo := d2gamescreen.BuildInfo{Branch: a.gitBranch, Commit: a.gitCommit}
mainMenu, err := d2gamescreen.CreateMainMenu(a, a.asset, a.renderer, a.inputManager, a.audio, a.ui, buildInfo, mainMenu, err := d2gamescreen.CreateMainMenu(a, a.asset, a.renderer, a.inputManager, a.audio, a.ui, buildInfo,
a.config.LogLevel, errorMessageOptional...) *a.Options.LogLevel, errorMessageOptional...)
if err != nil { if err != nil {
a.Error(err.Error()) a.Error(err.Error())
return return
@ -920,7 +884,7 @@ func (a *App) ToMainMenu(errorMessageOptional ...string) {
// ToSelectHero forces the game to transition to the Select Hero (create character) screen // ToSelectHero forces the game to transition to the Select Hero (create character) screen
func (a *App) ToSelectHero(connType d2clientconnectiontype.ClientConnectionType, host string) { func (a *App) ToSelectHero(connType d2clientconnectiontype.ClientConnectionType, host string) {
selectHero, err := d2gamescreen.CreateSelectHeroClass(a, a.asset, a.renderer, a.audio, a.ui, connType, a.config.LogLevel, host) selectHero, err := d2gamescreen.CreateSelectHeroClass(a, a.asset, a.renderer, a.audio, a.ui, connType, *a.Options.LogLevel, host)
if err != nil { if err != nil {
a.Error(err.Error()) a.Error(err.Error())
return return
@ -931,7 +895,7 @@ func (a *App) ToSelectHero(connType d2clientconnectiontype.ClientConnectionType,
// ToCreateGame forces the game to transition to the Create Game screen // ToCreateGame forces the game to transition to the Create Game screen
func (a *App) ToCreateGame(filePath string, connType d2clientconnectiontype.ClientConnectionType, host string) { func (a *App) ToCreateGame(filePath string, connType d2clientconnectiontype.ClientConnectionType, host string) {
gameClient, err := d2client.Create(connType, a.asset, a.config.LogLevel, a.scriptEngine) gameClient, err := d2client.Create(connType, a.asset, *a.Options.LogLevel, a.scriptEngine)
if err != nil { if err != nil {
a.Error(err.Error()) a.Error(err.Error())
} }
@ -942,7 +906,7 @@ func (a *App) ToCreateGame(filePath string, connType d2clientconnectiontype.Clie
a.ToMainMenu(errorMessage) a.ToMainMenu(errorMessage)
} else { } else {
game, err := d2gamescreen.CreateGame( game, err := d2gamescreen.CreateGame(
a, a.asset, a.ui, a.renderer, a.inputManager, a.audio, gameClient, a.terminal, a.config.LogLevel, a.guiManager, a, a.asset, a.ui, a.renderer, a.inputManager, a.audio, gameClient, a.terminal, *a.Options.LogLevel, a.guiManager,
) )
if err != nil { if err != nil {
a.Error(err.Error()) a.Error(err.Error())
@ -955,7 +919,7 @@ func (a *App) ToCreateGame(filePath string, connType d2clientconnectiontype.Clie
// ToCharacterSelect forces the game to transition to the Character Select (load character) screen // ToCharacterSelect forces the game to transition to the Character Select (load character) screen
func (a *App) ToCharacterSelect(connType d2clientconnectiontype.ClientConnectionType, connHost string) { func (a *App) ToCharacterSelect(connType d2clientconnectiontype.ClientConnectionType, connHost string) {
characterSelect, err := d2gamescreen.CreateCharacterSelect(a, a.asset, a.renderer, a.inputManager, characterSelect, err := d2gamescreen.CreateCharacterSelect(a, a.asset, a.renderer, a.inputManager,
a.audio, a.ui, connType, a.config.LogLevel, connHost) a.audio, a.ui, connType, *a.Options.LogLevel, connHost)
if err != nil { if err != nil {
a.Errorf("unable to create character select screen: %s", err) a.Errorf("unable to create character select screen: %s", err)
} }
@ -966,7 +930,7 @@ func (a *App) ToCharacterSelect(connType d2clientconnectiontype.ClientConnection
// ToMapEngineTest forces the game to transition to the map engine test screen // ToMapEngineTest forces the game to transition to the map engine test screen
func (a *App) ToMapEngineTest(region, level int) { func (a *App) ToMapEngineTest(region, level int) {
met, err := d2gamescreen.CreateMapEngineTest(region, level, a.asset, a.terminal, a.renderer, a.inputManager, a.audio, met, err := d2gamescreen.CreateMapEngineTest(region, level, a.asset, a.terminal, a.renderer, a.inputManager, a.audio,
a.config.LogLevel, a.screen) *a.Options.LogLevel, a.screen)
if err != nil { if err != nil {
a.Error(err.Error()) a.Error(err.Error())
return return
@ -977,10 +941,10 @@ func (a *App) ToMapEngineTest(region, level int) {
// ToCredits forces the game to transition to the credits screen // ToCredits forces the game to transition to the credits screen
func (a *App) ToCredits() { func (a *App) ToCredits() {
a.screen.SetNextScreen(d2gamescreen.CreateCredits(a, a.asset, a.renderer, a.config.LogLevel, a.ui)) a.screen.SetNextScreen(d2gamescreen.CreateCredits(a, a.asset, a.renderer, *a.Options.LogLevel, a.ui))
} }
// ToCinematics forces the game to transition to the cinematics menu // ToCinematics forces the game to transition to the cinematics menu
func (a *App) ToCinematics() { func (a *App) ToCinematics() {
a.screen.SetNextScreen(d2gamescreen.CreateCinematics(a, a.asset, a.renderer, a.audio, a.config.LogLevel, a.ui)) a.screen.SetNextScreen(d2gamescreen.CreateCinematics(a, a.asset, a.renderer, a.audio, *a.Options.LogLevel, a.ui))
} }

View File

@ -9,19 +9,23 @@ import (
) )
// NewAssetManager creates and assigns all necessary dependencies for the AssetManager top-level functions to work correctly // NewAssetManager creates and assigns all necessary dependencies for the AssetManager top-level functions to work correctly
func NewAssetManager() (*AssetManager, error) { func NewAssetManager(logLevel d2util.LogLevel) (*AssetManager, error) {
loader, err := d2loader.NewLoader(d2util.LogLevelDefault) loader, err := d2loader.NewLoader(logLevel)
if err != nil { if err != nil {
return nil, err return nil, err
} }
records, err := d2records.NewRecordManager(d2util.LogLevelDebug) records, err := d2records.NewRecordManager(logLevel)
if err != nil { if err != nil {
return nil, err return nil, err
} }
logger := d2util.NewLogger()
logger.SetPrefix(logPrefix)
logger.SetLevel(logLevel)
manager := &AssetManager{ manager := &AssetManager{
Logger: d2util.NewLogger(), Logger: logger,
Loader: loader, Loader: loader,
tables: make([]d2tbl.TextDictionary, 0), tables: make([]d2tbl.TextDictionary, 0),
animations: d2cache.CreateCache(animationBudget), animations: d2cache.CreateCache(animationBudget),
@ -31,7 +35,5 @@ func NewAssetManager() (*AssetManager, error) {
Records: records, Records: records,
} }
manager.SetPrefix(logPrefix)
return manager, err return manager, err
} }

View File

@ -5,8 +5,6 @@ import (
"os" "os"
"path" "path"
"path/filepath" "path/filepath"
"github.com/OpenDiablo2/OpenDiablo2/d2common/d2util"
) )
// Configuration defines the configuration for the engine, loaded from config.json // Configuration defines the configuration for the engine, loaded from config.json
@ -21,7 +19,6 @@ type Configuration struct {
RunInBackground bool RunInBackground bool
VsyncEnabled bool VsyncEnabled bool
Backend string Backend string
LogLevel d2util.LogLevel
path string path string
} }

View File

@ -4,8 +4,6 @@ import (
"os/user" "os/user"
"path" "path"
"runtime" "runtime"
"github.com/OpenDiablo2/OpenDiablo2/d2common/d2util"
) )
// DefaultConfig creates and returns a default configuration // DefaultConfig creates and returns a default configuration
@ -37,8 +35,7 @@ func DefaultConfig() *Configuration {
"d2video.mpq", "d2video.mpq",
"d2speech.mpq", "d2speech.mpq",
}, },
LogLevel: d2util.LogLevelDefault, path: DefaultConfigPath(),
path: DefaultConfigPath(),
} }
switch runtime.GOOS { switch runtime.GOOS {

1
go.mod
View File

@ -17,6 +17,5 @@ require (
golang.org/x/exp v0.0.0-20201008143054-e3b2a7f2fdc7 // indirect golang.org/x/exp v0.0.0-20201008143054-e3b2a7f2fdc7 // indirect
golang.org/x/image v0.0.0-20200927104501-e162460cd6b5 golang.org/x/image v0.0.0-20200927104501-e162460cd6b5
golang.org/x/sys v0.0.0-20201028215240-c5abc1b1d397 // indirect golang.org/x/sys v0.0.0-20201028215240-c5abc1b1d397 // indirect
gopkg.in/alecthomas/kingpin.v2 v2.2.6
gopkg.in/sourcemap.v1 v1.0.5 // indirect gopkg.in/sourcemap.v1 v1.0.5 // indirect
) )

2
go.sum
View File

@ -99,8 +99,6 @@ golang.org/x/tools v0.0.0-20201009162240-fcf82128ed91/go.mod h1:z6u4i615ZeAfBE4X
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
gopkg.in/alecthomas/kingpin.v2 v2.2.6 h1:jMFz6MfLP0/4fUyZle81rXUoxOBFi19VUFKVDOQfozc=
gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20200902074654-038fdea0a05b h1:QRR6H1YWRnHb4Y/HeNFCTJLFVxaq6wH4YuVdsUOr75U= gopkg.in/check.v1 v1.0.0-20200902074654-038fdea0a05b h1:QRR6H1YWRnHb4Y/HeNFCTJLFVxaq6wH4YuVdsUOr75U=
gopkg.in/check.v1 v1.0.0-20200902074654-038fdea0a05b/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20200902074654-038fdea0a05b/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=

View File

@ -8,15 +8,14 @@ import (
// GitBranch is set by the CI build process to the name of the branch // GitBranch is set by the CI build process to the name of the branch
//nolint:gochecknoglobals // This is filled in by the build system //nolint:gochecknoglobals // This is filled in by the build system
var GitBranch string var GitBranch string = "local"
// GitCommit is set by the CI build process to the commit hash // GitCommit is set by the CI build process to the commit hash
//nolint:gochecknoglobals // This is filled in by the build system //nolint:gochecknoglobals // This is filled in by the build system
var GitCommit string var GitCommit string = "build"
func main() { func main() {
log.SetFlags(log.Lshortfile) log.SetFlags(log.Lshortfile)
log.Println("OpenDiablo2 - Open source Diablo 2 engine")
instance := d2app.Create(GitBranch, GitCommit) instance := d2app.Create(GitBranch, GitCommit)