diff options
| author | oy <Tom_Adams@web.de> | 2011-04-13 20:37:12 +0200 |
|---|---|---|
| committer | oy <Tom_Adams@web.de> | 2011-04-13 20:37:12 +0200 |
| commit | 06115dd49dca2f8eb5f14606437e8fd20037cc4d (patch) | |
| tree | 5ec4bca6158319b3f5285d7689c5f94ae8da8c93 | |
| parent | 63e059b8fff6498e42b765a1dca000e53005ea77 (diff) | |
| download | zcatch-06115dd49dca2f8eb5f14606437e8fd20037cc4d.tar.gz zcatch-06115dd49dca2f8eb5f14606437e8fd20037cc4d.zip | |
added "Whitespace and line Endings cleanup" by GreYFoX
187 files changed, 3520 insertions, 3520 deletions
diff --git a/bam.lua b/bam.lua index 0c953e84..0c7c2f78 100644 --- a/bam.lua +++ b/bam.lua @@ -23,17 +23,17 @@ end function CHash(output, ...) local inputs = TableFlatten({...}) - + output = Path(output) - + -- compile all the files local cmd = Script("scripts/cmd5.py") .. " " for index, inname in ipairs(inputs) do - cmd = cmd .. Path(inname) .. " " + cmd = cmd .. Path(inname) .. " " end - + cmd = cmd .. " > " .. output - + AddJob(output, "cmd5 " .. output, cmd) for index, inname in ipairs(inputs) do AddDependency(output, inname) @@ -73,7 +73,7 @@ function Dat2c(datafile, sourcefile, arrayname) AddJob( sourcefile, "dat2c " .. PathFilename(sourcefile) .. " = " .. PathFilename(datafile), - Script("scripts/dat2c.py").. "\" " .. sourcefile .. " " .. datafile .. " " .. arrayname + Script("scripts/dat2c.py").. "\" " .. sourcefile .. " " .. datafile .. " " .. arrayname ) AddDependency(sourcefile, datafile) return sourcefile @@ -85,7 +85,7 @@ function ContentCompile(action, output) output, action .. " > " .. output, --Script("datasrc/compile.py") .. "\" ".. Path(output) .. " " .. action - Script("datasrc/compile.py") .. " " .. action .. " > " .. Path(output) + Script("datasrc/compile.py") .. " " .. action .. " > " .. Path(output) ) AddDependency(output, Path("datasrc/content.py")) -- do this more proper AddDependency(output, Path("datasrc/network.py")) @@ -150,7 +150,7 @@ function build(settings) settings.cc.includes:Add("src") if family == "unix" then - if platform == "macosx" then + if platform == "macosx" then settings.link.frameworks:Add("Carbon") settings.link.frameworks:Add("AppKit") else @@ -163,7 +163,7 @@ function build(settings) settings.link.libs:Add("ole32") settings.link.libs:Add("shell32") end - + -- compile zlib if needed if config.zlib.value == 1 then settings.link.libs:Add("z") @@ -179,7 +179,7 @@ function build(settings) -- build the small libraries wavpack = Compile(settings, Collect("src/engine/external/wavpack/*.c")) pnglite = Compile(settings, Collect("src/engine/external/pnglite/*.c")) - + -- build game components engine_settings = settings:Copy() server_settings = engine_settings:Copy() @@ -187,18 +187,18 @@ function build(settings) launcher_settings = engine_settings:Copy() if family == "unix" then - if platform == "macosx" then + if platform == "macosx" then client_settings.link.frameworks:Add("OpenGL") - client_settings.link.frameworks:Add("AGL") - client_settings.link.frameworks:Add("Carbon") - client_settings.link.frameworks:Add("Cocoa") - launcher_settings.link.frameworks:Add("Cocoa") + client_settings.link.frameworks:Add("AGL") + client_settings.link.frameworks:Add("Carbon") + client_settings.link.frameworks:Add("Cocoa") + launcher_settings.link.frameworks:Add("Cocoa") else client_settings.link.libs:Add("X11") client_settings.link.libs:Add("GL") client_settings.link.libs:Add("GLU") end - + elseif family == "windows" then client_settings.link.libs:Add("opengl32") client_settings.link.libs:Add("glu32") @@ -209,11 +209,11 @@ function build(settings) config.sdl:Apply(client_settings) -- apply freetype settings config.freetype:Apply(client_settings) - + engine = Compile(engine_settings, Collect("src/engine/shared/*.cpp", "src/base/*.c")) client = Compile(client_settings, Collect("src/engine/client/*.cpp")) server = Compile(server_settings, Collect("src/engine/server/*.cpp")) - + versionserver = Compile(settings, Collect("src/versionsrv/*.cpp")) masterserver = Compile(settings, Collect("src/mastersrv/*.cpp")) game_shared = Compile(settings, Collect("src/game/*.cpp"), nethash, network_source) @@ -230,13 +230,13 @@ function build(settings) client_osxlaunch = Compile(client_settings, "src/osxlaunch/client.m") server_osxlaunch = Compile(launcher_settings, "src/osxlaunch/server.m") end - + tools = {} for i,v in ipairs(tools_src) do toolname = PathFilename(PathBase(v)) tools[i] = Link(settings, toolname, Compile(settings, v), engine, zlib, pnglite) end - + -- build client, server, version server and master server client_exe = Link(client_settings, "teeworlds", game_shared, game_client, engine, client, game_editor, zlib, pnglite, wavpack, @@ -249,7 +249,7 @@ function build(settings) if platform == "macosx" then serverlaunch = Link(launcher_settings, "serverlaunch", server_osxlaunch) end - + versionserver_exe = Link(server_settings, "versionsrv", versionserver, engine, zlib) @@ -284,7 +284,7 @@ release_settings.debug = 0 release_settings.optimize = 1 release_settings.cc.defines:Add("CONF_RELEASE") -if platform == "macosx" and arch == "ia32" then +if platform == "macosx" and arch == "ia32" then debug_settings_ppc = debug_settings:Copy() debug_settings_ppc.config_name = "debug_ppc" debug_settings_ppc.config_ext = "_ppc_d" diff --git a/configure.lua b/configure.lua index b96c629d..26825b06 100644 --- a/configure.lua +++ b/configure.lua @@ -10,12 +10,12 @@ function NewConfig(on_configured_callback) config.OnConfigured = function(self) return true end - + if on_configured_callback then config.OnConfigured = on_configured_callback end - + config.options = {} config.settings = NewSettings() - + config.NewSettings = function(self) local s = NewSettings() for _,v in pairs(self.options) do @@ -28,25 +28,25 @@ function NewConfig(on_configured_callback) table.insert(self.options, o) self[o.name] = o end - + config.Print = function(self) for k,v in pairs(self.options) do print(v:FormatDisplay()) end end - + config.Save = function(self, filename) print("saved configuration to '"..filename.."'") local file = io.open(filename, "w") - + -- Define a little helper function to save options local saver = {} saver.file = file - + saver.line = function(self, str) self.file:write(str .. "\n") end - + saver.option = function(self, option, name) local valuestr = "no" if type(option[name]) == type(0) then @@ -64,30 +64,30 @@ function NewConfig(on_configured_callback) self.file:write(option.name.."."..name.." = ".. valuestr.."\n") end - -- Save all the options + -- Save all the options for k,v in pairs(self.options) do v:Save(saver) end file:close() end - + config.Load = function(self, filename) local options_func = loadfile(filename) local options_table = {} - + if not options_func then print("auto configuration") self:Config(filename) options_func = loadfile(filename) end - + if options_func then -- Setup the options tables for k,v in pairs(self.options) do options_table[v.name] = {} end setfenv(options_func, options_table) - + -- this is to make sure that we get nice error messages when -- someone sets an option that isn't valid. local mt = {} @@ -96,8 +96,8 @@ function NewConfig(on_configured_callback) if v ~= nil then return v end error("there is no configuration option named '" .. key .. "'") end - - setmetatable(options_table, mt) + + setmetatable(options_table, mt) -- Process the options options_func() @@ -117,10 +117,10 @@ function NewConfig(on_configured_callback) print("run 'bam config' to generate") print("run 'bam config help' for configuration options") print("") - os.exit(1) + os.exit(1) end end - + config.Config = function(self, filename) print("") print("configuration:") @@ -140,7 +140,7 @@ function NewConfig(on_configured_callback) end print("") end - + end config.Autodetect = function(self) @@ -159,7 +159,7 @@ function NewConfig(on_configured_callback) end end end - + config.Finalize = function(self, filename) if _bam_targets[0] == "config" then if _bam_targets[1] == "help" then @@ -171,11 +171,11 @@ function NewConfig(on_configured_callback) os.exit(0) end - + self:Load(filename) bam_update_globalstamp(filename) end - + return config end @@ -214,10 +214,10 @@ function MakeOption(name, value, check, save, display, printhelp) o.auto_detected = true o.FormatDisplay = function(self) local a = "SET" - if self.auto_detected then a = "AUTO" end + if self.auto_detected then a = "AUTO" end return string.format("%-5s %-20s %s", a, self.name, self:Display()) end - + o.Display = display o.PrintHelp = printhelp if o.Display == nil then o.Display = DefaultOptionDisplay end @@ -244,16 +244,16 @@ function OptTestCompileC(name, source, compileoptions, desc) end end end - + local save = function(option, output) output:option(option, "value") end - + local printhelp = function(option) print("\t"..option.name.."=on|off") if option.desc then print("\t\t"..option.desc) end end - + local o = MakeOption(name, false, check, save, nil, printhelp) o.desc = desc o.source = source @@ -275,16 +275,16 @@ function OptToggle(name, default_value, desc) end end end - + local save = function(option, output) output:option(option, "value") end - + local printhelp = function(option) print("\t"..option.name.."=on|off") if option.desc then print("\t\t"..option.desc) end end - + local o = MakeOption(name, default_value, check, save, nil, printhelp) o.desc = desc return o @@ -297,16 +297,16 @@ function OptInteger(name, default_value, desc) option.value = tonumber(ScriptArgs[option.name]) end end - + local save = function(option, output) output:option(option, "value") end - + local printhelp = function(option) print("\t"..option.name.."=N") if option.desc then print("\t\t"..option.desc) end end - + local o = MakeOption(name, default_value, check, save, nil, printhelp) o.desc = desc return o @@ -320,16 +320,16 @@ function OptString(name, default_value, desc) option.value = ScriptArgs[option.name] end end - + local save = function(option, output) output:option(option, "value") end - + local printhelp = function(option) print("\t"..option.name.."=STRING") if option.desc then print("\t\t"..option.desc) end end - + local o = MakeOption(name, default_value, check, save, nil, printhelp) o.desc = desc return o @@ -354,7 +354,7 @@ function OptCCompiler(name, default_driver, default_c, default_cxx, desc) if ScriptArgs[option.name..".cxx"] then option.cxx_compiler = ScriptArgs[option.name..".cxx"] end - + option.auto_detected = false elseif option.driver then -- no need todo anything if we have a driver @@ -379,11 +379,11 @@ function OptCCompiler(name, default_driver, default_c, default_cxx, desc) else error(option.driver.." is not a known c/c++ compile driver") end - + if option.c_compiler then settings.cc.c_compiler = option.c_compiler end if option.cxx_compiler then settings.cc.cxx_compiler = option.cxx_compiler end end - + local save = function(option, output) output:option(option, "driver") output:option(option, "c_compiler") @@ -407,7 +407,7 @@ function OptCCompiler(name, default_driver, default_c, default_cxx, desc) if option.cxx_compiler then s = s .. " cxx="..option.cxx_compiler end return s end - + local o = MakeOption(name, nil, check, save, display, printhelp) o.desc = desc o.driver = false @@ -430,7 +430,7 @@ function OptLibrary(name, header, desc) local check = function(option, settings) option.value = false option.include_path = false - + local function check_compile_include(filename, paths) if CTestCompile(settings, "#include <" .. filename .. ">\nint main(){return 0;}", "") then return "" @@ -441,7 +441,7 @@ function OptLibrary(name, header, desc) return v end end - + return false end @@ -468,12 +468,12 @@ function OptLibrary(name, header, desc) end end end - + local save = function(option, output) output:option(option, "value") output:option(option, "include_path") end - + local display = function(option) if option.value then if option.include_path then @@ -490,7 +490,7 @@ function OptLibrary(name, header, desc) print("\t"..option.name.."=disable|system|PATH") if option.desc then print("\t\t"..option.desc) end end - + local o = MakeOption(name, false, check, save, display, printhelp) o.include_path = false o.header = header diff --git a/datasrc/compile.py b/datasrc/compile.py index 0ae3bbc7..e8901c48 100644 --- a/datasrc/compile.py +++ b/datasrc/compile.py @@ -21,7 +21,7 @@ def create_flags_table(names): i += 1 lines += ["};"] return lines - + def EmitEnum(names, num): print("enum") print("{") @@ -92,11 +92,11 @@ if gen_client_content_source or gen_server_content_source: # NETWORK if gen_network_header: - + print("#ifndef GAME_GENERATED_PROTOCOL_H") print("#define GAME_GENERATED_PROTOCOL_H") print(network.RawHeader) - + for e in network.Enums: for l in create_enum_table(["%s_%s"%(e.name, v) for v in e.values], 'NUM_%sS'%e.name): print(l) print("") @@ -104,17 +104,17 @@ if gen_network_header: for e in network.Flags: for l in create_flags_table(["%s_%s" % (e.name, v) for v in e.values]): print(l) print("") - + for l in create_enum_table(["NETOBJ_INVALID"]+[o.enum_name for o in network.Objects], "NUM_NETOBJTYPES"): print(l) print("") for l in create_enum_table(["NETMSG_INVALID"]+[o.enum_name for o in network.Messages], "NUM_NETMSGTYPES"): print(l) print("") - + for item in network.Objects + network.Messages: for line in item.emit_declaration(): print(line) print("") - + EmitEnum(["SOUND_%s"%i.name.value.upper() for i in content.container.sounds.items], "NUM_SOUNDS") EmitEnum(["WEAPON_%s"%i.name.value.upper() for i in content.container.weapons.id.items], "NUM_WEAPONS") @@ -127,11 +127,11 @@ class CNetObjHandler char m_aMsgData[1024]; int m_NumObjCorrections; int ClampInt(const char *pErrorMsg, int Value, int Min, int Max); - + static const char *ms_apObjNames[]; static int ms_aObjSizes[]; static const char *ms_apMsgNames[]; - + public: CNetObjHandler(); @@ -140,7 +140,7 @@ public: int GetObjSize(int Type); int NumObjCorrections(); const char *CorrectedObjOn(); - + const char *GetMsgName(int Type); void *SecureUnpackMsg(int Type, CUnpacker *pUnpacker); const char *FailedMsgOn(); @@ -149,16 +149,16 @@ public: """) print("#endif // GAME_GENERATED_PROTOCOL_H") - + if gen_network_source: # create names lines = [] - + lines += ['#include <engine/shared/protocol.h>'] lines += ['#include <engine/message.h>'] lines += ['#include "protocol.h"'] - + lines += ['CNetObjHandler::CNetObjHandler()'] lines += ['{'] lines += ['\tm_pMsgFailedOn = "";'] @@ -202,7 +202,7 @@ if gen_network_source: lines += ['\t""'] lines += ['};'] lines += [''] - + lines += ['const char *CNetObjHandler::GetObjName(int Type)'] lines += ['{'] lines += ['\tif(Type < 0 || Type >= NUM_NETOBJTYPES) return "(out of range)";'] @@ -216,16 +216,16 @@ if gen_network_source: lines += ['\treturn ms_aObjSizes[Type];'] lines += ['};'] lines += [''] - - + + lines += ['const char *CNetObjHandler::GetMsgName(int Type)'] lines += ['{'] lines += ['\tif(Type < 0 || Type >= NUM_NETMSGTYPES) return "(out of range)";'] lines += ['\treturn ms_apMsgNames[Type];'] lines += ['};'] lines += [''] - - + + for l in lines: print(l) @@ -255,7 +255,7 @@ if gen_network_source: lines += ['{'] lines += ['\tswitch(Type)'] lines += ['\t{'] - + for item in network.Objects: for line in item.emit_validate(): lines += ["\t" + line] @@ -264,9 +264,9 @@ if gen_network_source: lines += ['\treturn -1;'] lines += ['};'] lines += [''] - - #int Validate(int Type, void *pData, int Size); - + + #int Validate(int Type, void *pData, int Size); + if 0: for item in network.Messages: for line in item.emit_unpack(): @@ -281,20 +281,20 @@ if gen_network_source: lines += ['\tsecure_unpack_%s,' % msg.name] lines += ['\t0x0'] lines += ['};'] - + # lines += ['void *CNetObjHandler::SecureUnpackMsg(int Type, CUnpacker *pUnpacker)'] lines += ['{'] lines += ['\tm_pMsgFailedOn = 0;'] lines += ['\tswitch(Type)'] lines += ['\t{'] - - + + for item in network.Messages: for line in item.emit_unpack(): lines += ["\t" + line] lines += ['\t'] - + lines += ['\tdefault:'] lines += ['\t\tm_pMsgFailedOn = "(type out of range)";'] lines += ['\t\tbreak;'] @@ -313,6 +313,6 @@ if gen_network_source: for l in lines: print(l) - + if gen_client_content_header or gen_server_content_header: print("#endif") diff --git a/datasrc/content.py b/datasrc/content.py index 1dfa7aea..e714e8b8 100644 --- a/datasrc/content.py +++ b/datasrc/content.py @@ -22,7 +22,7 @@ class Image(Struct): self.name = String(name) self.filename = String(filename) self.id = Int(-1) - + class SpriteSet(Struct): def __init__(self, name="", image=None, gridx=0, gridy=0): Struct.__init__(self, "SPRITESET") @@ -78,7 +78,7 @@ class WeaponSpec(Struct): self.sprite_proj = Pointer(Sprite, Sprite()) self.sprite_muzzles = Array(Pointer(Sprite, Sprite())) self.visual_size = Int(96) - + self.firedelay = Int(500) self.maxammo = Int(10) self.ammoregentime = Int(0) @@ -111,7 +111,7 @@ class Weapon_Gun(Struct): self.curvature = Float(1.25) self.speed = Float(2200) self.lifetime = Float(2.0) - + class Weapon_Shotgun(Struct): def __init__(self): Struct.__init__(self, "WEAPONSPEC_SHOTGUN") @@ -119,7 +119,7 @@ class Weapon_Shotgun(Struct): self.curvature = Float(1.25) self.speed = Float(2200) self.speeddiff = Float(0.8) - self.lifetime = Float(0.25) + self.lifetime = Float(0.25) class Weapon_Grenade(Struct): def __init__(self): @@ -137,7 +137,7 @@ class Weapon_Rifle(Struct): self.bounce_delay = Int(150) self.bounce_num = Int(1) self.bounce_cost = Float(0) - + class Weapon_Ninja(Struct): def __init__(self): Struct.__init__(self, "WEAPONSPEC_NINJA") @@ -190,7 +190,7 @@ container.sounds.Add(SoundSet("player_pain_long", FileList("audio/vo_teefault_pa container.sounds.Add(SoundSet("body_land", FileList("audio/foley_land-%02d.wv", 4))) container.sounds.Add(SoundSet("player_airjump", FileList("audio/foley_dbljump-%02d.wv", 3))) -container.sounds.Add(SoundSet("player_jump", FileList("audio/foley_foot_left-%02d.wv", 4) + FileList("audio/foley_foot_right-%02d.wv", 4))) +container.sounds.Add(SoundSet("player_jump", FileList("audio/foley_foot_left-%02d.wv", 4) + FileList("audio/foley_foot_right-%02d.wv", 4))) container.sounds.Add(SoundSet("player_die", FileList("audio/foley_body_splat-%02d.wv", 3))) container.sounds.Add(SoundSet("player_spawn", FileList("audio/vo_teefault_spawn-%02d.wv", 7))) container.sounds.Add(SoundSet("player_skid", FileList("audio/sfx_skid-%02d.wv", 4))) @@ -292,7 +292,7 @@ container.sprites.Add(Sprite("armor_empty", set_game, 23,2,2,2)) container.sprites.Add(Sprite("star1", set_game, 15,0,2,2)) container.sprites.Add(Sprite("star2", set_game, 17,0,2,2)) container.sprites.Add(Sprite("star3", set_game, 19,0,2,2)) - + container.sprites.Add(Sprite("part1", set_game, 6,0,1,1)) container.sprites.Add(Sprite("part2", set_game, 6,1,1,1)) container.sprites.Add(Sprite("part3", set_game, 7,0,1,1)) @@ -425,35 +425,35 @@ anim.body.frames.Add(AnimKeyframe(0.6, 0, 0, 0)) anim.body.frames.Add(AnimKeyframe(0.8, 0,-1, 0)) anim.body.frames.Add(AnimKeyframe(1.0, 0, 0, 0)) -anim.back_foot.frames.Add(AnimKeyframe(0.0, 8, 0, 0)) +anim.back_foot.frames.Add(AnimKeyframe(0.0, 8, 0, 0)) anim.back_foot.frames.Add(AnimKeyframe(0.2, -8, 0, 0)) anim.back_foot.frames.Add(AnimKeyframe(0.4,-10,-4, 0.2)) anim.back_foot.frames.Add(AnimKeyframe(0.6, -8,-8, 0.3)) -anim.back_foot.frames.Add(AnimKeyframe(0.8, 4,-4,-0.2)) -anim.back_foot.frames.Add(AnimKeyframe(1.0, 8, 0, 0)) +anim.back_foot.frames.Add(AnimKeyframe(0.8, 4,-4,-0.2)) +anim.back_foot.frames.Add(AnimKeyframe(1.0, 8, 0, 0)) anim.front_foot.frames.Add(AnimKeyframe(0.0,-10,-4, 0.2)) anim.front_foot.frames.Add(AnimKeyframe(0.2, -8,-8, 0.3)) -anim.front_foot.frames.Add(AnimKeyframe(0.4, 4,-4,-0.2)) -anim.front_foot.frames.Add(AnimKeyframe(0.6, 8, 0, 0)) -anim.front_foot.frames.Add(AnimKeyframe(0.8, 8, 0, 0)) +anim.front_foot.frames.Add(AnimKeyframe(0.4, 4,-4,-0.2)) +anim.front_foot.frames.Add(AnimKeyframe(0.6, 8, 0, 0)) +anim.front_foot.frames.Add(AnimKeyframe(0.8, 8, 0, 0)) anim.front_foot.frames.Add(AnimKeyframe(1.0,-10,-4, 0.2)) container.animations.Add(anim) anim = Animation("hammer_swing") anim.attach.frames.Add(AnimKeyframe(0.0, 0, 0, -0.10)) -anim.attach.frames.Add(AnimKeyframe(0.3, 0, 0, 0.25)) -anim.attach.frames.Add(AnimKeyframe(0.4, 0, 0, 0.30)) -anim.attach.frames.Add(AnimKeyframe(0.5, 0, 0, 0.25)) +anim.attach.frames.Add(AnimKeyframe(0.3, 0, 0, 0.25)) +anim.attach.frames.Add(AnimKeyframe(0.4, 0, 0, 0.30)) +anim.attach.frames.Add(AnimKeyframe(0.5, 0, 0, 0.25)) anim.attach.frames.Add(AnimKeyframe(1.0, 0, 0, -0.10)) container.animations.Add(anim) - + anim = Animation("ninja_swing") anim.attach.frames.Add(AnimKeyframe(0.00, 0, 0, -0.25)) anim.attach.frames.Add(AnimKeyframe(0.10, 0, 0, -0.05)) -anim.attach.frames.Add(AnimKeyframe(0.15, 0, 0, 0.35)) -anim.attach.frames.Add(AnimKeyframe(0.42, 0, 0, 0.40)) -anim.attach.frames.Add(AnimKeyframe(0.50, 0, 0, 0.35)) +anim.attach.frames.Add(AnimKeyframe(0.15, 0, 0, 0.35)) +anim.attach.frames.Add(AnimKeyframe(0.42, 0, 0, 0.40)) +anim.attach.frames.Add(AnimKeyframe(0.50, 0, 0, 0.35)) anim.attach.frames.Add(AnimKeyframe(1.00, 0, 0, -0.25)) container.animations.Add(anim) diff --git a/datasrc/datatypes.py b/datasrc/datatypes.py index ddb3c9e3..73719f59 100644 --- a/datasrc/datatypes.py +++ b/datasrc/datatypes.py @@ -21,7 +21,7 @@ def FixCasing(Str): else: NewStr += c.lower() return NewStr - + def FormatName(type, name): if "*" in type: return "m_p" + FixCasing(name) @@ -34,12 +34,12 @@ class BaseType: self._type_name = type_name self._target_name = "INVALID" self._id = GetID() # this is used to remember what order the members have in structures etc - + def Identifyer(self): return "x"+str(self._id) def TargetName(self): return self._target_name def TypeName(self): return self._type_name def ID(self): return self._id; - + def EmitDeclaration(self, name): return ["%s %s;"%(self.TypeName(), FormatName(self.TypeName(), name))] def EmitPreDefinition(self, target_name): @@ -52,7 +52,7 @@ class MemberType: def __init__(self, name, var): self.name = name self.var = var - + class Struct(BaseType): def __init__(self, type_name): BaseType.__init__(self, type_name) @@ -71,7 +71,7 @@ class Struct(BaseType): print(v.name, v.var) sys.exit(-1) return m - + def EmitTypeDeclaration(self, name): lines = [] lines += ["struct " + self.TypeName()] @@ -93,7 +93,7 @@ class Struct(BaseType): lines += ["\t" + " ".join(member.var.EmitDefinition("")) + ","] lines += ["}"] return lines - + class Array(BaseType): def __init__(self, type): BaseType.__init__(self, type.TypeName()) @@ -114,7 +114,7 @@ class Array(BaseType): for item in self.items: lines += item.EmitPreDefinition("%s[%d]"%(self.Identifyer(), i)) i += 1 - + if len(self.items): lines += ["static %s %s[] = {"%(self.TypeName(), self.Identifyer())] for item in self.items: @@ -123,7 +123,7 @@ class Array(BaseType): lines += ["};"] else: lines += ["static %s *%s = 0;"%(self.TypeName(), self.Identifyer())] - + return lines def EmitDefinition(self, name): return [str(len(self.items))+","+self.Identifyer()] @@ -139,7 +139,7 @@ class Int(BaseType): def EmitDefinition(self, name): return ["%d"%self.value] #return ["%d /* %s */"%(self.value, self._target_name)] - + class Float(BaseType): def __init__(self, value): BaseType.__init__(self, "float") @@ -149,7 +149,7 @@ class Float(BaseType): def EmitDefinition(self, name): return ["%f"%self.value] #return ["%d /* %s */"%(self.value, self._target_name)] - + class String(BaseType): def __init__(self, value): BaseType.__init__(self, "const char*") @@ -158,7 +158,7 @@ class String(BaseType): self.value = value def EmitDefinition(self, name): return ['"'+self.value+'"'] - + class Pointer(BaseType): def __init__(self, type, target): BaseType.__init__(self, "%s*"%type().TypeName()) @@ -227,7 +227,7 @@ class NetObject: lines += ["\treturn 0;"] lines += ["}"] return lines - + class NetEvent(NetObject): def __init__(self, name, variables): @@ -265,12 +265,12 @@ class NetMessage(NetObject): extra += ["\t\t"+line for line in v.emit_pack()] extra += ["\t\treturn pPacker->Error() != 0;"] extra += ["\t}"] - - + + lines = NetObject.emit_declaration(self) lines = lines[:-1] + extra + lines[-1:] return lines - + class NetVariable: def __init__(self, name): diff --git a/src/base/detect.h b/src/base/detect.h index 534339dd..0b66acef 100644 --- a/src/base/detect.h +++ b/src/base/detect.h @@ -4,8 +4,8 @@ #define BASE_DETECT_H /* - this file detected the family, platform and architecture - to compile for. + this file detected the family, platform and architecture + to compile for. */ /* platforms */ diff --git a/src/base/system.c b/src/base/system.c index 0c208b9b..94481f21 100644 --- a/src/base/system.c +++ b/src/base/system.c @@ -21,20 +21,20 @@ #include <sys/socket.h> #include <sys/ioctl.h> #include <errno.h> - #include <netdb.h> + #include <netdb.h> #include <netinet/in.h> #include <fcntl.h> #include <pthread.h> #include <arpa/inet.h> #include <dirent.h> - + #if defined(CONF_PLATFORM_MACOSX) #include <Carbon/Carbon.h> #endif - + #elif defined(CONF_FAMILY_WINDOWS) - #define WIN32_LEAN_AND_MEAN + #define WIN32_LEAN_AND_MEAN #define _WIN32_WINNT 0x0501 /* required for mingw to get getaddrinfo to work */ #include <windows.h> #include <winsock2.h> @@ -176,7 +176,7 @@ void *mem_alloc_debug(const char *filename, int line, unsigned size, unsigned al memory_stats.allocated += header->size; memory_stats.total_allocations++; memory_stats.active_allocations++; - + tail->guard = MEM_GUARD_VAL; header->prev = (MEMHEADER *)0; @@ -184,7 +184,7 @@ void *mem_alloc_debug(const char *filename, int line, unsigned size, unsigned al if(first) first->prev = header; first = header; - + /*dbg_msg("mem", "++ %p", header+1); */ return header+1; } @@ -195,20 +195,20 @@ void mem_free(void *p) { MEMHEADER *header = (MEMHEADER *)p - 1; MEMTAIL *tail = (MEMTAIL *)(((char*)(header+1))+header->size); - + if(tail->guard != MEM_GUARD_VAL) dbg_msg("mem", "!! %p", p); /* dbg_msg("mem", "-- %p", p); */ memory_stats.allocated -= header->size; memory_stats.active_allocations--; - + if(header->prev) header->prev->next = header->next; else first = header->next; if(header->next) header->next->prev = header->prev; - + free(header); } } @@ -219,7 +219,7 @@ void mem_debug_dump(IOHANDLE file) MEMHEADER *header = first; if(!file) file = io_open("memory.txt", IOFLAG_WRITE); - + if(file) { while(header) @@ -228,7 +228,7 @@ void mem_debug_dump(IOHANDLE file) io_write(file, buf, strlen(buf)); header = header->next; } - + io_close(file); } } @@ -275,7 +275,7 @@ IOHANDLE io_open(const char *filename, int flags) WIN32_FIND_DATA finddata; HANDLE handle; int length; - + length = str_length(filename); if(!filename || !length || filename[length-1] == '\\') return 0x0; @@ -630,9 +630,9 @@ int net_host_lookup(const char *hostname, NETADDR *addr, int types) /* dbg_msg("host lookup", "host='%s' port=%d %d", host, port, types); */ - + mem_zero(&hints, sizeof(hints)); - + hints.ai_family = AF_UNSPEC; if(types == NETTYPE_IPV4) @@ -655,8 +655,8 @@ static int parse_int(int *out, const char **str) int i = 0; *out = 0; if(**str < '0' || **str > '9') - return -1; - + return -1; + i = **str - '0'; (*str)++; @@ -665,9 +665,9 @@ static int parse_int(int *out, const char **str) if(**str < '0' || **str > '9') { *out = i; - return 0; + return 0; } - + i = (i*10) + (**str - '0'); (*str)++; } @@ -704,7 +704,7 @@ int net_addr_from_str(NETADDR *addr, const char *string) { const char *str = string; mem_zero(addr, sizeof(NETADDR)); - + if(str[0] == '[') { /* ipv6 */ @@ -760,10 +760,10 @@ int net_addr_from_str(NETADDR *addr, const char *string) str++; if(parse_uint16(&addr->port, &str)) return -1; } - + addr->type = NETTYPE_IPV4; } - + return 0; } @@ -825,7 +825,7 @@ static int priv_net_create_socket(int domain, int type, struct sockaddr *addr, i priv_net_close_socket(sock); return -1; } - + /* set non-blocking */ #if defined(CONF_FAMILY_WINDOWS) ioctlsocket(sock, FIONBIO, &mode); @@ -835,7 +835,7 @@ static int priv_net_create_socket(int domain, int type, struct sockaddr *addr, i /* set boardcast */ setsockopt(sock, SOL_SOCKET, SO_BROADCAST, (const char*)&broadcast, sizeof(broadcast)); - + /* return the newly created socket */ return sock; } @@ -937,7 +937,7 @@ int net_udp_send(NETSOCKET sock, const NETADDR *addr, const void *data, int size { char addrstr[256]; net_addr_str(addr, addrstr, sizeof(addrstr)); - + dbg_msg("net", "sendto error (%d '%s')", errno, strerror(errno)); dbg_msg("net", "\tsock = %d %x", sock, sock); dbg_msg("net", "\tsize = %d %x", size, size); @@ -1005,8 +1005,8 @@ NETSOCKET net_tcp_create(const NETADDR *a) bind(sock.ipv4sock, (struct sockaddr *)&addr, sizeof(addr)); } - /* return */ - return sock; + /* return */ + return sock; } int net_tcp_set_non_blocking(NETSOCKET sock) @@ -1122,7 +1122,7 @@ int net_tcp_connect_non_blocking(NETSOCKET sock, const NETADDR *a) /* netaddr_to_sockaddr(a, &addr); net_tcp_set_non_blocking(sock); - res = connect(sock, &addr, sizeof(addr)); + res = connect(sock, &addr, sizeof(addr)); net_tcp_set_blocking(sock); */ @@ -1206,7 +1206,7 @@ int fs_listdir(const char *dir, FS_LISTDIR_CALLBACK cb, int type, void *user) if(!d) return 0; - + str_format(buffer, sizeof(buffer), "%s/", dir); length = str_length(buffer); @@ -1246,7 +1246,7 @@ int fs_storage_path(const char *appname, char *path, int max) for(i = strlen(home)+2; path[i]; i++) path[i] = tolower(path[i]); #endif - + return 0; #endif } @@ -1286,7 +1286,7 @@ int fs_is_dir(const char *path) struct stat sb; if (stat(path, &sb) == -1) return 0; - + if (S_ISDIR(sb.st_mode)) return 1; else @@ -1326,7 +1326,7 @@ int fs_parent_dir(char *path) if(*path == '/' || *path == '\\') parent = path; } - + if(parent) { *parent = 0; @@ -1377,16 +1377,16 @@ void swap_endian(void *data, unsigned elem_size, unsigned num) int net_socket_read_wait(NETSOCKET sock, int time) { - struct timeval tv; - fd_set readfds; + struct timeval tv; + fd_set readfds; int sockid; - tv.tv_sec = 0; - tv.tv_usec = 1000*time; + tv.tv_sec = 0; + tv.tv_usec = 1000*time; sockid = 0; - FD_ZERO(&readfds); - if(sock.ipv4sock >= 0) + FD_ZERO(&readfds); + if(sock.ipv4sock >= 0) { FD_SET(sock.ipv4sock, &readfds); sockid = sock.ipv4sock; @@ -1398,8 +1398,8 @@ int net_socket_read_wait(NETSOCKET sock, int time) sockid = sock.ipv6sock; } - /* don't care about writefds and exceptfds */ - select(sockid+1, &readfds, NULL, NULL, &tv); + /* don't care about writefds and exceptfds */ + select(sockid+1, &readfds, NULL, NULL, &tv); if(sock.ipv4sock >= 0 && FD_ISSET(sock.ipv4sock, &readfds)) return 1; @@ -1407,7 +1407,7 @@ int net_socket_read_wait(NETSOCKET sock, int time) if(sock.ipv6sock >= 0 && FD_ISSET(sock.ipv6sock, &readfds)) return 1; - return 0; + return 0; } unsigned time_timestamp() @@ -1427,7 +1427,7 @@ void str_append(char *dst, const char *src, int dst_size) s++; i++; } - + dst[dst_size-1] = 0; /* assure null termination */ } @@ -1448,12 +1448,12 @@ void str_format(char *buffer, int buffer_size, const char *format, ...) va_list ap; va_start(ap, format); _vsnprintf(buffer, buffer_size, format, ap); - va_end(ap); + va_end(ap); #else va_list ap; va_start(ap, format); vsnprintf(buffer, buffer_size, format, ap); - va_end(ap); + va_end(ap); #endif buffer[buffer_size-1] = 0; /* assure null termination */ @@ -1578,7 +1578,7 @@ const char *str_find_nocase(const char *haystack, const char *needle) return haystack; haystack++; } - + return 0; } @@ -1598,7 +1598,7 @@ const char *str_find(const char *haystack, const char *needle) return haystack; haystack++; } - + return 0; } @@ -1620,7 +1620,7 @@ void str_timestamp(char *buffer, int buffer_size) { time_t time_data; struct tm *time_info; - + time(&time_data); time_info = localtime(&time_data); strftime(buffer, buffer_size, "%Y-%m-%d_%H-%M-%S", time_info); @@ -1700,7 +1700,7 @@ float str_tofloat(const char *str) { return atof(str); } static int str_utf8_isstart(char c) { - if((c&0xC0) == 0x80) /* 10xxxxxx */ + if((c&0xC0) == 0x80) /* 10xxxxxx */ return 0; return 1; } @@ -1721,7 +1721,7 @@ int str_utf8_forward(const char *str, int cursor) const char *buf = str + cursor; if(!buf[0]) return cursor; - + if((*buf&0x80) == 0x0) /* 0xxxxxxx */ return cursor+1; else if((*buf&0xE0) == 0xC0) /* 110xxxxx */ @@ -1742,7 +1742,7 @@ int str_utf8_forward(const char *str, int cursor) if(!buf[3]) return cursor+3; return cursor+4; } - + /* invalid */ return cursor+1; } @@ -1776,7 +1776,7 @@ int str_utf8_encode(char *ptr, int chr) ptr[3] = 0x80|(chr&0x3F); return 4; } - + return 0; } @@ -1784,7 +1784,7 @@ int str_utf8_decode(const char **ptr) { const char *buf = *ptr; int ch = 0; - + do { if((*buf&0x80) == 0x0) /* 0xxxxxxx */ @@ -1819,7 +1819,7 @@ int str_utf8_decode(const char **ptr) buf++; break; } - + *ptr = buf; return ch; } while(0); @@ -1827,7 +1827,7 @@ int str_utf8_decode(const char **ptr) /* out of bounds */ *ptr = buf; return -1; - + } int str_utf8_check(const char *str) @@ -1835,7 +1835,7 @@ int str_utf8_check(const char *str) while(*str) { if((*str&0x80) == 0x0) - str++; + str++; else if((*str&0xE0) == 0xC0 && (*(str+1)&0xC0) == 0x80) str += 2; else if((*str&0xF0) == 0xE0 && (*(str+1)&0xC0) == 0x80 && (*(str+2)&0xC0) == 0x80) diff --git a/src/base/system.h b/src/base/system.h index fea9e452..a486b89d 100644 --- a/src/base/system.h +++ b/src/base/system.h @@ -18,28 +18,28 @@ extern "C" { /* Function: dbg_assert Breaks into the debugger based on a test. - + Parameters: test - Result of the test. msg - Message that should be printed if the test fails. - + Remarks: Does nothing in release version of the library. - + See Also: <dbg_break> */ void dbg_assert(int test, const char *msg); -#define dbg_assert(test,msg) dbg_assert_imp(__FILE__, __LINE__, test, msg) +#define dbg_assert(test,msg) dbg_assert_imp(__FILE__, __LINE__, test, msg) void dbg_assert_imp(const char *filename, int line, int test, const char *msg); /* Function: dbg_break Breaks into the debugger. - + Remarks: Does nothing in release version of the library. - + See Also: <dbg_assert> */ @@ -47,16 +47,16 @@ void dbg_break(); /* Function: dbg_msg - + Prints a debug message. - + Parameters: sys - A string that describes what system the message belongs to fmt - A printf styled format string. - + Remarks: Does nothing in release version of the library. - + See Also: <dbg_assert> */ @@ -67,15 +67,15 @@ void dbg_msg(const char *sys, const char *fmt, ...); /* Function: mem_alloc Allocates memory. - + Parameters: size - Size of the needed block. alignment - Alignment for the block. - + Returns: Returns a pointer to the newly allocated block. Returns a null pointer if the memory couldn't be allocated. - + Remarks: - Passing 0 to size will allocated the smallest amount possible and return a unique pointer. @@ -89,12 +89,12 @@ void *mem_alloc_debug(const char *filename, int line, unsigned size, unsigned al /* Function: mem_free Frees a block allocated through <mem_alloc>. - + Remarks: - In the debug version of the library the function will assert if a non-valid block is passed, like a null pointer or a block that isn't allocated. - + See Also: <mem_alloc> */ @@ -103,16 +103,16 @@ void mem_free(void *block); /* Function: mem_copy Copies a a memory block. - + Parameters: dest - Destination. source - Source to copy. size - Size of the block to copy. - + Remarks: - This functions DOES NOT handles cases where source and destination is overlapping. - + See Also: <mem_move> */ @@ -121,16 +121,16 @@ void mem_copy(void *dest, const void *source, unsigned size); /* Function: mem_move Copies a a memory block - + Parameters: dest - Destination source - Source to copy size - Size of the block to copy - + Remarks: - This functions handles cases where source and destination is overlapping - + See Also: <mem_copy> */ @@ -139,7 +139,7 @@ void mem_move(void *dest, const void *source, unsigned size); /* Function: mem_zero Sets a complete memory block to 0 - + Parameters: block - Pointer to the block to zero out size - Size of the block @@ -149,12 +149,12 @@ void mem_zero(void *block, unsigned size); /* Function: mem_comp Compares two blocks of memory - + Parameters: a - First block of data b - Second block of data size - Size of the data to compare - + Returns: <0 - Block a is lesser then block b 0 - Block a is equal to block b @@ -168,7 +168,7 @@ int mem_comp(const void *a, const void *b, int size); Will trigger a assert if memory has failed. */ int mem_check_imp(); -#define mem_check() dbg_assert_imp(__FILE__, __LINE__, mem_check_imp(), "Memory check failed") +#define mem_check() dbg_assert_imp(__FILE__, __LINE__, mem_check_imp(), "Memory check failed") /* Group: File IO */ enum { @@ -205,7 +205,7 @@ IOHANDLE io_open(const char *filename, int flags); io - Handle to the file to read data from. buffer - Pointer to the buffer that will recive the data. size - Number of bytes to read from the file. - + Returns: Number of bytes read. @@ -215,11 +215,11 @@ unsigned io_read(IOHANDLE io, void *buffer, unsigned size); /* Function: io_skip Skips data in a file. - + Parameters: io - Handle to the file. size - Number of bytes to skip. - + Returns: Number of bytes skipped. */ @@ -228,12 +228,12 @@ unsigned io_skip(IOHANDLE io, int size); /* Function: io_write Writes data from a buffer to file. - + Parameters: io - Handle to the file. buffer - Pointer to the data that should be written. size - Number of bytes to write. - + Returns: Number of bytes written. */ @@ -242,12 +242,12 @@ unsigned io_write(IOHANDLE io, const void *buffer, unsigned size); /* Function: io_seek Seeks to a specified offset in the file. - + Parameters: io - Handle to the file. offset - Offset from pos to stop. origin - Position to start searching from. - + Returns: Returns 0 on success. */ @@ -256,10 +256,10 @@ int io_seek(IOHANDLE io, int offset, int origin); /* Function: io_tell Gets the current position in the file. - + Parameters: io - Handle to the file. - + Returns: Returns the current position. -1L if an error occured. */ @@ -268,10 +268,10 @@ long int io_tell(IOHANDLE io); /* Function: io_length Gets the total length of the file. Resetting cursor to the beginning - + Parameters: io - Handle to the file. - + Returns: Returns the total size. -1L if an error occured. */ @@ -280,10 +280,10 @@ long int io_length(IOHANDLE io); /* Function: io_close Closes a file. - + Parameters: io - Handle to the file. - + Returns: Returns 0 on success. */ @@ -292,10 +292,10 @@ int io_close(IOHANDLE io); /* Function: io_flush Empties all buffers and writes all pending data. - + Parameters: io - Handle to the file. - + Returns: Returns 0 on success. */ @@ -326,7 +326,7 @@ IOHANDLE io_stderr(); /* Function: thread_sleep Suspends the current thread for a given period. - + Parameters: milliseconds - Number of milliseconds to sleep. */ @@ -335,18 +335,18 @@ void thread_sleep(int milliseconds); /* Function: thread_create Creates a new thread. - + Parameters: threadfunc - Entry point for the new thread. user - Pointer to pass to the thread. - + */ void *thread_create(void (*threadfunc)(void *), void *user); /* Function: thread_wait Waits for a thread to be done or destroyed. - + Parameters: thread - Thread to wait for. */ @@ -355,7 +355,7 @@ void thread_wait(void *thread); /* Function: thread_destroy Destroys a thread. - + Parameters: thread - Thread to destroy. */ @@ -390,7 +390,7 @@ typedef long long int64; /* Function: time_get Fetches a sample from a high resolution timer. - + Returns: Current value of the timer. @@ -402,7 +402,7 @@ int64 time_get(); /* Function: time_freq Returns the frequency of the high resolution timer. - + Returns: Returns the frequency of the high resolution timer. */ @@ -411,7 +411,7 @@ int64 time_freq(); /* Function: time_timestamp Retrives the current time as a UNIX timestamp - + Returns: The time as a UNIX timestamp */ @@ -428,7 +428,7 @@ typedef struct enum { NETADDR_MAXSTRSIZE = 1+(8*4+7)+1+1+5+1, // [XXXX:XXXX:XXXX:XXXX:XXXX:XXXX:XXXX:XXXX]:XXXXX - + NETTYPE_INVALID = 0, NETTYPE_IPV4 = 1, NETTYPE_IPV6 = 2, @@ -446,10 +446,10 @@ typedef struct /* Function: net_init Initiates network functionallity. - + Returns: Returns 0 on success, - + Remarks: You must call this function before using any other network functions. @@ -469,11 +469,11 @@ int net_host_lookup(const char *hostname, NETADDR *addr, int types); /* Function: net_addr_comp Compares two network addresses. - + Parameters: a - Address to compare b - Address to compare to. - + Returns: <0 - Address a is lesser then address b 0 - Address a is equal to address b @@ -484,12 +484,12 @@ int net_addr_comp(const NETADDR *a, const NETADDR *b); /* Function: net_addr_str Turns a network address into a representive string. - + Parameters: addr - Address to turn into a string. string - Buffer to fill with the string. max_length - Maximum size of the string. - + Remarks: - The string will always be zero terminated @@ -499,10 +499,10 @@ void net_addr_str(const NETADDR *addr, char *string, int max_length); /* Function: net_addr_from_str Turns string into a network address. - + Returns: 0 on success - + Parameters: addr - Address to fill in. string - String to parse. @@ -517,7 +517,7 @@ int net_addr_from_str(NETADDR *addr, const char *string); Parameters: bindaddr - Address to bind the socket to. - + Returns: On success it returns an handle to the socket. On failure it returns NETSOCKET_INVALID. @@ -533,7 +533,7 @@ NETSOCKET net_udp_create(NETADDR bindaddr); addr - Where to send the packet. data - Pointer to the packet data to send. size - Size of the packet. - + Returns: On success it returns the number of bytes sent. Returns -1 on error. @@ -549,7 +549,7 @@ int net_udp_send(NETSOCKET sock, const NETADDR *addr, const void *data, int size addr - Pointer to an NETADDR that will recive the address. data - Pointer to a buffer that will recive the data. maxsize - Maximum size to recive. - + Returns: On success it returns the number of bytes recived. Returns -1 on error. @@ -562,7 +562,7 @@ int net_udp_recv(NETSOCKET sock, NETADDR *addr, void *data, int maxsize); Parameters: sock - Socket to close. - + Returns: Returns 0 on success. -1 on error. */ @@ -574,7 +574,7 @@ int net_udp_close(NETSOCKET sock); /* Function: net_tcp_create Creates a TCP socket. - + Parameters: bindaddr - Address to bind the socket to. @@ -586,11 +586,11 @@ NETSOCKET net_tcp_create(const NETADDR *a); /* Function: net_tcp_listen Makes the socket start listening for new connections. - + Parameters: sock - Socket to start listen to. backlog - Size of the queue of incomming connections to keep. - + Returns: Returns 0 on success. */ @@ -599,12 +599,12 @@ int net_tcp_listen(NETSOCKET sock, int backlog); /* Function: net_tcp_accept Polls a listning socket for a new connection. - + Parameters: sock - Listning socket to poll. new_sock - Pointer to a socket to fill in with the new socket. addr - Pointer to an address that will be filled in the remote address (optional, can be NULL). - + Returns: Returns a non-negative integer on success. Negative integer on failure. */ @@ -613,26 +613,26 @@ int net_tcp_accept(NETSOCKET sock, NETSOCKET *new_sock, NETADDR *addr); /* Function: net_tcp_connect Connects one socket to another. - + Parameters: sock - Socket to connect. addr - Address to connect to. Returns: Returns 0 on success. - + */ int net_tcp_connect(NETSOCKET sock, const NETADDR *addr); /* Function: net_tcp_send Sends data to a TCP stream. - + Parameters: sock - Socket to send data to. data - Pointer to the data to send. size - Size of the data to send. - + Returns: Number of bytes sent. Negative value on failure. */ @@ -641,12 +641,12 @@ int net_tcp_send(NETSOCKET sock, const void *data, int size); /* Function: net_tcp_recv Recvives data from a TCP stream. - + Parameters: sock - Socket to recvive data from. data - Pointer to a buffer to write the data to max_size - Maximum of data to write to the buffer. - + Returns: Number of bytes recvived. Negative value on failure. When in non-blocking mode, it returns 0 when there is no more data to @@ -657,10 +657,10 @@ int net_tcp_recv(NETSOCKET sock, void *data, int maxsize); /* Function: net_tcp_close Closes a TCP socket. - + Parameters: sock - Socket to close. - + Returns: Returns 0 on success. Negative value on failure. */ @@ -671,12 +671,12 @@ int net_tcp_close(NETSOCKET sock); /* Function: str_append Appends a string to another. - + Parameters: dst - Pointer to a buffer that contains a string. src - String to append. dst_size - Size of the buffer of the dst string. - + Remarks: - The strings are treated as zero-termineted strings. - Garantees that dst string will contain zero-termination. @@ -686,7 +686,7 @@ void str_append(char *dst, const char *src, int dst_size); /* Function: str_copy Copies a string to another. - + Parameters: dst - Pointer to a buffer that shall recive the string. src - String to be copied. @@ -701,10 +701,10 @@ void str_copy(char *dst, const char *src, int dst_size); /* Function: str_length Returns the length of a zero terminated string. - + Parameters: str - Pointer to the string. - + Returns: Length of string in bytes excluding the zero termination. */ @@ -713,7 +713,7 @@ int str_length(const char *str); /* Function: str_format Performs printf formating into a buffer. - + Parameters: buffer - Pointer to the buffer to recive the formated string. buffer_size - Size of the buffer. @@ -730,7 +730,7 @@ void str_format(char *buffer, int buffer_size, const char *format, ...); /* Function: str_sanitize_strong Replaces all characters below 32 and above 127 with whitespace. - + Parameters: str - String to sanitize. @@ -742,7 +742,7 @@ void str_sanitize_strong(char *str); /* Function: str_sanitize_cc Replaces all characters below 32 with whitespace. - + Parameters: str - String to sanitize. @@ -755,7 +755,7 @@ void str_sanitize_cc(char *str); Function: str_sanitize Replaces all characters below 32 with whitespace with exception to \t, \n and \r. - + Parameters: str - String to sanitize. @@ -767,7 +767,7 @@ void str_sanitize(char *str); /* Function: str_skip_to_whitespace Skips leading non-whitespace characters(all but ' ', '\t', '\n', '\r'). - + Parameters: str - Pointer to the string. @@ -783,7 +783,7 @@ char *str_skip_to_whitespace(char *str); /* Function: str_skip_whitespaces Skips leading whitespace characters(' ', '\t', '\n', '\r'). - + Parameters: str - Pointer to the string. @@ -799,12 +799,12 @@ char *str_skip_whitespaces(char *str); /* Function: str_comp_nocase Compares to strings case insensitive. - + Parameters: a - String to compare. b - String to compare. - - Returns: + + Returns: <0 - String a is lesser then string b 0 - String a is equal to string b >0 - String a is greater then string b @@ -819,12 +819,12 @@ int str_comp_nocase(const char *a, const char *b); /* Function: str_comp Compares to strings case sensitive. - + Parameters: a - String to compare. b - String to compare. - - Returns: + + Returns: <0 - String a is lesser then string b 0 - String a is equal to string b >0 - String a is greater then string b @@ -837,13 +837,13 @@ int str_comp(const char *a, const char *b); /* Function: str_comp_num Compares up to num characters of two strings case sensitive. - + Parameters: a - String to compare. b - String to compare. num - Maximum characters to compare - - Returns: + + Returns: <0 - String a is lesser then string b 0 - String a is equal to string b >0 - String a is greater then string b @@ -856,12 +856,12 @@ int str_comp_num(const char *a, const char *b, const int num); /* Function: str_comp_filenames Compares two strings case sensitive, digit chars will be compared as numbers. - + Parameters: a - String to compare. b - String to compare. - - Returns: + + Returns: <0 - String a is lesser then string b 0 - String a is equal to string b >0 - String a is greater then string b @@ -878,7 +878,7 @@ int str_comp_filenames(const char *a, const char *b); Parameters: haystack - String to search in needle - String to search for - + Returns: A pointer into haystack where the needle was found. Returns NULL of needle could not be found. @@ -896,7 +896,7 @@ const char *str_find_nocase(const char *haystack, const char *needle); Parameters: haystack - String to search in needle - String to search for - + Returns: A pointer into haystack where the needle was found. Returns NULL of needle could not be found. @@ -939,13 +939,13 @@ void str_timestamp(char *buffer, int buffer_size); /* Function: fs_listdir Lists the files in a directory - + Parameters: dir - Directory to list cb - Callback function to call for each entry type - Type of the directory user - Pointer to give to the callback - + Returns: Always returns 0. */ @@ -955,13 +955,13 @@ int fs_listdir(const char *dir, FS_LISTDIR_CALLBACK cb, int type, void *user); /* Function: fs_makedir Creates a directory - + Parameters: path - Directory to create - + Returns: Returns 0 on success. Negative value on failure. - + Remarks: Does not create several directories if needed. "a/b/c" will result in a failure if b or a does not exist. @@ -971,10 +971,10 @@ int fs_makedir(const char *path); /* Function: fs_storage_path Fetches per user configuration directory. - + Returns: Returns 0 on success. Negative value on failure. - + Remarks: - Returns ~/.appname on UNIX based systems - Returns ~/Library/Applications Support/appname on Mac OS X @@ -985,7 +985,7 @@ int fs_storage_path(const char *appname, char *path, int max); /* Function: fs_is_dir Checks if directory exists - + Returns: Returns 1 on success, 0 on failure. */ @@ -994,7 +994,7 @@ int fs_is_dir(const char *path); /* Function: fs_chdir Changes current working directory - + Returns: Returns 0 on success, 1 on failure. */ @@ -1003,7 +1003,7 @@ int fs_chdir(const char *path); /* Function: fs_getcwd Gets the current working directory. - + Returns: Returns a pointer to the buffer on success, 0 on failure. */ @@ -1012,7 +1012,7 @@ char *fs_getcwd(char *buffer, int buffer_size); /* Function: fs_parent_dir Get the parent directory of a directory - + Parameters: path - The directory string @@ -1027,7 +1027,7 @@ int fs_parent_dir(char *path); /* Function: fs_remove Deletes the file with the specified name. - + Parameters: filename - The file to delete @@ -1042,7 +1042,7 @@ int fs_remove(const char *filename); /* Function: fs_rename Renames the file or directory. If the paths differ the file will be moved. - + Parameters: oldname - The actual name newname - The new name @@ -1062,7 +1062,7 @@ int fs_rename(const char *oldname, const char *newname); /* Function: net_tcp_connect_non_blocking - + DOCTODO: serp */ int net_tcp_connect_non_blocking(NETSOCKET sock, const NETADDR *a); @@ -1121,7 +1121,7 @@ enum { #define DBG_LEVEL_LOW DBG_LEVEL_IMPORTANT #define DBG_LEVEL_HIGH DBG_LEVEL_INFO -typedef void (*DBG_LOGGER)(const char *line); +typedef void (*DBG_LOGGER)(const char *line); void dbg_logger(DBG_LOGGER logger); void dbg_logger_stdout(); @@ -1157,7 +1157,7 @@ unsigned str_quickhash(const char *str); /* Function: gui_messagebox Display plain OS-dependent message box - + Parameters: title - title of the message box message - text to display @@ -1168,7 +1168,7 @@ void gui_messagebox(const char *title, const char *message); /* Function: str_utf8_rewind Moves a cursor backwards in an utf8 string - + Parameters: str - utf8 string cursor - position in the string @@ -1184,11 +1184,11 @@ int str_utf8_rewind(const char *str, int cursor); /* Function: str_utf8_forward Moves a cursor forwards in an utf8 string - + Parameters: str - utf8 string cursor - position in the string - + Returns: New cursor position. @@ -1200,10 +1200,10 @@ int str_utf8_forward(const char *str, int cursor); /* Function: str_utf8_decode Decodes an utf8 character - + Parameters: ptr - pointer to an utf8 string. this pointer will be moved forward - + Returns: Unicode value for the character. -1 for invalid characters and 0 for end of string. @@ -1215,10 +1215,10 @@ int str_utf8_decode(const char **ptr); /* Function: str_utf8_encode Encode an utf8 character - + Parameters: ptr - Pointer to a buffer that should recive the data. Should be able to hold at least 4 bytes. - + Returns: Number of bytes put into the buffer. @@ -1230,10 +1230,10 @@ int str_utf8_encode(char *ptr, int chr); /* Function: str_utf8_check Checks if a strings contains just valid utf8 characters. - + Parameters: str - Pointer to a possible utf8 string. - + Returns: 0 - invalid characters found. 1 - only valid characters found. diff --git a/src/base/tl/algorithm.h b/src/base/tl/algorithm.h index c5cd74c3..6b2e542a 100644 --- a/src/base/tl/algorithm.h +++ b/src/base/tl/algorithm.h @@ -8,7 +8,7 @@ /* insert 4 - v + v 1 2 3 4 5 6 */ @@ -38,12 +38,12 @@ R partition_binary(R range, T value) concept_size::check(range); concept_slice::check(range); concept_sorted::check(range); - + if(range.empty()) return range; if(range.back() < value) return R(); - + while(range.size() > 1) { unsigned pivot = (range.size()-1)/2; @@ -82,7 +82,7 @@ void sort_bubble(R range) concept_empty::check(range); concept_forwarditeration::check(range); concept_backwarditeration::check(range); - + // slow bubblesort :/ for(; !range.empty(); range.pop_back()) { @@ -119,18 +119,18 @@ bool sort_verify(R range) { concept_empty::check(range); concept_forwarditeration::check(range); - + typename R::type *prev = &range.front(); range.pop_front(); for(; !range.empty(); range.pop_front()) { typename R::type *cur = &range.front(); - + if(*cur < *prev) return false; prev = cur; } - + return true; } diff --git a/src/base/tl/array.h b/src/base/tl/array.h index 0cee2afc..4f4b2fc3 100644 --- a/src/base/tl/array.h +++ b/src/base/tl/array.h @@ -10,10 +10,10 @@ /* Class: array Normal dynamic array class - + Remarks: - Grows 50% each time it needs to fit new items - - Use set_size() if you know how many elements + - Use set_size() if you know how many elements - Use optimize() to reduce the needed space. */ template <class T, class ALLOCATOR = allocator_default<T> > @@ -24,7 +24,7 @@ class array : private ALLOCATOR list = 0x0; clear(); } - + public: typedef plain_range<T> range; @@ -35,7 +35,7 @@ public: { init(); } - + /* Function: array copy constructor */ @@ -60,7 +60,7 @@ public: /* Function: delete_all - + Remarks: - Invalidates ranges */ @@ -74,7 +74,7 @@ public: /* Function: clear - + Remarks: - Invalidates ranges */ @@ -124,7 +124,7 @@ public: /* Function: remove_index - + Remarks: - Invalidates ranges */ @@ -132,7 +132,7 @@ public: { for(int i = index+1; i < num_elements; i++) list[i-1] = list[i]; - + set_size(size()-1); } @@ -156,10 +156,10 @@ public: /* Function: add Adds an item to the array. - + Arguments: item - Item to add. - + Remarks: - Invalidates ranges - See remarks about <array> how the array grows. @@ -175,9 +175,9 @@ public: /* Function: insert Inserts an item into the array at a specified location. - + Arguments: - item - Item to insert. + item - Item to insert. r - Range where to insert the item Remarks: @@ -188,16 +188,16 @@ public: { if(r.empty()) return add(item); - + int index = (int)(&r.front()-list); incsize(); set_size(size()+1); - + for(int i = num_elements-1; i > index; i--) list[i] = list[i-1]; list[index] = item; - + return num_elements-1; } @@ -236,7 +236,7 @@ public: /* Function: set_size Resizes the array to the specified size. - + Arguments: new_size - The new size for the array. */ @@ -251,10 +251,10 @@ public: Function: hint_size Allocates the number of elements wanted but does not increase the list size. - + Arguments: hint - Size to allocate. - + Remarks: - If the hint is smaller then the number of elements, nothing will be done. - Invalidates ranges @@ -302,7 +302,7 @@ public: (*this)[i] = other[i]; return *this; } - + /* Function: all Returns a range that contains the whole array. @@ -318,18 +318,18 @@ protected: alloc(list_size+1); else alloc(list_size+list_size/2); - } + } } void alloc(int new_len) { list_size = new_len; T *new_list = ALLOCATOR::alloc_array(list_size); - + int end = num_elements < list_size ? num_elements : list_size; for(int i = 0; i < end; i++) new_list[i] = list[i]; - + ALLOCATOR::free_array(list); num_elements = num_elements < list_size ? num_elements : list_size; diff --git a/src/base/tl/range.h b/src/base/tl/range.h index 25047d31..f05169fa 100644 --- a/src/base/tl/range.h +++ b/src/base/tl/range.h @@ -11,7 +11,7 @@ /* Concept: concept_empty - + template<class T> struct range { @@ -25,7 +25,7 @@ struct concept_empty /* Concept: concept_index - + template<class T> struct range { @@ -39,7 +39,7 @@ struct concept_index /* Concept: concept_size - + template<class T> struct range { @@ -53,7 +53,7 @@ struct concept_size /* Concept: concept_slice - + template<class T> struct range { @@ -67,7 +67,7 @@ struct concept_slice /* Concept: concept_sorted - + template<class T> struct range { @@ -82,13 +82,13 @@ struct concept_sorted /* Concept: concept_forwarditeration Checks for the front and pop_front methods - + template<class T> struct range { void pop_front(); T &front() const; - }; + }; */ struct concept_forwarditeration { @@ -98,13 +98,13 @@ struct concept_forwarditeration /* Concept: concept_backwarditeration Checks for the back and pop_back methods - + template<class T> struct range { void pop_back(); T &back() const; - }; + }; */ struct concept_backwarditeration { @@ -119,7 +119,7 @@ struct concept_backwarditeration /* Class: plain_range - + Concepts: <concept_empty> <concept_index> @@ -142,13 +142,13 @@ public: { *this = r; } - + plain_range(T *b, T *e) { begin = b; end = e; } - + bool empty() const { return begin >= end; } void pop_front() { assert(!empty()); begin++; } void pop_back() { assert(!empty()); end--; } @@ -160,7 +160,7 @@ public: { return plain_range(begin+startindex, begin+endindex); } - + protected: T *begin; T *end; @@ -168,7 +168,7 @@ protected: /* Class: plain_range_sorted - + Concepts: Same as <plain_range> but with these additions: <concept_sorted> @@ -180,7 +180,7 @@ class plain_range_sorted : public plain_range<T> public: /* sorted concept */ void sorted() const { } - + plain_range_sorted() {} @@ -188,11 +188,11 @@ public: { *this = r; } - + plain_range_sorted(T *b, T *e) : parent(b, e) {} - + plain_range_sorted slice(unsigned start, unsigned count) { return plain_range_sorted(parent::begin+start, parent::begin+start+count); @@ -206,29 +206,29 @@ private: reverse_range() {} public: typedef typename R::type type; - + reverse_range(R r) { range = r; } - + reverse_range(const reverse_range &other) { range = other.range; } - + bool empty() const { return range.empty(); } void pop_front() { range.pop_back(); } void pop_back() { range.pop_front(); } type& front() { return range.back(); } type& back() { return range.front(); } - + R range; }; template<class R> reverse_range<R> reverse(R range) { - return reverse_range<R>(range); + return reverse_range<R>(range); } template<class R> R reverse(reverse_range<R> range) { - return range.range; + return range.range; } #endif // TL_FILE_RANGE_HPP diff --git a/src/base/tl/sorted_array.h b/src/base/tl/sorted_array.h index 94ccd543..7e312e1e 100644 --- a/src/base/tl/sorted_array.h +++ b/src/base/tl/sorted_array.h @@ -10,11 +10,11 @@ template <class T, class ALLOCATOR = allocator_default<T> > class sorted_array : public array<T, ALLOCATOR> { typedef array<T, ALLOCATOR> parent; - + // insert and size is not allowed int insert(const T& item, typename parent::range r) { dbg_break(); return 0; } int set_size(int new_size) { dbg_break(); return 0; } - + public: typedef plain_range_sorted<T> range; @@ -27,7 +27,7 @@ public: { return parent::add(item); } - + void sort_range() { sort(all()); @@ -37,7 +37,7 @@ public: /* Function: all Returns a sorted range that contains the whole array. - */ + */ range all() { return range(parent::list, parent::list+parent::num_elements); } }; diff --git a/src/base/tl/string.h b/src/base/tl/string.h index 18fab4d4..e0b891ad 100644 --- a/src/base/tl/string.h +++ b/src/base/tl/string.h @@ -11,38 +11,38 @@ class string_base : private ALLOCATOR { char *str; int length; - + void reset() { str = 0; length = 0; } - + void free() { ALLOCATOR::free_array(str); reset(); - } - + } + void copy(const char *other_str, int other_length) { length = other_length; str = ALLOCATOR::alloc_array(length+1); mem_copy(str, other_str, length+1); } - + void copy(const string_base &other) { if(!other.str) return; copy(other.str, other.length); } - + public: string_base() { reset(); } string_base(const char *other_str) { copy(other_str, str_length(other_str)); } string_base(const string_base &other) { reset(); copy(other); } ~string_base() { free(); } - + string_base &operator = (const char *other) { free(); @@ -50,17 +50,17 @@ public: copy(other, str_length(other)); return *this; } - + string_base &operator = (const string_base &other) { free(); copy(other); return *this; } - + bool operator < (const char *other_str) const { return str_comp(str, other_str) < 0; } operator const char *() const { return str; } - + const char *cstr() const { return str; } }; diff --git a/src/base/vmath.h b/src/base/vmath.h index e4443da2..3461adf8 100644 --- a/src/base/vmath.h +++ b/src/base/vmath.h @@ -13,19 +13,19 @@ class vector2_base public: union { T x,u; }; union { T y,v; }; - + vector2_base() {} vector2_base(float nx, float ny) { x = nx; y = ny; } - + vector2_base operator -() const { return vector2_base(-x, -y); } vector2_base operator -(const vector2_base &v) const { return vector2_base(x-v.x, y-v.y); } vector2_base operator +(const vector2_base &v) const { return vector2_base(x+v.x, y+v.y); } vector2_base operator *(const T v) const { return vector2_base(x*v, y*v); } - + const vector2_base &operator =(const vector2_base &v) { x = v.x; y = v.y; return *this; } const vector2_base &operator +=(const vector2_base &v) { x += v.x; y += v.y; return *this; } @@ -81,7 +81,7 @@ inline vector2_base<T> closest_point_on_line(vector2_base<T> line_point0, vector if (t > 1.0f) return 1.0f; return t;*/ } - + // ------------------------------------ template<typename T> class vector3_base @@ -98,7 +98,7 @@ public: y = ny; z = nz; } - + const vector3_base &operator =(const vector3_base &v) { x = v.x; y = v.y; z = v.z; return *this; } vector3_base operator -(const vector3_base &v) const { return vector3_base(x-v.x, y-v.y, z-v.z); } @@ -107,7 +107,7 @@ public: vector3_base operator *(const T v) const { return vector3_base(x*v, y*v, z*v); } vector3_base operator *(const vector3_base &v) const { return vector3_base(x*v.x, y*v.y, z*v.z); } vector3_base operator /(const T v) const { return vector3_base(x/v, y/v, z/v); } - + const vector3_base &operator +=(const vector3_base &v) { x += v.x; y += v.y; z += v.z; return *this; } const vector3_base &operator -=(const vector3_base &v) { x -= v.x; y -= v.y; z -= v.z; return *this; } const vector3_base &operator *=(const T v) { x *= v; y *= v; z *= v; return *this; } @@ -174,13 +174,13 @@ public: z = nz; w = nw; } - + vector4_base operator +(const vector4_base &v) const { return vector4_base(x+v.x, y+v.y, z+v.z, w+v.w); } vector4_base operator -(const vector4_base &v) const { return vector4_base(x-v.x, y-v.y, z-v.z, w-v.w); } vector4_base operator -() const { return vector4_base(-x, -y, -z, -w); } vector4_base operator *(const vector4_base &v) const { return vector4_base(x*v.x, y*v.y, z*v.z, w*v.w); } vector4_base operator *(const T v) const { return vector4_base(x*v, y*v, z*v, w*v); } - + const vector4_base &operator =(const vector4_base &v) { x = v.x; y = v.y; z = v.z; w = v.w; return *this; } const vector4_base &operator +=(const vector4_base &v) { x += v.x; y += v.y; z += v.z; w += v.w; return *this; } diff --git a/src/engine/client.h b/src/engine/client.h index 870c355d..78741018 100644 --- a/src/engine/client.h +++ b/src/engine/client.h @@ -18,13 +18,13 @@ protected: int m_CurGameTick; float m_GameIntraTick; float m_GameTickTime; - + int m_PredTick; float m_PredIntraTick; - + float m_LocalTime; float m_FrameTime; - + int m_GameTickSpeed; public: @@ -66,11 +66,11 @@ public: inline float PredIntraGameTick() const { return m_PredIntraTick; } inline float GameTickTime() const { return m_GameTickTime; } inline int GameTickSpeed() const { return m_GameTickSpeed; } - + // other time access inline float FrameTime() const { return m_FrameTime; } inline float LocalTime() const { return m_LocalTime; } - + // actions virtual void Connect(const char *pAddress) = 0; virtual void Disconnect() = 0; @@ -88,26 +88,26 @@ public: // virtual int MapDownloadAmount() = 0; virtual int MapDownloadTotalsize() = 0; - + // input virtual int *GetInput(int Tick) = 0; - + // remote console virtual void RconAuth(const char *pUsername, const char *pPassword) = 0; virtual bool RconAuthed() = 0; virtual void Rcon(const char *pLine) = 0; - + // server info virtual void GetServerInfo(class CServerInfo *pServerInfo) = 0; - + // snapshot interface - + enum { SNAP_CURRENT=0, SNAP_PREV=1 }; - + // TODO: Refactor: should redo this a bit i think, too many virtual calls virtual int SnapNumItems(int SnapID) = 0; virtual void *SnapFindItem(int SnapID, int Type, int ID) = 0; @@ -126,8 +126,8 @@ public: return -1; return SendMsg(&Packer, Flags); } - - // + + // virtual const char *ErrorString() = 0; virtual const char *LatestVersion() = 0; virtual bool ConnectionProblems() = 0; @@ -155,9 +155,9 @@ public: virtual void OnMessage(int MsgID, CUnpacker *pUnpacker) = 0; virtual void OnPredict() = 0; virtual void OnActivateEditor() = 0; - + virtual int OnSnapInput(int *pData) = 0; - + virtual const char *GetItemName(int Type) = 0; virtual int GetCountryIndex(int Code) = 0; virtual const char *Version() = 0; diff --git a/src/engine/client/client.cpp b/src/engine/client/client.cpp index 5cce547e..61a96eee 100644 --- a/src/engine/client/client.cpp +++ b/src/engine/client/client.cpp @@ -545,7 +545,7 @@ void CClient::RconAuth(const char *pName, const char *pPassword) { if(RconAuthed()) return; - + CMsgPacker Msg(NETMSG_RCON_AUTH); Msg.AddString(pName, 32); Msg.AddString(pPassword, 32); @@ -860,7 +860,7 @@ void CClient::DebugRender() total = 42 */ FrameTimeAvg = FrameTimeAvg*0.9f + m_FrameTime*0.1f; - str_format(aBuffer, sizeof(aBuffer), "ticks: %8d %8d mem %dk %d gfxmem: %dk fps: %3d", + str_format(aBuffer, sizeof(aBuffer), "ticks: %8d %8d mem %dk %d gfxmem: %dk fps: %3d", m_CurGameTick, m_PredTick, mem_stats()->allocated/1024, mem_stats()->total_allocations, @@ -1030,7 +1030,7 @@ void CClient::ProcessConnlessPacket(CNetChunk *pPacket) // version info if(pPacket->m_DataSize == (int)(sizeof(VERSIONSRV_VERSION) + sizeof(VERSION_DATA)) && mem_comp(pPacket->m_pData, VERSIONSRV_VERSION, sizeof(VERSIONSRV_VERSION)) == 0) - + { unsigned char *pVersionData = (unsigned char*)pPacket->m_pData + sizeof(VERSIONSRV_VERSION); int VersionMatch = !mem_comp(pVersionData, VERSION_DATA, sizeof(VERSION_DATA)); @@ -1060,7 +1060,7 @@ void CClient::ProcessConnlessPacket(CNetChunk *pPacket) // map version list if(pPacket->m_DataSize >= (int)sizeof(VERSIONSRV_MAPLIST) && - mem_comp(pPacket->m_pData, VERSIONSRV_MAPLIST, sizeof(VERSIONSRV_MAPLIST)) == 0) + mem_comp(pPacket->m_pData, VERSIONSRV_MAPLIST, sizeof(VERSIONSRV_MAPLIST)) == 0) { int Size = pPacket->m_DataSize-sizeof(VERSIONSRV_MAPLIST); int Num = Size/sizeof(CMapVersion); @@ -1114,7 +1114,7 @@ void CClient::ProcessConnlessPacket(CNetChunk *pPacket) mem_copy(Addr.ip, pAddrs[i].m_aIp, sizeof(Addr.ip)); } Addr.port = (pAddrs[i].m_aPort[0]<<8) | pAddrs[i].m_aPort[1]; - + m_ServerBrowser.Set(Addr, IServerBrowser::SET_MASTER_ADD, -1, 0x0); } } @@ -1125,7 +1125,7 @@ void CClient::ProcessConnlessPacket(CNetChunk *pPacket) // we got ze info CUnpacker Up; CServerInfo Info = {0}; - + Up.Reset((unsigned char*)pPacket->m_pData+sizeof(SERVERBROWSE_INFO), pPacket->m_DataSize-sizeof(SERVERBROWSE_INFO)); int Token = str_toint(Up.GetString()); str_copy(Info.m_aVersion, Up.GetString(CUnpacker::SANITIZE_CC|CUnpacker::SKIP_START_WHITESPACES), sizeof(Info.m_aVersion)); @@ -1282,7 +1282,7 @@ void CClient::ProcessServerPacket(CNetChunk *pPacket) if(!pError) { m_pConsole->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "client/network", "loading done"); - SendReady(); + SendReady(); } else DisconnectWithReason(pError); diff --git a/src/engine/client/friends.h b/src/engine/client/friends.h index e3258ec2..be0cfa49 100644 --- a/src/engine/client/friends.h +++ b/src/engine/client/friends.h @@ -14,14 +14,14 @@ class CFriends : public IFriends static void ConRemoveFriend(IConsole::IResult *pResult, void *pUserData); static void ConfigSaveCallback(IConfig *pConfig, void *pUserData); - + public: CFriends(); - + void Init(); - + int NumFriends() const { return m_NumFriends; } - const CFriendInfo *GetFriend(int Index) const; + const CFriendInfo *GetFriend(int Index) const; bool IsFriend(const char *pName, const char *pClan, bool PlayersOnly) const; void AddFriend(const char *pName, const char *pClan); diff --git a/src/engine/client/graphics.cpp b/src/engine/client/graphics.cpp index 99f5e095..641f9dfb 100644 --- a/src/engine/client/graphics.cpp +++ b/src/engine/client/graphics.cpp @@ -50,7 +50,7 @@ static CVideoMode g_aFakeModes[] = { {1800,1440,8,8,8}, {1856,1392,8,8,8}, {1920,1080,8,8,8}, {1920,1200,8,8,8}, {1920,1440,8,8,8}, {1920,2400,8,8,8}, {2048,1536,8,8,8}, - + {320,240,5,6,5}, {400,300,5,6,5}, {640,480,5,6,5}, {720,400,5,6,5}, {768,576,5,6,5}, {800,600,5,6,5}, {1024,600,5,6,5}, {1024,768,5,6,5}, {1152,864,5,6,5}, @@ -67,7 +67,7 @@ void CGraphics_OpenGL::Flush() { if(m_NumVertices == 0) return; - + //glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST); //glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); @@ -83,7 +83,7 @@ void CGraphics_OpenGL::Flush() glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_TEXTURE_COORD_ARRAY); glEnableClientState(GL_COLOR_ARRAY); - + if(m_RenderEnable) { if(m_Drawing == DRAWING_QUADS) @@ -91,7 +91,7 @@ void CGraphics_OpenGL::Flush() else if(m_Drawing == DRAWING_LINES) glDrawArrays(GL_LINES, 0, m_NumVertices); } - + // Reset pointer m_NumVertices = 0; } @@ -125,26 +125,26 @@ unsigned char CGraphics_OpenGL::Sample(int w, int h, const unsigned char *pData, pData[(v*w+u+1)*4+Offset]+ pData[((v+1)*w+u)*4+Offset]+ pData[((v+1)*w+u+1)*4+Offset])/4; -} +} CGraphics_OpenGL::CGraphics_OpenGL() { m_NumVertices = 0; - + m_ScreenX0 = 0; m_ScreenY0 = 0; m_ScreenX1 = 0; m_ScreenY1 = 0; - + m_ScreenWidth = -1; m_ScreenHeight = -1; - + m_Rotation = 0; m_Drawing = 0; m_InvalidTexture = 0; - + m_TextureMemoryUsage = 0; - + m_RenderEnable = true; m_DoScreenshot = false; } @@ -161,7 +161,7 @@ void CGraphics_OpenGL::ClipDisable() //if(no_gfx) return; glDisable(GL_SCISSOR_TEST); } - + void CGraphics_OpenGL::BlendNone() { glDisable(GL_BLEND); @@ -180,10 +180,10 @@ void CGraphics_OpenGL::BlendAdditive() } int CGraphics_OpenGL::MemoryUsage() const -{ +{ return m_TextureMemoryUsage; -} - +} + void CGraphics_OpenGL::MapScreen(float TopLeftX, float TopLeftY, float BottomRightX, float BottomRightY) { m_ScreenX0 = TopLeftX; @@ -220,7 +220,7 @@ void CGraphics_OpenGL::LinesEnd() void CGraphics_OpenGL::LinesDraw(const CLineItem *pArray, int Num) { dbg_assert(m_Drawing == DRAWING_LINES, "called draw without begin"); - + for(int i = 0; i < Num; ++i) { m_aVertices[m_NumVertices + 2*i].m_Pos.x = pArray[i].m_X0; @@ -241,10 +241,10 @@ int CGraphics_OpenGL::UnloadTexture(int Index) { if(Index == m_InvalidTexture) return 0; - + if(Index < 0) return 0; - + glDeleteTextures(1, &m_aTextures[Index].m_Tex); m_aTextures[Index].m_Next = m_FirstFreeTexture; m_TextureMemoryUsage -= m_aTextures[Index].m_MemSize; @@ -261,16 +261,16 @@ int CGraphics_OpenGL::LoadTextureRaw(int Width, int Height, int Format, const vo int Oglformat = 0; int StoreOglformat = 0; int Tex = 0; - + // don't waste memory on texture if we are stress testing if(g_Config.m_DbgStress) return m_InvalidTexture; - + // grab texture Tex = m_FirstFreeTexture; m_FirstFreeTexture = m_aTextures[Tex].m_Next; m_aTextures[Tex].m_Next = -1; - + // resample if needed if(!(Flags&TEXLOAD_NORESAMPLE) && g_Config.m_GfxTextureQuality==0) { @@ -296,13 +296,13 @@ int CGraphics_OpenGL::LoadTextureRaw(int Width, int Height, int Format, const vo pTexData = pTmpData; } } - + Oglformat = GL_RGBA; if(Format == CImageInfo::FORMAT_RGB) Oglformat = GL_RGB; else if(Format == CImageInfo::FORMAT_ALPHA) Oglformat = GL_ALPHA; - + // upload texture if(g_Config.m_GfxTextureCompression) { @@ -320,13 +320,13 @@ int CGraphics_OpenGL::LoadTextureRaw(int Width, int Height, int Format, const vo else if(StoreFormat == CImageInfo::FORMAT_ALPHA) StoreOglformat = GL_ALPHA; } - + glGenTextures(1, &m_aTextures[Tex].m_Tex); glBindTexture(GL_TEXTURE_2D, m_aTextures[Tex].m_Tex); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST); gluBuild2DMipmaps(GL_TEXTURE_2D, StoreOglformat, Width, Height, Oglformat, GL_UNSIGNED_BYTE, pTexData); - + // calculate memory usage { int PixelSize = 4; @@ -346,7 +346,7 @@ int CGraphics_OpenGL::LoadTextureRaw(int Width, int Height, int Format, const vo } } } - + m_TextureMemoryUsage += m_aTextures[Tex].m_MemSize; mem_free(pTmpData); return Tex; @@ -358,7 +358,7 @@ int CGraphics_OpenGL::LoadTexture(const char *pFilename, int StorageType, int St int l = str_length(pFilename); int ID; CImageInfo Img; - + if(l < 3) return -1; if(LoadPNG(&Img, pFilename, StorageType)) @@ -370,7 +370,7 @@ int CGraphics_OpenGL::LoadTexture(const char *pFilename, int StorageType, int St mem_free(Img.m_pData); return ID; } - + return m_InvalidTexture; } @@ -379,7 +379,7 @@ int CGraphics_OpenGL::LoadPNG(CImageInfo *pImg, const char *pFilename, int Stora char aCompleteFilename[512]; unsigned char *pBuffer; png_t Png; // ignore_convention - + // open file for reading png_init(0,0); // ignore_convention @@ -391,7 +391,7 @@ int CGraphics_OpenGL::LoadPNG(CImageInfo *pImg, const char *pFilename, int Stora dbg_msg("game/png", "failed to open file. filename='%s'", pFilename); return 0; } - + int Error = png_open_file(&Png, aCompleteFilename); // ignore_convention if(Error != PNG_NO_ERROR) { @@ -400,18 +400,18 @@ int CGraphics_OpenGL::LoadPNG(CImageInfo *pImg, const char *pFilename, int Stora png_close_file(&Png); // ignore_convention return 0; } - + if(Png.depth != 8 || (Png.color_type != PNG_TRUECOLOR && Png.color_type != PNG_TRUECOLOR_ALPHA)) // ignore_convention { dbg_msg("game/png", "invalid format. filename='%s'", aCompleteFilename); png_close_file(&Png); // ignore_convention return 0; } - + pBuffer = (unsigned char *)mem_alloc(Png.width * Png.height * Png.bpp, 1); // ignore_convention png_get_data(&Png, pBuffer); // ignore_convention png_close_file(&Png); // ignore_convention - + pImg->m_Width = Png.width; // ignore_convention pImg->m_Height = Png.height; // ignore_convention if(Png.color_type == PNG_TRUECOLOR) // ignore_convention @@ -435,7 +435,7 @@ void CGraphics_OpenGL::ScreenshotDirect(const char *pFilename) glPixelStorei(GL_PACK_ALIGNMENT, 1); glReadPixels(0,0, w, h, GL_RGB, GL_UNSIGNED_BYTE, pPixelData); glPixelStorei(GL_PACK_ALIGNMENT, Alignment); - + // flip the pixel because opengl works from bottom left corner for(y = 0; y < h/2; y++) { @@ -443,16 +443,16 @@ void CGraphics_OpenGL::ScreenshotDirect(const char *pFilename) mem_copy(pPixelData+y*w*3, pPixelData+(h-y-1)*w*3, w*3); mem_copy(pPixelData+(h-y-1)*w*3, pTempRow,w*3); } - + // find filename { char aWholePath[1024]; png_t Png; // ignore_convention - IOHANDLE File = m_pStorage->OpenFile(pFilename, IOFLAG_WRITE, IStorage::TYPE_SAVE, aWholePath, sizeof(aWholePath)); + IOHANDLE File = m_pStorage->OpenFile(pFilename, IOFLAG_WRITE, IStorage::TYPE_SAVE, aWholePath, sizeof(aWholePath)); if(File) io_close(File); - + // save png char aBuf[256]; str_format(aBuf, sizeof(aBuf), "saved screenshot to '%s'", aWholePath); @@ -490,7 +490,7 @@ void CGraphics_OpenGL::QuadsBegin() { dbg_assert(m_Drawing == 0, "called quads_begin twice"); m_Drawing = DRAWING_QUADS; - + QuadsSetSubset(0,0,1,1); QuadsSetRotation(0); SetColor(1,1,1,1); @@ -609,7 +609,7 @@ void CGraphics_OpenGL::QuadsDrawTL(const CQuadItem *pArray, int Num) void CGraphics_OpenGL::QuadsDrawFreeform(const CFreeformItem *pArray, int Num) { dbg_assert(m_Drawing == DRAWING_QUADS, "called quads_draw_freeform without begin"); - + for(int i = 0; i < Num; ++i) { m_aVertices[m_NumVertices + 4*i].m_Pos.x = pArray[i].m_X0; @@ -632,7 +632,7 @@ void CGraphics_OpenGL::QuadsDrawFreeform(const CFreeformItem *pArray, int Num) m_aVertices[m_NumVertices + 4*i + 3].m_Tex = m_aTexture[2]; m_aVertices[m_NumVertices + 4*i + 3].m_Color = m_aColor[2]; } - + AddVertices(4*Num); } @@ -647,7 +647,7 @@ void CGraphics_OpenGL::QuadsText(float x, float y, float Size, float r, float g, { char c = *pText; pText++; - + if(c == '\n') { x = StartX; @@ -660,13 +660,13 @@ void CGraphics_OpenGL::QuadsText(float x, float y, float Size, float r, float g, (c/16)/16.0f, (c%16)/16.0f+1.0f/16.0f, (c/16)/16.0f+1.0f/16.0f); - + CQuadItem QuadItem(x, y, Size, Size); QuadsDrawTL(&QuadItem, 1); x += Size/2; } } - + QuadsEnd(); } @@ -674,7 +674,7 @@ bool CGraphics_OpenGL::Init() { m_pStorage = Kernel()->RequestInterface<IStorage>(); m_pConsole = Kernel()->RequestInterface<IConsole>(); - + // Set all z to -5.0f for(int i = 0; i < MAX_VERTICES; i++) m_aVertices[i].m_Pos.z = -5.0f; @@ -691,21 +691,21 @@ bool CGraphics_OpenGL::Init() glDisable(GL_DEPTH_TEST); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); - + glAlphaFunc(GL_GREATER, 0); glEnable(GL_ALPHA_TEST); glDepthMask(0); // create null texture, will get id=0 static const unsigned char aNullTextureData[] = { - 0xff,0x00,0x00,0xff, 0xff,0x00,0x00,0xff, 0x00,0xff,0x00,0xff, 0x00,0xff,0x00,0xff, - 0xff,0x00,0x00,0xff, 0xff,0x00,0x00,0xff, 0x00,0xff,0x00,0xff, 0x00,0xff,0x00,0xff, - 0x00,0x00,0xff,0xff, 0x00,0x00,0xff,0xff, 0xff,0xff,0x00,0xff, 0xff,0xff,0x00,0xff, - 0x00,0x00,0xff,0xff, 0x00,0x00,0xff,0xff, 0xff,0xff,0x00,0xff, 0xff,0xff,0x00,0xff, + 0xff,0x00,0x00,0xff, 0xff,0x00,0x00,0xff, 0x00,0xff,0x00,0xff, 0x00,0xff,0x00,0xff, + 0xff,0x00,0x00,0xff, 0xff,0x00,0x00,0xff, 0x00,0xff,0x00,0xff, 0x00,0xff,0x00,0xff, + 0x00,0x00,0xff,0xff, 0x00,0x00,0xff,0xff, 0xff,0xff,0x00,0xff, 0xff,0xff,0x00,0xff, + 0x00,0x00,0xff,0xff, 0x00,0x00,0xff,0xff, 0xff,0xff,0x00,0xff, 0xff,0xff,0x00,0xff, }; - + m_InvalidTexture = LoadTextureRaw(4,4,CImageInfo::FORMAT_RGBA,aNullTextureData,CImageInfo::FORMAT_RGBA,TEXLOAD_NORESAMPLE); - + return true; } @@ -713,7 +713,7 @@ int CGraphics_SDL::TryInit() { const SDL_VideoInfo *pInfo; int Flags = SDL_OPENGL; - + m_ScreenWidth = g_Config.m_GfxScreenWidth; m_ScreenHeight = g_Config.m_GfxScreenHeight; @@ -721,7 +721,7 @@ int CGraphics_SDL::TryInit() SDL_EventState(SDL_MOUSEMOTION, SDL_IGNORE); // set flags - Flags = SDL_OPENGL; + Flags = SDL_OPENGL; Flags |= SDL_GL_DOUBLEBUFFER; Flags |= SDL_HWPALETTE; if(g_Config.m_DbgResizable) @@ -755,7 +755,7 @@ int CGraphics_SDL::TryInit() // set caption SDL_WM_SetCaption("Teeworlds", "Teeworlds"); - + // create window m_pScreenSurface = SDL_SetVideoMode(m_ScreenWidth, m_ScreenHeight, 0, Flags); if(m_pScreenSurface == NULL) @@ -763,7 +763,7 @@ int CGraphics_SDL::TryInit() dbg_msg("gfx", "unable to set video mode: %s", SDL_GetError()); return -1; } - + return 0; } @@ -772,12 +772,12 @@ int CGraphics_SDL::InitWindow() { if(TryInit() == 0) return 0; - + // try disabling fsaa while(g_Config.m_GfxFsaaSamples) { g_Config.m_GfxFsaaSamples--; - + if(g_Config.m_GfxFsaaSamples) dbg_msg("gfx", "lowering FSAA to %d and trying again", g_Config.m_GfxFsaaSamples); else @@ -799,8 +799,8 @@ int CGraphics_SDL::InitWindow() } dbg_msg("gfx", "out of ideas. failed to init graphics"); - - return -1; + + return -1; } @@ -813,34 +813,34 @@ bool CGraphics_SDL::Init() { { int Systems = SDL_INIT_VIDEO; - + if(g_Config.m_SndEnable) Systems |= SDL_INIT_AUDIO; if(g_Config.m_ClEventthread) Systems |= SDL_INIT_EVENTTHREAD; - + if(SDL_Init(Systems) < 0) { dbg_msg("gfx", "unable to init SDL: %s", SDL_GetError()); return true; } } - + atexit(SDL_Quit); // ignore_convention #ifdef CONF_FAMILY_WINDOWS if(!getenv("SDL_VIDEO_WINDOW_POS") && !getenv("SDL_VIDEO_CENTERED")) // ignore_convention putenv("SDL_VIDEO_WINDOW_POS=8,27"); // ignore_convention #endif - + if(InitWindow() != 0) return true; SDL_ShowCursor(0); - + CGraphics_OpenGL::Init(); - + MapScreen(0,0,g_Config.m_GfxScreenWidth, g_Config.m_GfxScreenHeight); return false; } @@ -887,11 +887,11 @@ void CGraphics_SDL::Swap() ScreenshotDirect(m_aScreenshotName); m_DoScreenshot = false; } - + SDL_GL_SwapBuffers(); - + if(g_Config.m_GfxFinish) - glFinish(); + glFinish(); } @@ -908,9 +908,9 @@ int CGraphics_SDL::GetVideoModes(CVideoMode *pModes, int MaxModes) Count = MaxModes; return Count; } - + // TODO: fix this code on osx or windows - + ppModes = SDL_ListModes(NULL, SDL_OPENGL|SDL_GL_DOUBLEBUFFER|SDL_FULLSCREEN); if(ppModes == NULL) { @@ -936,7 +936,7 @@ int CGraphics_SDL::GetVideoModes(CVideoMode *pModes, int MaxModes) NumModes++; } } - + return NumModes; } diff --git a/src/engine/client/graphics.h b/src/engine/client/graphics.h index 20be3504..4367ccfc 100644 --- a/src/engine/client/graphics.h +++ b/src/engine/client/graphics.h @@ -8,7 +8,7 @@ class CGraphics_OpenGL : public IEngineGraphics protected: class IStorage *m_pStorage; class IConsole *m_pConsole; - + // typedef struct { float x, y, z; } CPoint; typedef struct { float u, v; } CTexCoord; @@ -20,14 +20,14 @@ protected: CTexCoord m_Tex; CColor m_Color; } CVertex; - + enum { MAX_VERTICES = 32*1024, MAX_TEXTURES = 1024*4, - + DRAWING_QUADS=1, - DRAWING_LINES=2 + DRAWING_LINES=2 }; CVertex m_aVertices[MAX_VERTICES]; @@ -65,27 +65,27 @@ protected: void Flush(); void AddVertices(int Count); void Rotate4(const CPoint &rCenter, CVertex *pPoints); - + static unsigned char Sample(int w, int h, const unsigned char *pData, int u, int v, int Offset); public: CGraphics_OpenGL(); - + virtual void ClipEnable(int x, int y, int w, int h); virtual void ClipDisable(); - + virtual void BlendNone(); virtual void BlendNormal(); virtual void BlendAdditive(); virtual int MemoryUsage() const; - + virtual void MapScreen(float TopLeftX, float TopLeftY, float BottomRightX, float BottomRightY); virtual void GetScreen(float *pTopLeftX, float *pTopLeftY, float *pBottomRightX, float *pBottomRightY); virtual void LinesBegin(); virtual void LinesEnd(); virtual void LinesDraw(const CLineItem *pArray, int Num); - + virtual int UnloadTexture(int Index); virtual int LoadTextureRaw(int Width, int Height, int Format, const void *pData, int StoreFormat, int Flags); @@ -115,14 +115,14 @@ public: virtual void QuadsDrawTL(const CQuadItem *pArray, int Num); virtual void QuadsDrawFreeform(const CFreeformItem *pArray, int Num); virtual void QuadsText(float x, float y, float Size, float r, float g, float b, float a, const char *pText); - + virtual bool Init(); }; class CGraphics_SDL : public CGraphics_OpenGL { - SDL_Surface *m_pScreenSurface; - + SDL_Surface *m_pScreenSurface; + int TryInit(); int InitWindow(); public: @@ -141,7 +141,7 @@ public: virtual void Swap(); virtual int GetVideoModes(CVideoMode *pModes, int MaxModes); - + }; #endif diff --git a/src/engine/client/input.cpp b/src/engine/client/input.cpp index 5cd58342..0b4a44a4 100644 --- a/src/engine/client/input.cpp +++ b/src/engine/client/input.cpp @@ -154,7 +154,7 @@ int CInput::Update() // skip private use area of the BMP(contains the unicodes for keyboard function keys on MacOS) if(Event.key.keysym.unicode < 0xE000 || Event.key.keysym.unicode > 0xF8FF) // ignore_convention AddEvent(Event.key.keysym.unicode, 0, 0); // ignore_convention - Key = Event.key.keysym.sym; // ignore_convention + Key = Event.key.keysym.sym; // ignore_convention break; case SDL_KEYUP: Action = IInput::FLAG_RELEASE; diff --git a/src/engine/client/serverbrowser.cpp b/src/engine/client/serverbrowser.cpp index 436c8c15..64d06116 100644 --- a/src/engine/client/serverbrowser.cpp +++ b/src/engine/client/serverbrowser.cpp @@ -86,7 +86,7 @@ bool CServerBrowser::SortCompareName(int Index1, int Index2) const CServerEntry *a = m_ppServerlist[Index1]; CServerEntry *b = m_ppServerlist[Index2]; // make sure empty entries are listed last - return (a->m_GotInfo && b->m_GotInfo) || (!a->m_GotInfo && !b->m_GotInfo) ? str_comp(a->m_Info.m_aName, b->m_Info.m_aName) < 0 : + return (a->m_GotInfo && b->m_GotInfo) || (!a->m_GotInfo && !b->m_GotInfo) ? str_comp(a->m_Info.m_aName, b->m_Info.m_aName) < 0 : a->m_GotInfo ? true : false; } @@ -535,7 +535,7 @@ void CServerBrowser::RequestImpl(const NETADDR &Addr, CServerEntry *pEntry) cons Packet.m_Flags = NETSENDFLAG_CONNLESS; Packet.m_DataSize = sizeof(Buffer); Packet.m_pData = Buffer; - + m_pNetClient->Send(&Packet); if(pEntry) @@ -659,7 +659,7 @@ void CServerBrowser::AddFavorite(const NETADDR &Addr) if(pEntry) pEntry->m_Info.m_Favorite = 1; - if(g_Config.m_Debug) + if(g_Config.m_Debug) { char aAddrStr[NETADDR_MAXSTRSIZE]; net_addr_str(&Addr, aAddrStr, sizeof(aAddrStr)); @@ -705,7 +705,7 @@ int CServerBrowser::LoadingProgression() const { if(m_NumServers == 0) return 0; - + int Servers = m_NumServers; int Loaded = m_NumServers-m_NumRequests; return 100.0f * Loaded/Servers; diff --git a/src/engine/client/serverbrowser.h b/src/engine/client/serverbrowser.h index e0d39aad..a9111d15 100644 --- a/src/engine/client/serverbrowser.h +++ b/src/engine/client/serverbrowser.h @@ -103,7 +103,7 @@ private: CServerEntry *Find(const NETADDR &Addr); CServerEntry *Add(const NETADDR &Addr); - + void RemoveRequest(CServerEntry *pEntry); void QueueRequest(CServerEntry *pEntry); diff --git a/src/engine/client/text.cpp b/src/engine/client/text.cpp index da91980d..b0896b92 100644 --- a/src/engine/client/text.cpp +++ b/src/engine/client/text.cpp @@ -36,7 +36,7 @@ static int aFontSizes[] = {8,9,10,11,12,13,14,15,16,17,18,19,20,36,64}; struct CFontChar { int m_ID; - + // these values are scaled to the pFont size // width * font_size == real_size float m_Width; @@ -44,7 +44,7 @@ struct CFontChar float m_OffsetX; float m_OffsetY; float m_AdvanceX; - + float m_aUvs[4]; int64 m_TouchTime; }; @@ -57,16 +57,16 @@ struct CFontSizeData GLuint m_aTextures[2]; int m_TextureWidth; int m_TextureHeight; - + int m_NumXChars; int m_NumYChars; - + int m_CharMaxWidth; int m_CharMaxHeight; - + CFontChar m_aCharacters[MAX_CHARACTERS*MAX_CHARACTERS]; - - int m_CurrentCharacter; + + int m_CurrentCharacter; }; class CFont @@ -82,7 +82,7 @@ class CTextRender : public IEngineTextRender { IGraphics *m_pGraphics; IGraphics *Graphics() { return m_pGraphics; } - + int WordLength(const char *pText) { int s = 1; @@ -106,13 +106,13 @@ class CTextRender : public IEngineTextRender float m_TextOutlineG; float m_TextOutlineB; float m_TextOutlineA; - + int m_FontTextureFormat; CFont *m_pDefaultFont; FT_Library m_FTLibrary; - + int GetFontSizeIndex(int Pixelsize) { for(unsigned i = 0; i < NUM_FONT_SIZES; i++) @@ -120,18 +120,18 @@ class CTextRender : public IEngineTextRender if(aFontSizes[i] >= Pixelsize) return i; } - + return NUM_FONT_SIZES-1; } - + void Grow(unsigned char *pIn, unsigned char *pOut, int w, int h) { - for(int y = 0; y < h; y++) - for(int x = 0; x < w; x++) - { - int c = pIn[y*w+x]; + for(int y = 0; y < h; y++) + for(int x = 0; x < w; x++) + { + int c = pIn[y*w+x]; for(int sy = -1; sy <= 1; sy++) for(int sx = -1; sx <= 1; sx++) @@ -142,7 +142,7 @@ class CTextRender : public IEngineTextRender { int Index = GetY*w+GetX; if(pIn[Index] > c) - c = pIn[Index]; + c = pIn[Index]; } } @@ -157,18 +157,18 @@ class CTextRender : public IEngineTextRender int Height = CharHeight*Ychars; void *pMem = mem_alloc(Width*Height, 1); mem_zero(pMem, Width*Height); - + if(pSizeData->m_aTextures[0] == 0) glGenTextures(2, pSizeData->m_aTextures); else FontMemoryUsage -= pSizeData->m_TextureWidth*pSizeData->m_TextureHeight*2; - + pSizeData->m_NumXChars = Xchars; pSizeData->m_NumYChars = Ychars; pSizeData->m_TextureWidth = Width; pSizeData->m_TextureHeight = Height; pSizeData->m_CurrentCharacter = 0; - + for(int i = 0; i < 2; i++) { glBindTexture(GL_TEXTURE_2D, pSizeData->m_aTextures[i]); @@ -177,9 +177,9 @@ class CTextRender : public IEngineTextRender glTexImage2D(GL_TEXTURE_2D, 0, m_FontTextureFormat, Width, Height, 0, m_FontTextureFormat, GL_UNSIGNED_BYTE, pMem); FontMemoryUsage += Width*Height; } - + dbg_msg("", "pFont memory usage: %d", FontMemoryUsage); - + mem_free(pMem); } @@ -198,43 +198,43 @@ class CTextRender : public IEngineTextRender pSizeData->m_NumXChars <<= 1; else pSizeData->m_NumYChars <<= 1; - InitTexture(pSizeData, pSizeData->m_CharMaxWidth, pSizeData->m_CharMaxHeight, pSizeData->m_NumXChars, pSizeData->m_NumYChars); + InitTexture(pSizeData, pSizeData->m_CharMaxWidth, pSizeData->m_CharMaxHeight, pSizeData->m_NumXChars, pSizeData->m_NumYChars); } - - + + // TODO: Refactor: move this into a pFont class void InitIndex(CFont *pFont, int Index) { CFontSizeData *pSizeData = &pFont->m_aSizes[Index]; - + pSizeData->m_FontSize = aFontSizes[Index]; FT_Set_Pixel_Sizes(pFont->m_FtFace, 0, pSizeData->m_FontSize); - + int OutlineThickness = AdjustOutlineThicknessToFontSize(1, pSizeData->m_FontSize); - + { unsigned GlyphIndex; int MaxH = 0; int MaxW = 0; - + int Charcode = FT_Get_First_Char(pFont->m_FtFace, &GlyphIndex); while(GlyphIndex != 0) - { + { // do stuff FT_Load_Glyph(pFont->m_FtFace, GlyphIndex, FT_LOAD_DEFAULT); - + if(pFont->m_FtFace->glyph->metrics.width > MaxW) MaxW = pFont->m_FtFace->glyph->metrics.width; // ignore_convention if(pFont->m_FtFace->glyph->metrics.height > MaxH) MaxH = pFont->m_FtFace->glyph->metrics.height; // ignore_convention Charcode = FT_Get_Next_Char(pFont->m_FtFace, Charcode, &GlyphIndex); } - + MaxW = (MaxW>>6)+2+OutlineThickness*2; MaxH = (MaxH>>6)+2+OutlineThickness*2; - + for(pSizeData->m_CharMaxWidth = 1; pSizeData->m_CharMaxWidth < MaxW; pSizeData->m_CharMaxWidth <<= 1); for(pSizeData->m_CharMaxHeight = 1; pSizeData->m_CharMaxHeight < MaxH; pSizeData->m_CharMaxHeight <<= 1); } - + //dbg_msg("pFont", "init size %d, texture size %d %d", pFont->sizes[index].font_size, w, h); //FT_New_Face(m_FTLibrary, "data/fonts/vera.ttf", 0, &pFont->ft_face); InitTexture(pSizeData, pSizeData->m_CharMaxWidth, pSizeData->m_CharMaxHeight, 8, 8); @@ -253,7 +253,7 @@ class CTextRender : public IEngineTextRender { int x = (SlotID%pSizeData->m_NumXChars) * (pSizeData->m_TextureWidth/pSizeData->m_NumXChars); int y = (SlotID/pSizeData->m_NumXChars) * (pSizeData->m_TextureHeight/pSizeData->m_NumYChars); - + glBindTexture(GL_TEXTURE_2D, pSizeData->m_aTextures[Texnum]); glTexSubImage2D(GL_TEXTURE_2D, 0, x, y, pSizeData->m_TextureWidth/pSizeData->m_NumXChars, @@ -284,13 +284,13 @@ class CTextRender : public IEngineTextRender if(pSizeData->m_aCharacters[i].m_TouchTime < pSizeData->m_aCharacters[Oldest].m_TouchTime) Oldest = i; } - + if(time_get()-pSizeData->m_aCharacters[Oldest].m_TouchTime < time_freq()) { IncreaseTextureSize(pSizeData); return GetSlot(pSizeData); } - + return Oldest; } } @@ -315,12 +315,12 @@ class CTextRender : public IEngineTextRender } pBitmap = &pFont->m_FtFace->glyph->bitmap; // ignore_convention - + // fetch slot SlotID = GetSlot(pSizeData); if(SlotID < 0) return -1; - + // adjust spacing int OutlineThickness = AdjustOutlineThicknessToFontSize(1, pSizeData->m_FontSize); x += OutlineThickness; @@ -337,7 +337,7 @@ class CTextRender : public IEngineTextRender } else if(pBitmap->pixel_mode == FT_PIXEL_MODE_MONO) // ignore_convention { - for(py = 0; py < pBitmap->rows; py++) // ignore_convention + for(py = 0; py < pBitmap->rows; py++) // ignore_convention for(px = 0; px < pBitmap->width; px++) // ignore_convention { if(pBitmap->buffer[py*pBitmap->pitch+px/8]&(1<<(7-(px%8)))) // ignore_convention @@ -345,13 +345,13 @@ class CTextRender : public IEngineTextRender } } - if(0) for(py = 0; py < SlotW; py++) - for(px = 0; px < SlotH; px++) + if(0) for(py = 0; py < SlotW; py++) + for(px = 0; px < SlotH; px++) ms_aGlyphData[py*SlotW+px] = 255; - + // upload the glyph UploadGlyph(pSizeData, 0, SlotID, Chr, ms_aGlyphData); - + if(OutlineThickness == 1) { Grow(ms_aGlyphData, ms_aGlyphDataOutlined, SlotW, SlotH); @@ -366,7 +366,7 @@ class CTextRender : public IEngineTextRender } UploadGlyph(pSizeData, 1, SlotID, Chr, ms_aGlyphData); } - + // set char info { CFontChar *pFontchr = &pSizeData->m_aCharacters[SlotID]; @@ -375,27 +375,27 @@ class CTextRender : public IEngineTextRender float Vscale = 1.0f/pSizeData->m_TextureHeight; int Height = pBitmap->rows + OutlineThickness*2 + 2; // ignore_convention int Width = pBitmap->width + OutlineThickness*2 + 2; // ignore_convention - + pFontchr->m_ID = Chr; pFontchr->m_Height = Height * Scale; pFontchr->m_Width = Width * Scale; pFontchr->m_OffsetX = (pFont->m_FtFace->glyph->bitmap_left-1) * Scale; // ignore_convention pFontchr->m_OffsetY = (pSizeData->m_FontSize - pFont->m_FtFace->glyph->bitmap_top) * Scale; // ignore_convention pFontchr->m_AdvanceX = (pFont->m_FtFace->glyph->advance.x>>6) * Scale; // ignore_convention - + pFontchr->m_aUvs[0] = (SlotID%pSizeData->m_NumXChars) / (float)(pSizeData->m_NumXChars); pFontchr->m_aUvs[1] = (SlotID/pSizeData->m_NumXChars) / (float)(pSizeData->m_NumYChars); pFontchr->m_aUvs[2] = pFontchr->m_aUvs[0] + Width*Uscale; pFontchr->m_aUvs[3] = pFontchr->m_aUvs[1] + Height*Vscale; } - + return SlotID; } CFontChar *GetChar(CFont *pFont, CFontSizeData *pSizeData, int Chr) { CFontChar *pFontchr = NULL; - + // search for the character // TODO: remove this linear search int i; @@ -407,7 +407,7 @@ class CTextRender : public IEngineTextRender break; } } - + // check if we need to render the character if(!pFontchr) { @@ -415,12 +415,12 @@ class CTextRender : public IEngineTextRender if(Index >= 0) pFontchr = &pSizeData->m_aCharacters[Index]; } - + // touch the character // TODO: don't call time_get here if(pFontchr) pFontchr->m_TouchTime = time_get(); - + return pFontchr; } @@ -436,8 +436,8 @@ class CTextRender : public IEngineTextRender FT_Get_Kerning(pFont->m_FtFace, Left, Right, FT_KERNING_DEFAULT, &Kerning); return (Kerning.x>>6); } - - + + public: CTextRender() { @@ -457,21 +457,21 @@ public: // GL_LUMINANCE can be good for debugging m_FontTextureFormat = GL_ALPHA; } - + virtual void Init() { m_pGraphics = Kernel()->RequestInterface<IGraphics>(); FT_Init_FreeType(&m_FTLibrary); } - + virtual CFont *LoadFont(const char *pFilename) { CFont *pFont = (CFont *)mem_alloc(sizeof(CFont), 1); - + mem_zero(pFont, sizeof(*pFont)); str_copy(pFont->m_aFilename, pFilename, sizeof(pFont->m_aFilename)); - + if(FT_New_Face(m_FTLibrary, pFont->m_aFilename, 0, &pFont->m_FtFace)) { mem_free(pFont); @@ -480,7 +480,7 @@ public: for(unsigned i = 0; i < NUM_FONT_SIZES; i++) pFont->m_aSizes[i].m_FontSize = -1; - + dbg_msg("textrender", "loaded pFont from '%s'", pFilename); return pFont; }; @@ -495,8 +495,8 @@ public: dbg_msg("textrender", "default pFont set %p", pFont); m_pDefaultFont = pFont; } - - + + virtual void SetCursor(CTextCursor *pCursor, float x, float y, float FontSize, int Flags) { mem_zero(pCursor, sizeof(*pCursor)); @@ -510,8 +510,8 @@ public: pCursor->m_Flags = Flags; pCursor->m_CharCount = 0; } - - + + virtual void Text(void *pFontSetV, float x, float y, float Size, const char *pText, int MaxWidth) { CTextCursor Cursor; @@ -527,7 +527,7 @@ public: TextEx(&Cursor, pText, Length); return Cursor.m_X; } - + virtual int TextLineCount(void *pFontSetV, float Size, const char *pText, float LineWidth) { CTextCursor Cursor; @@ -552,12 +552,12 @@ public: m_TextOutlineB = b; m_TextOutlineA = a; } - + virtual void TextEx(CTextCursor *pCursor, const char *pText, int Length) { CFont *pFont = pCursor->m_pFont; CFontSizeData *pSizeData = NULL; - + //dbg_msg("textrender", "rendering text '%s'", text); float ScreenX0, ScreenY0, ScreenX1, ScreenY1; @@ -576,7 +576,7 @@ public: // to correct coords, convert to screen coords, round, and convert back Graphics()->GetScreen(&ScreenX0, &ScreenY0, &ScreenX1, &ScreenY1); - + FakeToScreenX = (Graphics()->ScreenWidth()/(ScreenX1-ScreenX0)); FakeToScreenY = (Graphics()->ScreenHeight()/(ScreenY1-ScreenY0)); ActualX = (int)(pCursor->m_X * FakeToScreenX); @@ -592,7 +592,7 @@ public: // fetch pFont data if(!pFont) pFont = m_pDefaultFont; - + if(!pFont) return; @@ -600,11 +600,11 @@ public: RenderSetup(pFont, ActualSize); float Scale = 1/pSizeData->m_FontSize; - + // set length if(Length < 0) Length = str_length(pText); - + pEnd = pText + Length; // if we don't want to render, we can just skip the first outline pass @@ -649,7 +649,7 @@ public: Compare.m_Flags &= ~TEXTFLAG_RENDER; Compare.m_LineWidth = -1; TextEx(&Compare, pText, Wlen); - + if(Compare.m_X-DrawX > pCursor->m_LineWidth) { // word can't be fitted in one line, cut it @@ -659,11 +659,11 @@ public: Cutter.m_Y = DrawY; Cutter.m_Flags &= ~TEXTFLAG_RENDER; Cutter.m_Flags |= TEXTFLAG_STOP_AT_END; - + TextEx(&Cutter, (const char *)pCurrent, Wlen); Wlen = Cutter.m_CharCount; NewLine = 1; - + if(Wlen <= 3) // if we can't place 3 chars of the word on this line, take the next Wlen = 0; } @@ -672,10 +672,10 @@ public: NewLine = 1; Wlen = 0; } - + pBatchEnd = pCurrent + Wlen; } - + const char *pTmp = pCurrent; int NextCharacter = str_utf8_decode(&pTmp); while(pCurrent < pBatchEnd) @@ -683,7 +683,7 @@ public: int Character = NextCharacter; pCurrent = pTmp; NextCharacter = str_utf8_decode(&pTmp); - + if(Character == '\n') { DrawX = pCursor->m_StartX; @@ -718,14 +718,14 @@ public: pCursor->m_CharCount++; } } - + if(NewLine) { DrawX = pCursor->m_StartX; DrawY += Size; GotNewLine = 1; DrawX = (int)(DrawX * FakeToScreenX) / FakeToScreenX; // realign - DrawY = (int)(DrawY * FakeToScreenY) / FakeToScreenY; + DrawY = (int)(DrawY * FakeToScreenY) / FakeToScreenY; ++LineCount; } } @@ -736,11 +736,11 @@ public: pCursor->m_X = DrawX; pCursor->m_LineCount = LineCount; - + if(GotNewLine) pCursor->m_Y = DrawY; } - + }; IEngineTextRender *CreateEngineTextRender() { return new CTextRender; } diff --git a/src/engine/config.h b/src/engine/config.h index 7e00cf65..35ef9fb9 100644 --- a/src/engine/config.h +++ b/src/engine/config.h @@ -15,9 +15,9 @@ public: virtual void Reset() = 0; virtual void RestoreStrings() = 0; virtual void Save() = 0; - + virtual void RegisterCallback(SAVECALLBACKFUNC pfnFunc, void *pUserData) = 0; - + virtual void WriteLine(const char *pLine) = 0; }; diff --git a/src/engine/console.h b/src/engine/console.h index 77de927e..f8ec67b0 100644 --- a/src/engine/console.h +++ b/src/engine/console.h @@ -25,14 +25,14 @@ public: public: IResult() { m_NumArgs = 0; } virtual ~IResult() {} - + virtual int GetInteger(unsigned Index) = 0; virtual float GetFloat(unsigned Index) = 0; virtual const char *GetString(unsigned Index) = 0; - + int NumArguments() const { return m_NumArgs; } }; - + class CCommandInfo { public: @@ -50,16 +50,16 @@ public: virtual void PossibleCommands(const char *pStr, int FlagMask, FPossibleCallback pfnCallback, void *pUser) = 0; virtual void ParseArguments(int NumArgs, const char **ppArguments) = 0; - virtual void Register(const char *pName, const char *pParams, + virtual void Register(const char *pName, const char *pParams, int Flags, FCommandCallback pfnFunc, void *pUser, const char *pHelp) = 0; virtual void Chain(const char *pName, FChainCommandCallback pfnChainFunc, void *pUser) = 0; virtual void StoreCommands(bool Store) = 0; - + virtual bool LineIsValid(const char *pStr) = 0; virtual void ExecuteLine(const char *Sptr) = 0; virtual void ExecuteLineStroked(int Stroke, const char *pStr) = 0; virtual void ExecuteFile(const char *pFilename) = 0; - + virtual void RegisterPrintCallback(FPrintCallback pfnPrintCallback, void *pUserData) = 0; virtual void Print(int Level, const char *pFrom, const char *pStr) = 0; }; diff --git a/src/engine/friends.h b/src/engine/friends.h index 50e5ef1f..bf9df904 100644 --- a/src/engine/friends.h +++ b/src/engine/friends.h @@ -21,11 +21,11 @@ public: { MAX_FRIENDS=128, }; - + virtual void Init() = 0; - + virtual int NumFriends() const = 0; - virtual const CFriendInfo *GetFriend(int Index) const = 0; + virtual const CFriendInfo *GetFriend(int Index) const = 0; virtual bool IsFriend(const char *pName, const char *pClan, bool PlayersOnly) const = 0; virtual void AddFriend(const char *pName, const char *pClan) = 0; diff --git a/src/engine/graphics.h b/src/engine/graphics.h index de99caac..0912bfb5 100644 --- a/src/engine/graphics.h +++ b/src/engine/graphics.h @@ -19,11 +19,11 @@ public: /* Variable: width Contains the width of the image */ int m_Width; - + /* Variable: height Contains the height of the image */ int m_Height; - + /* Variable: format Contains the format of the image. See <Image Formats> for more information. */ int m_Format; @@ -61,27 +61,27 @@ public: int ScreenWidth() const { return m_ScreenWidth; } int ScreenHeight() const { return m_ScreenHeight; } float ScreenAspect() const { return (float)ScreenWidth()/(float)ScreenHeight(); } - + virtual void Clear(float r, float g, float b) = 0; - + virtual void ClipEnable(int x, int y, int w, int h) = 0; virtual void ClipDisable() = 0; - + virtual void MapScreen(float TopLeftX, float TopLeftY, float BottomRightX, float BottomRightY) = 0; virtual void GetScreen(float *pTopLeftX, float *pTopLeftY, float *pBottomRightX, float *pBottomRightY) = 0; - + // TODO: These should perhaps not be virtuals virtual void BlendNone() = 0; virtual void BlendNormal() = 0; virtual void BlendAdditive() = 0; virtual int MemoryUsage() const = 0; - + virtual int LoadPNG(CImageInfo *pImg, const char *pFilename, int StorageType) =0; virtual int UnloadTexture(int Index) = 0; virtual int LoadTextureRaw(int Width, int Height, int Format, const void *pData, int StoreFormat, int Flags) = 0; virtual int LoadTexture(const char *pFilename, int StorageType, int StoreFormat, int Flags) = 0; virtual void TextureSet(int TextureID) = 0; - + struct CLineItem { float m_X0, m_Y0, m_X1, m_Y1; @@ -91,13 +91,13 @@ public: virtual void LinesBegin() = 0; virtual void LinesEnd() = 0; virtual void LinesDraw(const CLineItem *pArray, int Num) = 0; - + virtual void QuadsBegin() = 0; virtual void QuadsEnd() = 0; virtual void QuadsSetRotation(float Angle) = 0; virtual void QuadsSetSubset(float TopLeftY, float TopLeftV, float BottomRightU, float BottomRightV) = 0; virtual void QuadsSetSubsetFree(float x0, float y0, float x1, float y1, float x2, float y2, float x3, float y3) = 0; - + struct CQuadItem { float m_X, m_Y, m_Width, m_Height; @@ -106,7 +106,7 @@ public: }; virtual void QuadsDraw(CQuadItem *pArray, int Num) = 0; virtual void QuadsDrawTL(const CQuadItem *pArray, int Num) = 0; - + struct CFreeformItem { float m_X0, m_Y0, m_X1, m_Y1, m_X2, m_Y2, m_X3, m_Y3; @@ -116,7 +116,7 @@ public: }; virtual void QuadsDrawFreeform(const CFreeformItem *pArray, int Num) = 0; virtual void QuadsText(float x, float y, float Size, float r, float g, float b, float a, const char *pText) = 0; - + struct CColorVertex { int m_Index; @@ -126,7 +126,7 @@ public: }; virtual void SetColorVertex(const CColorVertex *pArray, int Num) = 0; virtual void SetColor(float r, float g, float b, float a) = 0; - + virtual void TakeScreenshot(const char *pFilename) = 0; virtual int GetVideoModes(CVideoMode *pModes, int MaxModes) = 0; @@ -139,13 +139,13 @@ class IEngineGraphics : public IGraphics public: virtual bool Init() = 0; virtual void Shutdown() = 0; - + virtual void Minimize() = 0; virtual void Maximize() = 0; - + virtual int WindowActive() = 0; virtual int WindowOpen() = 0; - + }; extern IEngineGraphics *CreateEngineGraphics(); diff --git a/src/engine/input.h b/src/engine/input.h index aa9be78f..7d28be10 100644 --- a/src/engine/input.h +++ b/src/engine/input.h @@ -41,7 +41,7 @@ protected: int KeyWasPressed(int Key) { return m_aInputState[m_InputCurrent^1][Key]; } -public: +public: enum { FLAG_PRESS=1, @@ -53,7 +53,7 @@ public: int NumEvents() const { return m_NumEvents; } void ClearEvents() { m_NumEvents = 0; } CEvent GetEvent(int Index) const - { + { if(Index < 0 || Index >= m_NumEvents) { IInput::CEvent e = {0,0}; @@ -61,19 +61,19 @@ public: } return m_aInputEvents[Index]; } - + // keys int KeyPressed(int Key) { return m_aInputState[m_InputCurrent][Key]; } int KeyReleases(int Key) { return m_aInputCount[m_InputCurrent][Key].m_Releases; } int KeyPresses(int Key) { return m_aInputCount[m_InputCurrent][Key].m_Presses; } int KeyDown(int Key) { return KeyPressed(Key)&&!KeyWasPressed(Key); } const char *KeyName(int Key) { return (Key >= 0 && Key < 512) ? g_aaKeyStrings[Key] : g_aaKeyStrings[0]; } - + // virtual void MouseModeRelative() = 0; virtual void MouseModeAbsolute() = 0; virtual int MouseDoubleClick() = 0; - + virtual void MouseRelative(float *x, float *y) = 0; }; diff --git a/src/engine/kernel.h b/src/engine/kernel.h index 288f49ab..b5961bc3 100644 --- a/src/engine/kernel.h +++ b/src/engine/kernel.h @@ -18,7 +18,7 @@ protected: public: IInterface() : m_pKernel(0) {} virtual ~IInterface() {} - + //virtual unsigned InterfaceID() = 0; //virtual const char *InterfaceName() = 0; }; @@ -27,7 +27,7 @@ public: public: \ static const char *InterfaceName() { return Name; } \ private: - + //virtual unsigned InterfaceID() { return INTERFACE_ID; } //virtual const char *InterfaceName() { return name; } @@ -55,7 +55,7 @@ public: { return ReregisterInterfaceImpl(TINTERFACE::InterfaceName(), pInterface); } - + // Usage example: // IMyInterface *pMyHandle = Kernel()->RequestInterface<IMyInterface>() template<class TINTERFACE> diff --git a/src/engine/server.h b/src/engine/server.h index c27365ca..28dc3d11 100644 --- a/src/engine/server.h +++ b/src/engine/server.h @@ -21,7 +21,7 @@ public: const char *m_pName; int m_Latency; }; - + int Tick() const { return m_CurrentGameTick; } int TickSpeed() const { return m_TickSpeed; } @@ -32,7 +32,7 @@ public: virtual int GetClientInfo(int ClientID, CClientInfo *pInfo) = 0; virtual void GetClientAddr(int ClientID, char *pAddrStr, int Size) = 0; virtual int *LatestInput(int ClientID, int *pSize) = 0; - + virtual int SendMsg(CMsgPacker *pMsg, int Flags, int ClientID) = 0; template<class T> @@ -43,18 +43,18 @@ public: return -1; return SendMsg(&Packer, Flags, ClientID); } - + virtual void SetClientName(int ClientID, char const *pName) = 0; virtual void SetClientClan(int ClientID, char const *pClan) = 0; virtual void SetClientCountry(int ClientID, int Country) = 0; virtual void SetClientScore(int ClientID, int Score) = 0; - + virtual int SnapNewID() = 0; virtual void SnapFreeID(int ID) = 0; virtual void *SnapNewItem(int Type, int ID, int Size) = 0; virtual void SnapSetStaticsize(int ItemType, int Size) = 0; - + virtual bool IsAuthed(int ClientID) = 0; virtual void Kick(int ClientID, const char *pReason) = 0; }; @@ -67,12 +67,12 @@ public: virtual void OnInit() = 0; virtual void OnConsoleInit() = 0; virtual void OnShutdown() = 0; - + virtual void OnTick() = 0; virtual void OnPreSnap() = 0; virtual void OnSnap(int ClientID) = 0; virtual void OnPostSnap() = 0; - + virtual void OnMessage(int MsgID, CUnpacker *pUnpacker, int ClientID) = 0; virtual void OnClientConnected(int ClientID) = 0; @@ -83,7 +83,7 @@ public: virtual bool IsClientReady(int ClientID) = 0; virtual bool IsClientPlayer(int ClientID) = 0; - + virtual const char *GameType() = 0; virtual const char *Version() = 0; virtual const char *NetVersion() = 0; diff --git a/src/engine/server/register.cpp b/src/engine/server/register.cpp index 0b53c67c..0b7eb948 100644 --- a/src/engine/server/register.cpp +++ b/src/engine/server/register.cpp @@ -41,15 +41,15 @@ void CRegister::RegisterSendFwcheckresponse(NETADDR *pAddr) Packet.m_pData = SERVERBROWSE_FWRESPONSE; m_pNetServer->Send(&Packet); } - + void CRegister::RegisterSendHeartbeat(NETADDR Addr) { static unsigned char aData[sizeof(SERVERBROWSE_HEARTBEAT) + 2]; unsigned short Port = g_Config.m_SvPort; CNetChunk Packet; - + mem_copy(aData, SERVERBROWSE_HEARTBEAT, sizeof(SERVERBROWSE_HEARTBEAT)); - + Packet.m_ClientID = -1; Packet.m_Address = Addr; Packet.m_Flags = NETSENDFLAG_CONNLESS; @@ -118,7 +118,7 @@ void CRegister::RegisterUpdate(int Nettype) else if(m_RegisterState == REGISTERSTATE_UPDATE_ADDRS) { m_RegisterRegisteredServer = -1; - + if(!m_pMasterServer->IsRefreshing()) { int i; @@ -137,7 +137,7 @@ void CRegister::RegisterUpdate(int Nettype) m_aMasterserverInfo[i].m_Count = -1; m_aMasterserverInfo[i].m_LastSend = 0; } - + m_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, "register", "fetching server counts"); RegisterNewState(REGISTERSTATE_QUERY_COUNT); } @@ -149,7 +149,7 @@ void CRegister::RegisterUpdate(int Nettype) { if(!m_aMasterserverInfo[i].m_Valid) continue; - + if(m_aMasterserverInfo[i].m_Count == -1) { Left++; @@ -160,7 +160,7 @@ void CRegister::RegisterUpdate(int Nettype) } } } - + // check if we are done or timed out if(Left == 0 || Now > m_RegisterStateStart+Freq*3) { @@ -171,7 +171,7 @@ void CRegister::RegisterUpdate(int Nettype) { if(!m_aMasterserverInfo[i].m_Valid || m_aMasterserverInfo[i].m_Count == -1) continue; - + if(Best == -1 || m_aMasterserverInfo[i].m_Count < m_aMasterserverInfo[Best].m_Count) Best = i; } @@ -184,7 +184,7 @@ void CRegister::RegisterUpdate(int Nettype) RegisterNewState(REGISTERSTATE_ERROR); } else - { + { char aBuf[256]; str_format(aBuf, sizeof(aBuf), "chose '%s' as master, sending heartbeats", m_pMasterServer->GetName(m_RegisterRegisteredServer)); m_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, "register", aBuf); @@ -201,7 +201,7 @@ void CRegister::RegisterUpdate(int Nettype) m_aMasterserverInfo[m_RegisterRegisteredServer].m_LastSend = Now; RegisterSendHeartbeat(m_aMasterserverInfo[m_RegisterRegisteredServer].m_Addr); } - + if(Now > m_RegisterStateStart+Freq*60) { m_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, "register", "WARNING: Master server is not responding, switching master"); @@ -212,9 +212,9 @@ void CRegister::RegisterUpdate(int Nettype) { if(m_RegisterFirst) m_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, "register", "server registered"); - + m_RegisterFirst = 0; - + // check if we should send new heartbeat again if(Now > m_RegisterStateStart+Freq) { @@ -253,7 +253,7 @@ int CRegister::RegisterProcessPacket(CNetChunk *pPacket) } if(!Valid) return 0; - + if(pPacket->m_DataSize == sizeof(SERVERBROWSE_FWCHECK) && mem_comp(pPacket->m_pData, SERVERBROWSE_FWCHECK, sizeof(SERVERBROWSE_FWCHECK)) == 0) { diff --git a/src/engine/server/server.cpp b/src/engine/server/server.cpp index 3878ece1..266b9130 100644 --- a/src/engine/server/server.cpp +++ b/src/engine/server/server.cpp @@ -26,7 +26,7 @@ #include "register.h" #include "server.h" -#if defined(CONF_FAMILY_WINDOWS) +#if defined(CONF_FAMILY_WINDOWS) #define _WIN32_WINNT 0x0501 #define WIN32_LEAN_AND_MEAN #include <windows.h> @@ -75,7 +75,7 @@ void CSnapIDPool::Reset() m_aIDs[i].m_Next = i+1; m_aIDs[i].m_State = 0; } - + m_aIDs[MAX_IDS-1].m_Next = -1; m_FirstFree = 0; m_FirstTimed = -1; @@ -88,17 +88,17 @@ void CSnapIDPool::Reset() void CSnapIDPool::RemoveFirstTimeout() { int NextTimed = m_aIDs[m_FirstTimed].m_Next; - + // add it to the free list m_aIDs[m_FirstTimed].m_Next = m_FirstFree; m_aIDs[m_FirstTimed].m_State = 0; m_FirstFree = m_FirstTimed; - + // remove it from the timed list m_FirstTimed = NextTimed; if(m_FirstTimed == -1) m_LastTimed = -1; - + m_Usage--; } @@ -109,7 +109,7 @@ int CSnapIDPool::NewID() // process timed ids while(m_FirstTimed != -1 && m_aIDs[m_FirstTimed].m_Timeout < Now) RemoveFirstTimeout(); - + int ID = m_FirstFree; dbg_assert(ID != -1, "id error"); if(ID == -1) @@ -138,7 +138,7 @@ void CSnapIDPool::FreeID(int ID) m_aIDs[ID].m_State = 2; m_aIDs[ID].m_Timeout = time_get()+time_freq()*5; m_aIDs[ID].m_Next = -1; - + if(m_LastTimed != -1) { m_aIDs[m_LastTimed].m_Next = ID; @@ -150,7 +150,7 @@ void CSnapIDPool::FreeID(int ID) m_LastTimed = ID; } } - + void CServer::CClient::Reset() { // reset input @@ -169,15 +169,15 @@ void CServer::CClient::Reset() CServer::CServer() : m_DemoRecorder(&m_SnapshotDelta) { m_TickSpeed = SERVER_TICK_SPEED; - + m_pGameServer = 0; - + m_CurrentGameTick = 0; m_RunServer = 1; m_pCurrentMapData = 0; m_CurrentMapSize = 0; - + m_MapReload = 0; m_RconClientID = -1; @@ -202,12 +202,12 @@ int CServer::TrySetClientName(int ClientID, const char *pName) str_format(aBuf, sizeof(aBuf), "'%s' -> '%s'", pName, aTrimmedName); Console()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "server", aBuf); pName = aTrimmedName; - - + + // check for empty names if(!pName[0]) return -1; - + // make sure that two clients doesn't have the same name for(int i = 0; i < MAX_CLIENTS; i++) if(i != ClientID && m_aClients[i].m_State >= CClient::STATE_READY) @@ -227,10 +227,10 @@ void CServer::SetClientName(int ClientID, const char *pName) { if(ClientID < 0 || ClientID >= MAX_CLIENTS || m_aClients[ClientID].m_State < CClient::STATE_READY) return; - + if(!pName) return; - + char aNameTry[MAX_NAME_LENGTH]; str_copy(aNameTry, pName, MAX_NAME_LENGTH); if(TrySetClientName(ClientID, aNameTry)) @@ -249,7 +249,7 @@ void CServer::SetClientClan(int ClientID, const char *pClan) { if(ClientID < 0 || ClientID >= MAX_CLIENTS || m_aClients[ClientID].m_State < CClient::STATE_READY || !pClan) return; - + str_copy(m_aClients[ClientID].m_aClan, pClan, MAX_CLAN_LENGTH); } @@ -257,7 +257,7 @@ void CServer::SetClientCountry(int ClientID, int Country) { if(ClientID < 0 || ClientID >= MAX_CLIENTS || m_aClients[ClientID].m_State < CClient::STATE_READY) return; - + m_aClients[ClientID].m_Country = Country; } @@ -280,7 +280,7 @@ void CServer::Kick(int ClientID, const char *pReason) Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", "you can't kick yourself"); return; } - + m_NetServer.Drop(ClientID, pReason); } @@ -343,7 +343,7 @@ void CServer::GetClientAddr(int ClientID, char *pAddrStr, int Size) net_addr_str(&Addr, pAddrStr, Size); } } - + int *CServer::LatestInput(int ClientID, int *size) { @@ -360,7 +360,7 @@ const char *CServer::ClientName(int ClientID) return m_aClients[ClientID].m_aName; else return "(connecting client)"; - + } const char *CServer::ClientClan(int ClientID) @@ -398,13 +398,13 @@ int CServer::SendMsgEx(CMsgPacker *pMsg, int Flags, int ClientID, bool System) CNetChunk Packet; if(!pMsg) return -1; - + mem_zero(&Packet, sizeof(CNetChunk)); - + Packet.m_ClientID = ClientID; Packet.m_pData = pMsg->Data(); Packet.m_DataSize = pMsg->Size(); - + // HACK: modify the message id in the packet and store the system flag *((unsigned char*)Packet.m_pData) <<= 1; if(System) @@ -414,7 +414,7 @@ int CServer::SendMsgEx(CMsgPacker *pMsg, int Flags, int ClientID, bool System) Packet.m_Flags |= NETSENDFLAG_VITAL; if(Flags&MSGFLAG_FLUSH) Packet.m_Flags |= NETSENDFLAG_FLUSH; - + // write message to demo recorder if(!(Flags&MSGFLAG_NORECORD)) m_DemoRecorder.RecordMessage(pMsg->Data(), pMsg->Size()); @@ -441,7 +441,7 @@ int CServer::SendMsgEx(CMsgPacker *pMsg, int Flags, int ClientID, bool System) void CServer::DoSnapshot() { GameServer()->OnPreSnap(); - + // create snapshot for demo recording if(m_DemoRecorder.IsRecording()) { @@ -452,7 +452,7 @@ void CServer::DoSnapshot() m_SnapshotBuilder.Init(); GameServer()->OnSnap(-1); SnapshotSize = m_SnapshotBuilder.Finish(aData); - + // write snapshot m_DemoRecorder.RecordSnapshot(Tick(), aData, SnapshotSize); } @@ -463,15 +463,15 @@ void CServer::DoSnapshot() // client must be ingame to recive snapshots if(m_aClients[i].m_State != CClient::STATE_INGAME) continue; - + // this client is trying to recover, don't spam snapshots if(m_aClients[i].m_SnapRate == CClient::SNAPRATE_RECOVER && (Tick()%50) != 0) continue; - + // this client is trying to recover, don't spam snapshots if(m_aClients[i].m_SnapRate == CClient::SNAPRATE_INIT && (Tick()%10) != 0) continue; - + { char aData[CSnapshot::MAX_SIZE]; CSnapshot *pData = (CSnapshot*)aData; // Fix compiler warning for strict-aliasing @@ -496,13 +496,13 @@ void CServer::DoSnapshot() // remove old snapshos // keep 3 seconds worth of snapshots m_aClients[i].m_Snapshots.PurgeUntil(m_CurrentGameTick-SERVER_TICK_SPEED*3); - + // save it the snapshot m_aClients[i].m_Snapshots.Add(m_CurrentGameTick, time_get(), SnapshotSize, pData, 0); - + // find snapshot that we can preform delta against EmptySnap.Clear(); - + { DeltashotSize = m_aClients[i].m_Snapshots.Get(m_aClients[i].m_LastAckedSnapshot, 0, &pDeltashot, 0); if(DeltashotSize >= 0) @@ -514,10 +514,10 @@ void CServer::DoSnapshot() m_aClients[i].m_SnapRate = CClient::SNAPRATE_RECOVER; } } - + // create delta DeltaSize = m_SnapshotDelta.CreateDelta(pDeltashot, pData, aDeltaData); - + if(DeltaSize) { // compress it @@ -527,7 +527,7 @@ void CServer::DoSnapshot() SnapshotSize = CVariableInt::Compress(aDeltaData, DeltaSize, aCompData); NumPackets = (SnapshotSize+MaxSize-1)/MaxSize; - + for(int n = 0, Left = SnapshotSize; Left; n++) { int Chunk = Left < MaxSize ? Left : MaxSize; @@ -549,7 +549,7 @@ void CServer::DoSnapshot() Msg.AddInt(m_CurrentGameTick); Msg.AddInt(m_CurrentGameTick-DeltaTick); Msg.AddInt(NumPackets); - Msg.AddInt(n); + Msg.AddInt(n); Msg.AddInt(Crc); Msg.AddInt(Chunk); Msg.AddRaw(&aCompData[n*MaxSize], Chunk); @@ -587,7 +587,7 @@ int CServer::NewClientCallback(int ClientID, void *pUser) int CServer::DelClientCallback(int ClientID, const char *pReason, void *pUser) { CServer *pThis = (CServer *)pUser; - + NETADDR Addr = pThis->m_NetServer.ClientAddr(ClientID); char aAddrStr[NETADDR_MAXSTRSIZE]; net_addr_str(&Addr, aAddrStr, sizeof(aAddrStr)); @@ -598,7 +598,7 @@ int CServer::DelClientCallback(int ClientID, const char *pReason, void *pUser) // notify the mod about the drop if(pThis->m_aClients[ClientID].m_State >= CClient::STATE_READY) pThis->GameServer()->OnClientDrop(ClientID, pReason); - + pThis->m_aClients[ClientID].m_State = CClient::STATE_EMPTY; pThis->m_aClients[ClientID].m_aName[0] = 0; pThis->m_aClients[ClientID].m_aClan[0] = 0; @@ -636,16 +636,16 @@ void CServer::SendRconLineAuthed(const char *pLine, void *pUser) CServer *pThis = (CServer *)pUser; static volatile int ReentryGuard = 0; int i; - + if(ReentryGuard) return; ReentryGuard++; - + for(i = 0; i < MAX_CLIENTS; i++) { if(pThis->m_aClients[i].m_State != CClient::STATE_EMPTY && pThis->m_aClients[i].m_Authed) pThis->SendRconLine(i, pLine); } - + ReentryGuard--; } @@ -655,15 +655,15 @@ void CServer::ProcessClientPacket(CNetChunk *pPacket) NETADDR Addr; CUnpacker Unpacker; Unpacker.Reset(pPacket->m_pData, pPacket->m_DataSize); - + // unpack msgid and system flag int Msg = Unpacker.GetInt(); int Sys = Msg&1; Msg >>= 1; - + if(Unpacker.Error()) return; - + if(Sys) { // system message @@ -680,7 +680,7 @@ void CServer::ProcessClientPacket(CNetChunk *pPacket) m_NetServer.Drop(ClientID, aReason); return; } - + const char *pPassword = Unpacker.GetString(CUnpacker::SANITIZE_CC); if(g_Config.m_Password[0] != 0 && str_comp(g_Config.m_Password, pPassword) != 0) { @@ -688,7 +688,7 @@ void CServer::ProcessClientPacket(CNetChunk *pPacket) m_NetServer.Drop(ClientID, "Wrong password"); return; } - + m_aClients[ClientID].m_State = CClient::STATE_CONNECTING; SendMap(ClientID); } @@ -699,11 +699,11 @@ void CServer::ProcessClientPacket(CNetChunk *pPacket) int ChunkSize = 1024-128; int Offset = Chunk * ChunkSize; int Last = 0; - + // drop faulty map data requests if(Chunk < 0 || Offset > m_CurrentMapSize) return; - + if(Offset+ChunkSize >= m_CurrentMapSize) { ChunkSize = m_CurrentMapSize-Offset; @@ -711,7 +711,7 @@ void CServer::ProcessClientPacket(CNetChunk *pPacket) ChunkSize = 0; Last = 1; } - + CMsgPacker Msg(NETMSG_MAP_DATA); Msg.AddInt(Last); Msg.AddInt(m_CurrentMapCrc); @@ -719,7 +719,7 @@ void CServer::ProcessClientPacket(CNetChunk *pPacket) Msg.AddInt(ChunkSize); Msg.AddRaw(&m_pCurrentMapData[Offset], ChunkSize); SendMsgEx(&Msg, MSGFLAG_VITAL|MSGFLAG_FLUSH, ClientID, true); - + if(g_Config.m_Debug) { char aBuf[256]; @@ -734,7 +734,7 @@ void CServer::ProcessClientPacket(CNetChunk *pPacket) Addr = m_NetServer.ClientAddr(ClientID); char aAddrStr[NETADDR_MAXSTRSIZE]; net_addr_str(&Addr, aAddrStr, sizeof(aAddrStr)); - + char aBuf[256]; str_format(aBuf, sizeof(aBuf), "player is ready. ClientID=%x addr=%s", ClientID, aAddrStr); Console()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "server", aBuf); @@ -750,7 +750,7 @@ void CServer::ProcessClientPacket(CNetChunk *pPacket) Addr = m_NetServer.ClientAddr(ClientID); char aAddrStr[NETADDR_MAXSTRSIZE]; net_addr_str(&Addr, aAddrStr, sizeof(aAddrStr)); - + char aBuf[256]; str_format(aBuf, sizeof(aBuf), "player has entered the game. ClientID=%x addr=%s", ClientID, aAddrStr); Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", aBuf); @@ -762,18 +762,18 @@ void CServer::ProcessClientPacket(CNetChunk *pPacket) { CClient::CInput *pInput; int64 TagTime; - + m_aClients[ClientID].m_LastAckedSnapshot = Unpacker.GetInt(); int IntendedTick = Unpacker.GetInt(); int Size = Unpacker.GetInt(); - + // check for errors if(Unpacker.Error() || Size/4 > MAX_INPUT_SIZE) return; if(m_aClients[ClientID].m_LastAckedSnapshot > 0) m_aClients[ClientID].m_SnapRate = CClient::SNAPRATE_FULL; - + if(m_aClients[ClientID].m_Snapshots.Get(m_aClients[ClientID].m_LastAckedSnapshot, &TagTime, 0, 0) >= 0) m_aClients[ClientID].m_Latency = (int)(((time_get()-TagTime)*1000)/time_freq()); @@ -782,7 +782,7 @@ void CServer::ProcessClientPacket(CNetChunk *pPacket) if(IntendedTick > m_aClients[ClientID].m_LastInputTick) { int TimeLeft = ((TickStartTime(IntendedTick)-time_get())*1000) / time_freq(); - + CMsgPacker Msg(NETMSG_INPUTTIMING); Msg.AddInt(IntendedTick); Msg.AddInt(TimeLeft); @@ -792,20 +792,20 @@ void CServer::ProcessClientPacket(CNetChunk *pPacket) m_aClients[ClientID].m_LastInputTick = IntendedTick; pInput = &m_aClients[ClientID].m_aInputs[m_aClients[ClientID].m_CurrentInput]; - + if(IntendedTick <= Tick()) IntendedTick = Tick()+1; pInput->m_GameTick = IntendedTick; - + for(int i = 0; i < Size/4; i++) pInput->m_aData[i] = Unpacker.GetInt(); - + mem_copy(m_aClients[ClientID].m_LatestInput.m_aData, pInput->m_aData, MAX_INPUT_SIZE*sizeof(int)); - + m_aClients[ClientID].m_CurrentInput++; m_aClients[ClientID].m_CurrentInput %= 200; - + // call the mod with the fresh input data if(m_aClients[ClientID].m_State == CClient::STATE_INGAME) GameServer()->OnClientDirectInput(ClientID, m_aClients[ClientID].m_LatestInput.m_aData); @@ -813,7 +813,7 @@ void CServer::ProcessClientPacket(CNetChunk *pPacket) else if(Msg == NETMSG_RCON_CMD) { const char *pCmd = Unpacker.GetString(); - + if(Unpacker.Error() == 0 && m_aClients[ClientID].m_Authed) { char aBuf[256]; @@ -829,7 +829,7 @@ void CServer::ProcessClientPacket(CNetChunk *pPacket) const char *pPw; Unpacker.GetString(); // login name, not used pPw = Unpacker.GetString(CUnpacker::SANITIZE_CC); - + if(Unpacker.Error() == 0) { if(g_Config.m_SvRconPassword[0] == 0) @@ -841,7 +841,7 @@ void CServer::ProcessClientPacket(CNetChunk *pPacket) CMsgPacker Msg(NETMSG_RCON_AUTH_STATUS); Msg.AddInt(1); SendMsgEx(&Msg, MSGFLAG_VITAL, ClientID, true); - + m_aClients[ClientID].m_Authed = 1; SendRconLine(ClientID, "Authentication successful. Remote console access granted."); char aBuf[256]; @@ -905,7 +905,7 @@ void CServer::ProcessClientPacket(CNetChunk *pPacket) GameServer()->OnMessage(Msg, &Unpacker, ClientID); } } - + void CServer::SendServerInfo(NETADDR *pAddr, int Token) { CNetChunk Packet; @@ -920,17 +920,17 @@ void CServer::SendServerInfo(NETADDR *pAddr, int Token) { if(GameServer()->IsClientPlayer(i)) PlayerCount++; - + ClientCount++; } } - + p.Reset(); p.AddRaw(SERVERBROWSE_INFO, sizeof(SERVERBROWSE_INFO)); str_format(aBuf, sizeof(aBuf), "%d", Token); p.AddString(aBuf, 6); - + p.AddString(GameServer()->Version(), 32); p.AddString(g_Config.m_SvName, 64); p.AddString(GetMapName(), 32); @@ -940,28 +940,28 @@ void CServer::SendServerInfo(NETADDR *pAddr, int Token) // flags int i = 0; - if(g_Config.m_Password[0]) // password set + if(g_Config.m_Password[0]) // password set i |= SERVER_FLAG_PASSWORD; str_format(aBuf, sizeof(aBuf), "%d", i); p.AddString(aBuf, 2); - str_format(aBuf, sizeof(aBuf), "%d", PlayerCount); p.AddString(aBuf, 3); // num players + str_format(aBuf, sizeof(aBuf), "%d", PlayerCount); p.AddString(aBuf, 3); // num players str_format(aBuf, sizeof(aBuf), "%d", m_NetServer.MaxClients()-g_Config.m_SvSpectatorSlots); p.AddString(aBuf, 3); // max players - str_format(aBuf, sizeof(aBuf), "%d", ClientCount); p.AddString(aBuf, 3); // num clients + str_format(aBuf, sizeof(aBuf), "%d", ClientCount); p.AddString(aBuf, 3); // num clients str_format(aBuf, sizeof(aBuf), "%d", m_NetServer.MaxClients()); p.AddString(aBuf, 3); // max clients for(i = 0; i < MAX_CLIENTS; i++) { if(m_aClients[i].m_State != CClient::STATE_EMPTY) { - p.AddString(ClientName(i), MAX_NAME_LENGTH); // client name - p.AddString(ClientClan(i), MAX_CLAN_LENGTH); // client clan - str_format(aBuf, sizeof(aBuf), "%d", m_aClients[i].m_Country); p.AddString(aBuf, 6); // client country - str_format(aBuf, sizeof(aBuf), "%d", m_aClients[i].m_Score); p.AddString(aBuf, 6); // client score - str_format(aBuf, sizeof(aBuf), "%d", GameServer()->IsClientPlayer(i)?1:0); p.AddString(aBuf, 2); // is player? + p.AddString(ClientName(i), MAX_NAME_LENGTH); // client name + p.AddString(ClientClan(i), MAX_CLAN_LENGTH); // client clan + str_format(aBuf, sizeof(aBuf), "%d", m_aClients[i].m_Country); p.AddString(aBuf, 6); // client country + str_format(aBuf, sizeof(aBuf), "%d", m_aClients[i].m_Score); p.AddString(aBuf, 6); // client score + str_format(aBuf, sizeof(aBuf), "%d", GameServer()->IsClientPlayer(i)?1:0); p.AddString(aBuf, 2); // is player? } } - + Packet.m_ClientID = -1; Packet.m_Address = *pAddr; Packet.m_Flags = NETSENDFLAG_CONNLESS; @@ -994,21 +994,21 @@ int CServer::BanAdd(NETADDR Addr, int Seconds, const char *pReason) str_format(aBuf, sizeof(aBuf), "banned %s for life", aAddrStr); Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", aBuf); - return m_NetServer.BanAdd(Addr, Seconds, pReason); + return m_NetServer.BanAdd(Addr, Seconds, pReason); } int CServer::BanRemove(NETADDR Addr) { return m_NetServer.BanRemove(Addr); } - + void CServer::PumpNetwork() { CNetChunk Packet; m_NetServer.Update(); - + // process packets while(m_NetServer.Recv(&Packet)) { @@ -1046,7 +1046,7 @@ int CServer::LoadMap(const char *pMapName) //DATAFILE *df; char aBuf[512]; str_format(aBuf, sizeof(aBuf), "maps/%s.map", pMapName); - + /*df = datafile_load(buf); if(!df) return 0;*/ @@ -1057,25 +1057,25 @@ int CServer::LoadMap(const char *pMapName) Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "mapchecker", "invalid standard map"); return 0; } - + if(!m_pMap->Load(aBuf)) return 0; - + // stop recording when we change map m_DemoRecorder.Stop(); - + // reinit snapshot ids m_IDPool.TimeoutIDs(); - + // get the crc of the map m_CurrentMapCrc = m_pMap->Crc(); char aBufMsg[256]; str_format(aBufMsg, sizeof(aBufMsg), "%s crc is %08x", aBuf, m_CurrentMapCrc); Console()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "server", aBufMsg); - + str_copy(m_aCurrentMap, pMapName, sizeof(m_aCurrentMap)); //map_set(df); - + // load compelate map into memory for download { IOHANDLE File = Storage()->OpenFile(aBuf, IOFLAG_READ, IStorage::TYPE_ALL); @@ -1109,7 +1109,7 @@ int CServer::Run() dbg_msg("server", "failed to load map. mapname='%s'", g_Config.m_SvMap); return -1; } - + // start server NETADDR BindAddr; if(g_Config.m_SvBindaddr[0] && net_host_lookup(g_Config.m_SvBindaddr, &BindAddr, NETTYPE_ALL) == 0) @@ -1123,8 +1123,8 @@ int CServer::Run() BindAddr.type = NETTYPE_ALL; BindAddr.port = g_Config.m_SvPort; } - - + + if(!m_NetServer.Open(BindAddr, g_Config.m_SvMaxClients, g_Config.m_SvMaxClientsPerIP, 0)) { dbg_msg("server", "couldn't open socket. port might already be in use"); @@ -1132,11 +1132,11 @@ int CServer::Run() } m_NetServer.SetCallbacks(NewClientCallback, DelClientCallback, this); - + char aBuf[256]; str_format(aBuf, sizeof(aBuf), "server name is '%s'", g_Config.m_SvName); Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", aBuf); - + GameServer()->OnInit(); str_format(aBuf, sizeof(aBuf), "version %s", GameServer()->NetVersion()); Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", aBuf); @@ -1148,10 +1148,10 @@ int CServer::Run() { int64 ReportTime = time_get(); int ReportInterval = 3; - + m_Lastheartbeat = 0; m_GameStartTime = time_get(); - + if(g_Config.m_Debug) { str_format(aBuf, sizeof(aBuf), "baseline memory usage %dk", mem_stats()->allocated/1024); @@ -1162,28 +1162,28 @@ int CServer::Run() { int64 t = time_get(); int NewTicks = 0; - + // load new map TODO: don't poll this if(str_comp(g_Config.m_SvMap, m_aCurrentMap) != 0 || m_MapReload) { m_MapReload = 0; - + // load map if(LoadMap(g_Config.m_SvMap)) { // new map loaded GameServer()->OnShutdown(); - + for(int c = 0; c < MAX_CLIENTS; c++) { if(m_aClients[c].m_State <= CClient::STATE_AUTH) continue; - + SendMap(c); m_aClients[c].Reset(); m_aClients[c].m_State = CClient::STATE_CONNECTING; } - + m_GameStartTime = time_get(); m_CurrentGameTick = 0; Kernel()->ReregisterInterface(GameServer()); @@ -1197,12 +1197,12 @@ int CServer::Run() str_copy(g_Config.m_SvMap, m_aCurrentMap, sizeof(g_Config.m_SvMap)); } } - + while(t > TickStartTime(m_CurrentGameTick+1)) { m_CurrentGameTick++; NewTicks++; - + // apply new input for(int c = 0; c < MAX_CLIENTS; c++) { @@ -1221,19 +1221,19 @@ int CServer::Run() GameServer()->OnTick(); } - + // snap game if(NewTicks) { if(g_Config.m_SvHighBandwidth || (m_CurrentGameTick%2) == 0) DoSnapshot(); } - + // master server stuff m_Register.RegisterUpdate(BindAddr.type); - + PumpNetwork(); - + if(ReportTime < time_get()) { if(g_Config.m_Debug) @@ -1242,23 +1242,23 @@ int CServer::Run() static NETSTATS prev_stats; NETSTATS stats; netserver_stats(net, &stats); - + perf_next(); - + if(config.dbg_pref) perf_dump(&rootscope); dbg_msg("server", "send=%8d recv=%8d", (stats.send_bytes - prev_stats.send_bytes)/reportinterval, (stats.recv_bytes - prev_stats.recv_bytes)/reportinterval); - + prev_stats = stats; */ } - + ReportTime += time_freq()*ReportInterval; } - + // wait for incomming data net_socket_read_wait(m_NetServer.Socket(), 5); } @@ -1296,14 +1296,14 @@ void CServer::ConBan(IConsole::IResult *pResult, void *pUser) CServer *pServer = (CServer *)pUser; const char *pStr = pResult->GetString(0); int Minutes = 30; - const char *pReason = "No reason given"; - + const char *pReason = "No reason given"; + if(pResult->NumArguments() > 1) Minutes = pResult->GetInteger(1); - + if(pResult->NumArguments() > 2) pReason = pResult->GetString(2); - + if(net_addr_from_str(&Addr, pStr) == 0) { if(pServer->m_RconClientID >= 0 && pServer->m_RconClientID < MAX_CLIENTS && pServer->m_aClients[pServer->m_RconClientID].m_State != CClient::STATE_EMPTY) @@ -1348,7 +1348,7 @@ void CServer::ConUnban(IConsole::IResult *pResult, void *pUser) NETADDR Addr; CServer *pServer = (CServer *)pUser; const char *pStr = pResult->GetString(0); - + if(net_addr_from_str(&Addr, pStr) == 0 && !pServer->BanRemove(Addr)) { char aAddrStr[NETADDR_MAXSTRSIZE]; @@ -1384,7 +1384,7 @@ void CServer::ConBans(IConsole::IResult *pResult, void *pUser) char aBuf[1024]; char aAddrStr[NETADDR_MAXSTRSIZE]; CServer* pServer = (CServer *)pUser; - + int Num = pServer->m_NetServer.BanNum(); for(int i = 0; i < Num; i++) { @@ -1392,7 +1392,7 @@ void CServer::ConBans(IConsole::IResult *pResult, void *pUser) pServer->m_NetServer.BanGet(i, &Info); NETADDR Addr = Info.m_Addr; net_addr_str(&Addr, aAddrStr, sizeof(aAddrStr)); - + if(Info.m_Expires == -1) { str_format(aBuf, sizeof(aBuf), "#%i %s for life", i, aAddrStr); @@ -1480,7 +1480,7 @@ void CServer::ConchainMaxclientsperipUpdate(IConsole::IResult *pResult, void *pU void CServer::RegisterCommands() { m_pConsole = Kernel()->RequestInterface<IConsole>(); - + Console()->Register("kick", "i?r", CFGFLAG_SERVER, ConKick, this, ""); Console()->Register("ban", "s?ir", CFGFLAG_SERVER|CFGFLAG_STORE, ConBan, this, ""); Console()->Register("unban", "s", CFGFLAG_SERVER|CFGFLAG_STORE, ConUnban, this, ""); @@ -1490,14 +1490,14 @@ void CServer::RegisterCommands() Console()->Register("record", "?s", CFGFLAG_SERVER|CFGFLAG_STORE, ConRecord, this, ""); Console()->Register("stoprecord", "", CFGFLAG_SERVER, ConStopRecord, this, ""); - + Console()->Register("reload", "", CFGFLAG_SERVER, ConMapReload, this, ""); Console()->Chain("sv_name", ConchainSpecialInfoupdate, this); Console()->Chain("password", ConchainSpecialInfoupdate, this); Console()->Chain("sv_max_clients_per_ip", ConchainMaxclientsperipUpdate, this); -} +} int CServer::SnapNewID() @@ -1515,7 +1515,7 @@ void *CServer::SnapNewItem(int Type, int ID, int Size) { dbg_assert(Type >= 0 && Type <=0xffff, "incorrect type"); dbg_assert(ID >= 0 && ID <=0xffff, "incorrect id"); - return ID < 0 ? 0 : m_SnapshotBuilder.NewItem(Type, ID, Size); + return ID < 0 ? 0 : m_SnapshotBuilder.NewItem(Type, ID, Size); } void CServer::SnapSetStaticsize(int ItemType, int Size) @@ -1549,7 +1549,7 @@ int main(int argc, const char **argv) // ignore_convention IEngineMasterServer *pEngineMasterServer = CreateEngineMasterServer(); IStorage *pStorage = CreateStorage("Teeworlds", argc, argv); // ignore_convention IConfig *pConfig = CreateConfig(); - + pServer->InitRegister(&pServer->m_NetServer, pEngineMasterServer, pConsole); { @@ -1565,20 +1565,20 @@ int main(int argc, const char **argv) // ignore_convention RegisterFail = RegisterFail || !pKernel->RegisterInterface(pConfig); RegisterFail = RegisterFail || !pKernel->RegisterInterface(static_cast<IEngineMasterServer*>(pEngineMasterServer)); // register as both RegisterFail = RegisterFail || !pKernel->RegisterInterface(static_cast<IMasterServer*>(pEngineMasterServer)); - + if(RegisterFail) return -1; } - + pEngine->Init(); pConfig->Init(); pEngineMasterServer->Init(); pEngineMasterServer->Load(); - + // register all console commands pServer->RegisterCommands(); pGameServer->OnConsoleInit(); - + // execute autoexec file pConsole->ExecuteFile("autoexec.cfg"); @@ -1588,13 +1588,13 @@ int main(int argc, const char **argv) // ignore_convention // restore empty config strings to their defaults pConfig->RestoreStrings(); - + pEngine->InitLogfile(); // run the server dbg_msg("server", "starting..."); pServer->Run(); - + // free delete pServer; delete pKernel; diff --git a/src/engine/server/server.h b/src/engine/server/server.h index 66cac91f..9a68c9fe 100644 --- a/src/engine/server/server.h +++ b/src/engine/server/server.h @@ -21,17 +21,17 @@ class CSnapIDPool }; CID m_aIDs[MAX_IDS]; - + int m_FirstFree; int m_FirstTimed; int m_LastTimed; int m_Usage; int m_InUsage; - -public: + +public: CSnapIDPool(); - + void Reset(); void RemoveFirstTimeout(); int NewID(); @@ -52,7 +52,7 @@ public: class CClient { public: - + enum { STATE_EMPTY = 0, @@ -60,49 +60,49 @@ public: STATE_CONNECTING, STATE_READY, STATE_INGAME, - + SNAPRATE_INIT=0, SNAPRATE_FULL, SNAPRATE_RECOVER }; - + class CInput { public: int m_aData[MAX_INPUT_SIZE]; int m_GameTick; // the tick that was chosen for the input }; - + // connection state info int m_State; int m_Latency; int m_SnapRate; - + int m_LastAckedSnapshot; int m_LastInputTick; CSnapshotStorage m_Snapshots; - + CInput m_LatestInput; CInput m_aInputs[200]; // TODO: handle input better int m_CurrentInput; - + char m_aName[MAX_NAME_LENGTH]; char m_aClan[MAX_CLAN_LENGTH]; int m_Country; int m_Score; int m_Authed; int m_AuthTries; - + void Reset(); }; - + CClient m_aClients[MAX_CLIENTS]; CSnapshotDelta m_SnapshotDelta; CSnapshotBuilder m_SnapshotBuilder; CSnapIDPool m_IDPool; CNetServer m_NetServer; - + IEngineMap *m_pMap; int64 m_GameStartTime; @@ -117,14 +117,14 @@ public: char m_aCurrentMap[64]; unsigned m_CurrentMapCrc; unsigned char *m_pCurrentMapData; - int m_CurrentMapSize; - + int m_CurrentMapSize; + CDemoRecorder m_DemoRecorder; CRegister m_Register; CMapChecker m_MapChecker; - + CServer(); - + int TrySetClientName(int ClientID, const char *pName); virtual void SetClientName(int ClientID, const char *pName); @@ -162,15 +162,15 @@ public: void SendConnectionReady(int ClientID); void SendRconLine(int ClientID, const char *pLine); static void SendRconLineAuthed(const char *pLine, void *pUser); - + void ProcessClientPacket(CNetChunk *pPacket); - + void SendServerInfo(NETADDR *pAddr, int Token); void UpdateServerInfo(); int BanAdd(NETADDR Addr, int Seconds, const char *pReason); int BanRemove(NETADDR Addr); - + void PumpNetwork(); @@ -193,8 +193,8 @@ public: static void ConchainMaxclientsperipUpdate(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData); void RegisterCommands(); - - + + virtual int SnapNewID(); virtual void SnapFreeID(int ID); virtual void *SnapNewItem(int Type, int ID, int Size); diff --git a/src/engine/serverbrowser.h b/src/engine/serverbrowser.h index 1ac22056..3ca59f9c 100644 --- a/src/engine/serverbrowser.h +++ b/src/engine/serverbrowser.h @@ -28,11 +28,11 @@ public: int m_SortedIndex; int m_ServerIndex; - + NETADDR m_NetAddr; - + int m_QuickSearchHit; - + int m_MaxClients; int m_NumClients; int m_MaxPlayers; @@ -66,11 +66,11 @@ public: SORT_MAP, SORT_GAMETYPE, SORT_NUMPLAYERS, - + QUICK_SERVERNAME=1, QUICK_PLAYER=2, QUICK_MAPNAME=4, - + TYPE_INTERNET = 0, TYPE_LAN = 1, TYPE_FAVORITES = 2, @@ -84,12 +84,12 @@ public: virtual bool IsRefreshing() const = 0; virtual bool IsRefreshingMasters() const = 0; virtual int LoadingProgression() const = 0; - + virtual int NumServers() const = 0; - + virtual int NumSortedServers() const = 0; virtual const CServerInfo *SortedGet(int Index) const = 0; - + virtual bool IsFavorite(const NETADDR &Addr) const = 0; virtual void AddFavorite(const NETADDR &Addr) = 0; virtual void RemoveFavorite(const NETADDR &Addr) = 0; diff --git a/src/engine/shared/compression.cpp b/src/engine/shared/compression.cpp index f14e1cc4..40fe28c4 100644 --- a/src/engine/shared/compression.cpp +++ b/src/engine/shared/compression.cpp @@ -4,9 +4,9 @@ #include "compression.h" -// Format: ESDDDDDD EDDDDDDD EDD... Extended, Data, Sign -unsigned char *CVariableInt::Pack(unsigned char *pDst, int i) -{ +// Format: ESDDDDDD EDDDDDDD EDD... Extended, Data, Sign +unsigned char *CVariableInt::Pack(unsigned char *pDst, int i) +{ *pDst = (i>>25)&0x40; // set sign bit if i<0 i = i^(i>>31); // if(i<0) i = ~i @@ -27,16 +27,16 @@ unsigned char *CVariableInt::Pack(unsigned char *pDst, int i) } pDst++; - return pDst; -} - + return pDst; +} + const unsigned char *CVariableInt::Unpack(const unsigned char *pSrc, int *pInOut) -{ - int Sign = (*pSrc>>6)&1; - *pInOut = *pSrc&0x3F; +{ + int Sign = (*pSrc>>6)&1; + *pInOut = *pSrc&0x3F; do - { + { if(!(*pSrc&0x80)) break; pSrc++; *pInOut |= (*pSrc&(0x7F))<<(6); @@ -56,8 +56,8 @@ const unsigned char *CVariableInt::Unpack(const unsigned char *pSrc, int *pInOut pSrc++; *pInOut ^= -Sign; // if(sign) *i = ~(*i) - return pSrc; -} + return pSrc; +} long CVariableInt::Decompress(const void *pSrc_, int Size, void *pDst_) diff --git a/src/engine/shared/config.cpp b/src/engine/shared/config.cpp index f531fa5a..b9aa1320 100644 --- a/src/engine/shared/config.cpp +++ b/src/engine/shared/config.cpp @@ -10,21 +10,21 @@ class CConfig : public IConfig { IStorage *m_pStorage; IOHANDLE m_ConfigFile; - + struct CCallback { SAVECALLBACKFUNC m_pfnFunc; void *m_pUserData; }; - + enum { MAX_CALLBACKS = 16 }; - + CCallback m_aCallbacks[MAX_CALLBACKS]; int m_NumCallbacks; - + void EscapeParam(char *pDst, const char *pSrc, int size) { for(int i = 0; *pSrc && i < size - 1; ++i) @@ -43,22 +43,22 @@ public: m_ConfigFile = 0; m_NumCallbacks = 0; } - + virtual void Init() { m_pStorage = Kernel()->RequestInterface<IStorage>(); Reset(); } - + virtual void Reset() { #define MACRO_CONFIG_INT(Name,ScriptName,def,min,max,flags,desc) g_Config.m_##Name = def; #define MACRO_CONFIG_STR(Name,ScriptName,len,def,flags,desc) str_copy(g_Config.m_##Name, def, len); - #include "config_variables.h" + #include "config_variables.h" - #undef MACRO_CONFIG_INT - #undef MACRO_CONFIG_STR + #undef MACRO_CONFIG_INT + #undef MACRO_CONFIG_STR } virtual void RestoreStrings() @@ -71,34 +71,34 @@ public: #undef MACRO_CONFIG_INT #undef MACRO_CONFIG_STR } - + virtual void Save() { if(!m_pStorage) return; m_ConfigFile = m_pStorage->OpenFile("settings.cfg", IOFLAG_WRITE, IStorage::TYPE_SAVE); - + if(!m_ConfigFile) return; - + char aLineBuf[1024*2]; char aEscapeBuf[1024*2]; #define MACRO_CONFIG_INT(Name,ScriptName,def,min,max,flags,desc) if((flags)&CFGFLAG_SAVE){ str_format(aLineBuf, sizeof(aLineBuf), "%s %i", #ScriptName, g_Config.m_##Name); WriteLine(aLineBuf); } #define MACRO_CONFIG_STR(Name,ScriptName,len,def,flags,desc) if((flags)&CFGFLAG_SAVE){ EscapeParam(aEscapeBuf, g_Config.m_##Name, sizeof(aEscapeBuf)); str_format(aLineBuf, sizeof(aLineBuf), "%s \"%s\"", #ScriptName, aEscapeBuf); WriteLine(aLineBuf); } - #include "config_variables.h" + #include "config_variables.h" + + #undef MACRO_CONFIG_INT + #undef MACRO_CONFIG_STR - #undef MACRO_CONFIG_INT - #undef MACRO_CONFIG_STR - for(int i = 0; i < m_NumCallbacks; i++) m_aCallbacks[i].m_pfnFunc(this, m_aCallbacks[i].m_pUserData); - + io_close(m_ConfigFile); m_ConfigFile = 0; } - + virtual void RegisterCallback(SAVECALLBACKFUNC pfnFunc, void *pUserData) { dbg_assert(m_NumCallbacks < MAX_CALLBACKS, "too many config callbacks"); @@ -106,7 +106,7 @@ public: m_aCallbacks[m_NumCallbacks].m_pUserData = pUserData; m_NumCallbacks++; } - + virtual void WriteLine(const char *pLine) { if(!m_ConfigFile) @@ -117,7 +117,7 @@ public: static const char Newline[] = "\n"; #endif io_write(m_ConfigFile, pLine, str_length(pLine)); - io_write(m_ConfigFile, Newline, sizeof(Newline)-1); + io_write(m_ConfigFile, Newline, sizeof(Newline)-1); } }; diff --git a/src/engine/shared/config.h b/src/engine/shared/config.h index 9a524d22..ed89daa2 100644 --- a/src/engine/shared/config.h +++ b/src/engine/shared/config.h @@ -4,12 +4,12 @@ #define ENGINE_SHARED_CONFIG_H struct CConfiguration -{ - #define MACRO_CONFIG_INT(Name,ScriptName,Def,Min,Max,Save,Desc) int m_##Name; - #define MACRO_CONFIG_STR(Name,ScriptName,Len,Def,Save,Desc) char m_##Name[Len]; // Flawfinder: ignore - #include "config_variables.h" - #undef MACRO_CONFIG_INT - #undef MACRO_CONFIG_STR +{ + #define MACRO_CONFIG_INT(Name,ScriptName,Def,Min,Max,Save,Desc) int m_##Name; + #define MACRO_CONFIG_STR(Name,ScriptName,Len,Def,Save,Desc) char m_##Name[Len]; // Flawfinder: ignore + #include "config_variables.h" + #undef MACRO_CONFIG_INT + #undef MACRO_CONFIG_STR }; extern CConfiguration g_Config; diff --git a/src/engine/shared/config_variables.h b/src/engine/shared/config_variables.h index 8dec2102..eb7f9ca7 100644 --- a/src/engine/shared/config_variables.h +++ b/src/engine/shared/config_variables.h @@ -56,7 +56,7 @@ MACRO_CONFIG_INT(SndNonactiveMute, snd_nonactive_mute, 0, 0, 1, CFGFLAG_SAVE|CFG MACRO_CONFIG_INT(GfxScreenWidth, gfx_screen_width, 800, 0, 0, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Screen resolution width") MACRO_CONFIG_INT(GfxScreenHeight, gfx_screen_height, 600, 0, 0, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Screen resolution height") MACRO_CONFIG_INT(GfxFullscreen, gfx_fullscreen, 1, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Fullscreen") -MACRO_CONFIG_INT(GfxAlphabits, gfx_alphabits, 0, 0, 0, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Alpha bits for framebuffer (fullscreen only)") +MACRO_CONFIG_INT(GfxAlphabits, gfx_alphabits, 0, 0, 0, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Alpha bits for framebuffer (fullscreen only)") MACRO_CONFIG_INT(GfxColorDepth, gfx_color_depth, 24, 16, 24, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Colors bits for framebuffer (fullscreen only)") MACRO_CONFIG_INT(GfxClear, gfx_clear, 0, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Clear screen before rendering") MACRO_CONFIG_INT(GfxVsync, gfx_vsync, 1, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Vertical sync") diff --git a/src/engine/shared/console.cpp b/src/engine/shared/console.cpp index 3241d05d..032ff2ae 100644 --- a/src/engine/shared/console.cpp +++ b/src/engine/shared/console.cpp @@ -38,21 +38,21 @@ int CConsole::ParseStart(CResult *pResult, const char *pString, int Length) int Len = sizeof(pResult->m_aStringStorage); if(Length < Len) Len = Length; - + str_copy(pResult->m_aStringStorage, pString, Length); pStr = pResult->m_aStringStorage; - + // get command pStr = str_skip_whitespaces(pStr); pResult->m_pCommand = pStr; pStr = str_skip_to_whitespace(pStr); - + if(*pStr) { pStr[0] = 0; pStr++; } - + pResult->m_pArgsStart = pStr; return 0; } @@ -63,38 +63,38 @@ int CConsole::ParseArgs(CResult *pResult, const char *pFormat) char *pStr; int Optional = 0; int Error = 0; - + pStr = pResult->m_pArgsStart; - while(1) + while(1) { // fetch command Command = *pFormat; pFormat++; - + if(!Command) break; - + if(Command == '?') Optional = 1; else { pStr = str_skip_whitespaces(pStr); - + if(!(*pStr)) // error, non optional command needs value { if(!Optional) Error = 1; break; } - + // add token if(*pStr == '"') { char *pDst; pStr++; pResult->AddArgument(pStr); - + pDst = pStr; // we might have to process escape data while(1) { @@ -109,22 +109,22 @@ int CConsole::ParseArgs(CResult *pResult, const char *pFormat) } else if(pStr[0] == 0) return 1; // return error - + *pDst = *pStr; pDst++; pStr++; } - + // write null termination *pDst = 0; - + pStr++; } else { pResult->AddArgument(pStr); - + if(Command == 'r') // rest of the string break; else if(Command == 'i') // validate int @@ -167,14 +167,14 @@ bool CConsole::LineIsValid(const char *pStr) { if(!pStr || *pStr == 0) return false; - + do { CResult Result; const char *pEnd = pStr; const char *pNextPart = 0; int InString = 0; - + while(*pEnd) { if(*pEnd == '"') @@ -186,25 +186,25 @@ bool CConsole::LineIsValid(const char *pStr) } else if(!InString) { - if(*pEnd == ';') // command separator + if(*pEnd == ';') // command separator { pNextPart = pEnd+1; break; } - else if(*pEnd == '#') // comment, no need to do anything more + else if(*pEnd == '#') // comment, no need to do anything more break; } - + pEnd++; } - + if(ParseStart(&Result, pStr, (pEnd-pStr) + 1) != 0) return false; CCommand *pCommand = FindCommand(Result.m_pCommand, m_FlagMask); if(!pCommand || ParseArgs(&Result, pCommand->m_pParams)) return false; - + pStr = pNextPart; } while(pStr && *pStr); @@ -213,14 +213,14 @@ bool CConsole::LineIsValid(const char *pStr) } void CConsole::ExecuteLineStroked(int Stroke, const char *pStr) -{ +{ while(pStr && *pStr) { CResult Result; const char *pEnd = pStr; const char *pNextPart = 0; int InString = 0; - + while(*pEnd) { if(*pEnd == '"') @@ -232,18 +232,18 @@ void CConsole::ExecuteLineStroked(int Stroke, const char *pStr) } else if(!InString) { - if(*pEnd == ';') // command separator + if(*pEnd == ';') // command separator { pNextPart = pEnd+1; break; } - else if(*pEnd == '#') // comment, no need to do anything more + else if(*pEnd == '#') // comment, no need to do anything more break; } - + pEnd++; } - + if(ParseStart(&Result, pStr, (pEnd-pStr) + 1) != 0) return; @@ -258,7 +258,7 @@ void CConsole::ExecuteLineStroked(int Stroke, const char *pStr) Result.AddArgument(m_paStrokeStr[Stroke]); IsStrokeCommand = 1; } - + if(Stroke || IsStrokeCommand) { if(ParseArgs(&Result, pCommand->m_pParams)) @@ -284,7 +284,7 @@ void CConsole::ExecuteLineStroked(int Stroke, const char *pStr) str_format(aBuf, sizeof(aBuf), "No such command: %s.", Result.m_pCommand); Print(OUTPUT_LEVEL_STANDARD, "Console", aBuf); } - + pStr = pNextPart; } } @@ -299,7 +299,7 @@ void CConsole::PossibleCommands(const char *pStr, int FlagMask, FPossibleCallbac if(str_find_nocase(pCommand->m_pName, pStr)) pfnCallback(pCommand->m_pName, pUser); } - } + } } CConsole::CCommand *CConsole::FindCommand(const char *pName, int FlagMask) @@ -312,8 +312,8 @@ CConsole::CCommand *CConsole::FindCommand(const char *pName, int FlagMask) if(str_comp_nocase(pCommand->m_pName, pName) == 0) return pCommand; } - } - + } + return 0x0; } @@ -335,7 +335,7 @@ void CConsole::ExecuteFile(const char *pFilename) m_pStorage = Kernel()->RequestInterface<IStorage>(); if(!m_pStorage) return; - + // push this one to the stack CExecFile ThisFile; CExecFile *pPrev = m_pFirstExec; @@ -345,13 +345,13 @@ void CConsole::ExecuteFile(const char *pFilename) // exec the file IOHANDLE File = m_pStorage->OpenFile(pFilename, IOFLAG_READ, IStorage::TYPE_ALL); - + char aBuf[256]; if(File) { char *pLine; CLineReader lr; - + str_format(aBuf, sizeof(aBuf), "executing '%s'", pFilename); Print(IConsole::OUTPUT_LEVEL_STANDARD, "console", aBuf); lr.Init(File); @@ -366,7 +366,7 @@ void CConsole::ExecuteFile(const char *pFilename) str_format(aBuf, sizeof(aBuf), "failed to open '%s'", pFilename); Print(IConsole::OUTPUT_LEVEL_STANDARD, "console", aBuf); } - + m_pFirstExec = pPrev; } @@ -402,7 +402,7 @@ static void IntVariableCommand(IConsole::IResult *pResult, void *pUserData) if(pResult->NumArguments()) { int Val = pResult->GetInteger(0); - + // do clamping if(pData->m_Min != pData->m_Max) { @@ -468,30 +468,30 @@ CConsole::CConsole(int FlagMask) m_pFirstExec = 0; m_pPrintCallbackUserdata = 0; m_pfnPrintCallback = 0; - + m_pStorage = 0; - + // register some basic commands Register("echo", "r", CFGFLAG_SERVER|CFGFLAG_CLIENT, Con_Echo, this, "Echo the text"); Register("exec", "r", CFGFLAG_SERVER|CFGFLAG_CLIENT, Con_Exec, this, "Execute the specified file"); - + // TODO: this should disappear #define MACRO_CONFIG_INT(Name,ScriptName,Def,Min,Max,Flags,Desc) \ { \ static CIntVariableData Data = { this, &g_Config.m_##Name, Min, Max }; \ Register(#ScriptName, "?i", Flags, IntVariableCommand, &Data, Desc); \ } - + #define MACRO_CONFIG_STR(Name,ScriptName,Len,Def,Flags,Desc) \ { \ static CStrVariableData Data = { this, g_Config.m_##Name, Len }; \ Register(#ScriptName, "?r", Flags, StrVariableCommand, &Data, Desc); \ } - #include "config_variables.h" + #include "config_variables.h" - #undef MACRO_CONFIG_INT - #undef MACRO_CONFIG_STR + #undef MACRO_CONFIG_INT + #undef MACRO_CONFIG_STR } void CConsole::ParseArguments(int NumArgs, const char **ppArguments) @@ -518,7 +518,7 @@ void CConsole::ParseArguments(int NumArgs, const char **ppArguments) } } -void CConsole::Register(const char *pName, const char *pParams, +void CConsole::Register(const char *pName, const char *pParams, int Flags, FCommandCallback pfnFunc, void *pUser, const char *pHelp) { CCommand *pCommand = (CCommand *)mem_alloc(sizeof(CCommand), sizeof(void*)); @@ -528,8 +528,8 @@ void CConsole::Register(const char *pName, const char *pParams, pCommand->m_pName = pName; pCommand->m_pParams = pParams; pCommand->m_Flags = Flags; - - + + pCommand->m_pNext = m_pFirstCommand; m_pFirstCommand = pCommand; } @@ -543,7 +543,7 @@ void CConsole::Con_Chain(IResult *pResult, void *pUserData) void CConsole::Chain(const char *pName, FChainCommandCallback pfnChainFunc, void *pUser) { CCommand *pCommand = FindCommand(pName, m_FlagMask); - + if(!pCommand) { char aBuf[256]; @@ -551,7 +551,7 @@ void CConsole::Chain(const char *pName, FChainCommandCallback pfnChainFunc, void Print(IConsole::OUTPUT_LEVEL_DEBUG, "console", aBuf); return; } - + CChain *pChainInfo = (CChain *)mem_alloc(sizeof(CChain), sizeof(void*)); // store info @@ -559,7 +559,7 @@ void CConsole::Chain(const char *pName, FChainCommandCallback pfnChainFunc, void pChainInfo->m_pUserData = pUser; pChainInfo->m_pfnCallback = pCommand->m_pfnCallback; pChainInfo->m_pCallbackUserData = pCommand->m_pUserData; - + // chain pCommand->m_pfnCallback = Con_Chain; pCommand->m_pUserData = pChainInfo; diff --git a/src/engine/shared/console.h b/src/engine/shared/console.h index a276751a..77c46fb0 100644 --- a/src/engine/shared/console.h +++ b/src/engine/shared/console.h @@ -16,7 +16,7 @@ class CConsole : public IConsole FCommandCallback m_pfnCallback; void *m_pUserData; }; - + class CChain { @@ -25,8 +25,8 @@ class CConsole : public IConsole FCommandCallback m_pfnCallback; void *m_pCallbackUserData; void *m_pUserData; - }; - + }; + int m_FlagMask; bool m_StoreCommands; const char *m_paStrokeStr[2]; @@ -38,7 +38,7 @@ class CConsole : public IConsole const char *m_pFilename; struct CExecFile *m_pPrev; }; - + CExecFile *m_pFirstExec; class IStorage *m_pStorage; @@ -48,22 +48,22 @@ class CConsole : public IConsole void ExecuteFileRecurse(const char *pFilename); void ExecuteLineStroked(int Stroke, const char *pStr); - + FPrintCallback m_pfnPrintCallback; void *m_pPrintCallbackUserdata; enum { - CONSOLE_MAX_STR_LENGTH = 1024, + CONSOLE_MAX_STR_LENGTH = 1024, MAX_PARTS = (CONSOLE_MAX_STR_LENGTH+1)/2 }; - + class CResult : public IResult { public: char m_aStringStorage[CONSOLE_MAX_STR_LENGTH+1]; char *m_pArgsStart; - + const char *m_pCommand; const char *m_apArgs[MAX_PARTS]; @@ -89,7 +89,7 @@ class CConsole : public IConsole } return *this; } - + void AddArgument(const char *pArg) { m_apArgs[m_NumArgs++] = pArg; @@ -99,7 +99,7 @@ class CConsole : public IConsole virtual int GetInteger(unsigned Index); virtual float GetFloat(unsigned Index); }; - + int ParseStart(CResult *pResult, const char *pString, int Length); int ParseArgs(CResult *pResult, const char *pFormat); @@ -146,7 +146,7 @@ public: virtual void Register(const char *pName, const char *pParams, int Flags, FCommandCallback pfnFunc, void *pUser, const char *pHelp); virtual void Chain(const char *pName, FChainCommandCallback pfnChainFunc, void *pUser); virtual void StoreCommands(bool Store); - + virtual bool LineIsValid(const char *pStr); virtual void ExecuteLine(const char *pStr); virtual void ExecuteFile(const char *pFilename); diff --git a/src/engine/shared/datafile.cpp b/src/engine/shared/datafile.cpp index 74936ea0..3a5a4b1d 100644 --- a/src/engine/shared/datafile.cpp +++ b/src/engine/shared/datafile.cpp @@ -75,9 +75,9 @@ bool CDataFileReader::Open(class IStorage *pStorage, const char *pFilename, int { dbg_msg("datafile", "could not open '%s'", pFilename); return false; - } - - + } + + // take the CRC of the file and store it unsigned Crc = 0; { @@ -85,9 +85,9 @@ bool CDataFileReader::Open(class IStorage *pStorage, const char *pFilename, int { BUFFER_SIZE = 64*1024 }; - + unsigned char aBuffer[BUFFER_SIZE]; - + while(1) { unsigned Bytes = io_read(File, aBuffer, BUFFER_SIZE); @@ -95,11 +95,11 @@ bool CDataFileReader::Open(class IStorage *pStorage, const char *pFilename, int break; Crc = crc32(Crc, aBuffer, Bytes); // ignore_convention } - + io_seek(File, 0, IOSEEK_START); } - - + + // TODO: change this header CDatafileHeader Header; io_read(File, &Header, sizeof(Header)); @@ -113,14 +113,14 @@ bool CDataFileReader::Open(class IStorage *pStorage, const char *pFilename, int } #if defined(CONF_ARCH_ENDIAN_BIG) - swap_endian(&Header, sizeof(int), sizeof(Header)/sizeof(int)); + swap_endian(&Header, sizeof(int), sizeof(Header)/sizeof(int)); #endif if(Header.m_Version != 3 && Header.m_Version != 4) { dbg_msg("datafile", "wrong version. version=%x", Header.m_Version); return 0; } - + // read in the rest except the data unsigned Size = 0; Size += Header.m_NumItemTypes*sizeof(CDatafileItemType); @@ -128,7 +128,7 @@ bool CDataFileReader::Open(class IStorage *pStorage, const char *pFilename, int if(Header.m_Version == 4) Size += Header.m_NumRawData*sizeof(int); // v4 has uncompressed data sizes aswell Size += Header.m_ItemSize; - + unsigned AllocSize = Size; AllocSize += sizeof(CDatafile); // add space for info structure AllocSize += Header.m_NumRawData*sizeof(void*); // add space for data pointers @@ -140,10 +140,10 @@ bool CDataFileReader::Open(class IStorage *pStorage, const char *pFilename, int pTmpDataFile->m_pData = (char *)(pTmpDataFile+1)+Header.m_NumRawData*sizeof(char *); pTmpDataFile->m_File = File; pTmpDataFile->m_Crc = Crc; - + // clear the data pointers mem_zero(pTmpDataFile->m_ppDataPtrs, Header.m_NumRawData*sizeof(void*)); - + // read types, offsets, sizes and item data unsigned ReadSize = io_read(File, pTmpDataFile->m_pData, Size); if(ReadSize != Size) @@ -169,12 +169,12 @@ bool CDataFileReader::Open(class IStorage *pStorage, const char *pFilename, int dbg_msg("datafile", "swaplen=%d", Header.m_Swaplen); dbg_msg("datafile", "item_size=%d", m_pDataFile->m_Header.m_ItemSize); } - + m_pDataFile->m_Info.m_pItemTypes = (CDatafileItemType *)m_pDataFile->m_pData; m_pDataFile->m_Info.m_pItemOffsets = (int *)&m_pDataFile->m_Info.m_pItemTypes[m_pDataFile->m_Header.m_NumItemTypes]; m_pDataFile->m_Info.m_pDataOffsets = (int *)&m_pDataFile->m_Info.m_pItemOffsets[m_pDataFile->m_Header.m_NumItems]; m_pDataFile->m_Info.m_pDataSizes = (int *)&m_pDataFile->m_Info.m_pDataOffsets[m_pDataFile->m_Header.m_NumRawData]; - + if(Header.m_Version == 4) m_pDataFile->m_Info.m_pItemStart = (char *)&m_pDataFile->m_Info.m_pDataSizes[m_pDataFile->m_Header.m_NumRawData]; else @@ -191,7 +191,7 @@ bool CDataFileReader::Open(class IStorage *pStorage, const char *pFilename, int void *p = datafile_get_data(df, i); dbg_msg("datafile", "%d %d", (int)((char*)p - (char*)(&m_pDataFile->data)), size); } - + for(int i = 0; i < datafile_num_items(df); i++) { int type, id; @@ -218,7 +218,7 @@ bool CDataFileReader::Open(class IStorage *pStorage, const char *pFilename, int } */ } - + return true; } @@ -227,7 +227,7 @@ bool CDataFileReader::GetCrcSize(class IStorage *pStorage, const char *pFilename IOHANDLE File = pStorage->OpenFile(pFilename, IOFLAG_READ, StorageType); if(!File) return false; - + // get crc and size unsigned Crc = 0; unsigned Size = 0; @@ -240,7 +240,7 @@ bool CDataFileReader::GetCrcSize(class IStorage *pStorage, const char *pFilename Crc = crc32(Crc, aBuffer, Bytes); // ignore_convention Size += Bytes; } - + io_close(File); *pCrc = Crc; @@ -258,23 +258,23 @@ int CDataFileReader::NumData() int CDataFileReader::GetDataSize(int Index) { if(!m_pDataFile) { return 0; } - + if(Index == m_pDataFile->m_Header.m_NumRawData-1) return m_pDataFile->m_Header.m_DataSize-m_pDataFile->m_Info.m_pDataOffsets[Index]; - return m_pDataFile->m_Info.m_pDataOffsets[Index+1]-m_pDataFile->m_Info.m_pDataOffsets[Index]; + return m_pDataFile->m_Info.m_pDataOffsets[Index+1]-m_pDataFile->m_Info.m_pDataOffsets[Index]; } void *CDataFileReader::GetDataImpl(int Index, int Swap) { if(!m_pDataFile) { return 0; } - + // load it if needed if(!m_pDataFile->m_ppDataPtrs[Index]) { // fetch the data size int DataSize = GetDataSize(Index); int SwapSize = DataSize; - + if(m_pDataFile->m_Header.m_Version == 4) { // v4 has compressed data @@ -284,7 +284,7 @@ void *CDataFileReader::GetDataImpl(int Index, int Swap) dbg_msg("datafile", "loading data index=%d size=%d uncompressed=%d", Index, DataSize, UncompressedSize); m_pDataFile->m_ppDataPtrs[Index] = (char *)mem_alloc(UncompressedSize, 1); - + // read the compressed data io_seek(m_pDataFile->m_File, m_pDataFile->m_DataStartOffset+m_pDataFile->m_Info.m_pDataOffsets[Index], IOSEEK_START); io_read(m_pDataFile->m_File, pTemp, DataSize); @@ -311,7 +311,7 @@ void *CDataFileReader::GetDataImpl(int Index, int Swap) swap_endian(m_pDataFile->m_ppDataPtrs[Index], sizeof(int), SwapSize/sizeof(int)); #endif } - + return m_pDataFile->m_ppDataPtrs[Index]; } @@ -329,7 +329,7 @@ void CDataFileReader::UnloadData(int Index) { if(Index < 0) return; - + // mem_free(m_pDataFile->m_ppDataPtrs[Index]); m_pDataFile->m_ppDataPtrs[Index] = 0x0; @@ -340,13 +340,13 @@ int CDataFileReader::GetItemSize(int Index) if(!m_pDataFile) { return 0; } if(Index == m_pDataFile->m_Header.m_NumItems-1) return m_pDataFile->m_Header.m_ItemSize-m_pDataFile->m_Info.m_pItemOffsets[Index]; - return m_pDataFile->m_Info.m_pItemOffsets[Index+1]-m_pDataFile->m_Info.m_pItemOffsets[Index]; + return m_pDataFile->m_Info.m_pItemOffsets[Index+1]-m_pDataFile->m_Info.m_pItemOffsets[Index]; } void *CDataFileReader::GetItem(int Index, int *pType, int *pID) { if(!m_pDataFile) { if(pType) *pType = 0; if(pID) *pID = 0; return 0; } - + CDatafileItem *i = (CDatafileItem *)(m_pDataFile->m_Info.m_pItemStart+m_pDataFile->m_Info.m_pItemOffsets[Index]); if(pType) *pType = (i->m_TypeAndID>>16)&0xffff; // remove sign extention @@ -362,7 +362,7 @@ void CDataFileReader::GetType(int Type, int *pStart, int *pNum) if(!m_pDataFile) return; - + for(int i = 0; i < m_pDataFile->m_Header.m_NumItemTypes; i++) { if(m_pDataFile->m_Info.m_pItemTypes[i].m_Type == Type) @@ -377,7 +377,7 @@ void CDataFileReader::GetType(int Type, int *pStart, int *pNum) void *CDataFileReader::FindItem(int Type, int ID) { if(!m_pDataFile) return 0; - + int Start, Num; GetType(Type, &Start, &Num); for(int i = 0; i < Num; i++) @@ -400,12 +400,12 @@ bool CDataFileReader::Close() { if(!m_pDataFile) return true; - + // free the data that is loaded int i; for(i = 0; i < m_pDataFile->m_Header.m_NumRawData; i++) mem_free(m_pDataFile->m_ppDataPtrs[i]); - + io_close(m_pDataFile->m_File); mem_free(m_pDataFile); m_pDataFile = 0; @@ -424,7 +424,7 @@ bool CDataFileWriter::Open(class IStorage *pStorage, const char *pFilename) m_File = pStorage->OpenFile(pFilename, IOFLAG_WRITE, IStorage::TYPE_SAVE); if(!m_File) return false; - + m_NumItems = 0; m_NumDatas = 0; m_NumItemTypes = 0; @@ -435,7 +435,7 @@ bool CDataFileWriter::Open(class IStorage *pStorage, const char *pFilename) m_aItemTypes[i].m_First = -1; m_aItemTypes[i].m_Last = -1; } - + return true; } @@ -450,7 +450,7 @@ int CDataFileWriter::AddItem(int Type, int ID, int Size, void *pData) m_aItems[m_NumItems].m_Type = Type; m_aItems[m_NumItems].m_ID = ID; m_aItems[m_NumItems].m_Size = Size; - + // copy data m_aItems[m_NumItems].m_pData = mem_alloc(Size, 1); mem_copy(m_aItems[m_NumItems].m_pData, pData, Size); @@ -461,16 +461,16 @@ int CDataFileWriter::AddItem(int Type, int ID, int Size, void *pData) // link m_aItems[m_NumItems].m_Prev = m_aItemTypes[Type].m_Last; m_aItems[m_NumItems].m_Next = -1; - + if(m_aItemTypes[Type].m_Last != -1) m_aItems[m_aItemTypes[Type].m_Last].m_Next = m_NumItems; m_aItemTypes[Type].m_Last = m_NumItems; - + if(m_aItemTypes[Type].m_First == -1) m_aItemTypes[Type].m_First = m_NumItems; - + m_aItemTypes[Type].m_Num++; - + m_NumItems++; return m_NumItems-1; } @@ -491,7 +491,7 @@ int CDataFileWriter::AddData(int Size, void *pData) dbg_msg("datafile", "compression error %d", Result); dbg_assert(0, "zlib error"); } - + pInfo->m_UncompressedSize = Size; pInfo->m_CompressedSize = (int)s; pInfo->m_pCompressedData = mem_alloc(pInfo->m_CompressedSize, 1); @@ -539,23 +539,23 @@ int CDataFileWriter::Finish() dbg_msg("datafile", "item=%d size=%d (%d)", i, m_aItems[i].m_Size, m_aItems[i].m_Size+sizeof(CDatafileItem)); ItemSize += m_aItems[i].m_Size + sizeof(CDatafileItem); } - - + + for(int i = 0; i < m_NumDatas; i++) DataSize += m_aDatas[i].m_CompressedSize; - + // calculate the complete size TypesSize = m_NumItemTypes*sizeof(CDatafileItemType); HeaderSize = sizeof(CDatafileHeader); OffsetSize = (m_NumItems + m_NumDatas + m_NumDatas) * sizeof(int); // ItemOffsets, DataOffsets, DataUncompressedSizes FileSize = HeaderSize + TypesSize + OffsetSize + ItemSize + DataSize; SwapSize = FileSize - DataSize; - + (void)SwapSize; - + if(DEBUG) dbg_msg("datafile", "num_m_aItemTypes=%d TypesSize=%d m_aItemsize=%d DataSize=%d", m_NumItemTypes, TypesSize, ItemSize, DataSize); - + // construct Header { Header.m_aID[0] = 'D'; @@ -570,7 +570,7 @@ int CDataFileWriter::Finish() Header.m_NumRawData = m_NumDatas; Header.m_ItemSize = ItemSize; Header.m_DataSize = DataSize; - + // write Header if(DEBUG) dbg_msg("datafile", "HeaderSize=%d", sizeof(Header)); @@ -579,7 +579,7 @@ int CDataFileWriter::Finish() #endif io_write(m_File, &Header, sizeof(Header)); } - + // write types for(int i = 0, Count = 0; i < 0xffff; i++) { @@ -599,7 +599,7 @@ int CDataFileWriter::Finish() Count += m_aItemTypes[i].m_Num; } } - + // write item offsets for(int i = 0, Offset = 0; i < 0xffff; i++) { @@ -617,13 +617,13 @@ int CDataFileWriter::Finish() #endif io_write(m_File, &Temp, sizeof(Temp)); Offset += m_aItems[k].m_Size + sizeof(CDatafileItem); - + // next k = m_aItems[k].m_Next; } } } - + // write data offsets for(int i = 0, Offset = 0; i < m_NumDatas; i++) { @@ -648,7 +648,7 @@ int CDataFileWriter::Finish() #endif io_write(m_File, &UncompressedSize, sizeof(UncompressedSize)); } - + // write m_aItems for(int i = 0; i < 0xffff; i++) { @@ -663,20 +663,20 @@ int CDataFileWriter::Finish() Item.m_Size = m_aItems[k].m_Size; if(DEBUG) dbg_msg("datafile", "writing item type=%x idx=%d id=%d size=%d", i, k, m_aItems[k].m_ID, m_aItems[k].m_Size); - + #if defined(CONF_ARCH_ENDIAN_BIG) swap_endian(&Item, sizeof(int), sizeof(Item)/sizeof(int)); swap_endian(m_aItems[k].m_pData, sizeof(int), m_aItems[k].m_Size/sizeof(int)); #endif io_write(m_File, &Item, sizeof(Item)); io_write(m_File, m_aItems[k].m_pData, m_aItems[k].m_Size); - + // next k = m_aItems[k].m_Next; } } } - + // write data for(int i = 0; i < m_NumDatas; i++) { @@ -690,10 +690,10 @@ int CDataFileWriter::Finish() mem_free(m_aItems[i].m_pData); for(int i = 0; i < m_NumDatas; ++i) mem_free(m_aDatas[i].m_pCompressedData); - + io_close(m_File); m_File = 0; - + if(DEBUG) dbg_msg("datafile", "done"); return 0; diff --git a/src/engine/shared/datafile.h b/src/engine/shared/datafile.h index 15bed033..46e8ada8 100644 --- a/src/engine/shared/datafile.h +++ b/src/engine/shared/datafile.h @@ -11,14 +11,14 @@ class CDataFileReader public: CDataFileReader() : m_pDataFile(0) {} ~CDataFileReader() { Close(); } - + bool IsOpen() const { return m_pDataFile != 0; } - + bool Open(class IStorage *pStorage, const char *pFilename, int StorageType); bool Close(); static bool GetCrcSize(class IStorage *pStorage, const char *pFilename, int StorageType, unsigned *pCrc, unsigned *pSize); - + void *GetData(int Index); void *GetDataSwapped(int Index); // makes sure that the data is 32bit LE ints when saved int GetDataSize(int Index); @@ -30,7 +30,7 @@ public: int NumItems(); int NumData(); void Unload(); - + unsigned Crc(); }; @@ -60,15 +60,15 @@ class CDataFileWriter int m_First; int m_Last; }; - + IOHANDLE m_File; int m_NumItems; int m_NumDatas; int m_NumItemTypes; CItemTypeInfo m_aItemTypes[0xffff]; CItemInfo m_aItems[1024]; - CDataInfo m_aDatas[1024]; - + CDataInfo m_aDatas[1024]; + public: CDataFileWriter() : m_File(0) {} bool Open(class IStorage *pStorage, const char *Filename); diff --git a/src/engine/shared/demo.cpp b/src/engine/shared/demo.cpp index ac78f22f..e48c2f1e 100644 --- a/src/engine/shared/demo.cpp +++ b/src/engine/shared/demo.cpp @@ -47,7 +47,7 @@ int CDemoRecorder::Start(class IStorage *pStorage, class IConsole *pConsole, con char aBuf[512]; str_format(aMapFilename, sizeof(aMapFilename), "%s.map", pMap); if(pStorage->FindFile(aMapFilename, "maps", IStorage::TYPE_ALL, aBuf, sizeof(aBuf))) - MapFile = pStorage->OpenFile(aBuf, IOFLAG_READ, IStorage::TYPE_ALL); + MapFile = pStorage->OpenFile(aBuf, IOFLAG_READ, IStorage::TYPE_ALL); } if(!MapFile) { @@ -67,7 +67,7 @@ int CDemoRecorder::Start(class IStorage *pStorage, class IConsole *pConsole, con m_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, "demo_recorder", aBuf); return -1; } - + // write header mem_zero(&Header, sizeof(Header)); mem_copy(Header.m_aMarker, gs_aHeaderMarker, sizeof(Header.m_aMarker)); @@ -87,7 +87,7 @@ int CDemoRecorder::Start(class IStorage *pStorage, class IConsole *pConsole, con // Header.m_Length - add this on stop str_timestamp(Header.m_aTimestamp, sizeof(Header.m_aTimestamp)); io_write(DemoFile, &Header, sizeof(Header)); - + // write map data while(1) { @@ -98,11 +98,11 @@ int CDemoRecorder::Start(class IStorage *pStorage, class IConsole *pConsole, con io_write(DemoFile, &aChunk, Bytes); } io_close(MapFile); - + m_LastKeyFrame = -1; m_LastTickMarker = -1; m_FirstTick = -1; - + char aBuf[256]; str_format(aBuf, sizeof(aBuf), "Recording to '%s'", pFilename); m_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, "demo_recorder", aBuf); @@ -113,25 +113,25 @@ int CDemoRecorder::Start(class IStorage *pStorage, class IConsole *pConsole, con /* Tickmarker - 7 = Always set - 6 = Keyframe flag - 0-5 = Delta tick - + 7 = Always set + 6 = Keyframe flag + 0-5 = Delta tick + Normal - 7 = Not set - 5-6 = Type - 0-4 = Size + 7 = Not set + 5-6 = Type + 0-4 = Size */ enum { CHUNKTYPEFLAG_TICKMARKER = 0x80, CHUNKTICKFLAG_KEYFRAME = 0x40, // only when tickmarker is set - + CHUNKMASK_TICK = 0x3f, CHUNKMASK_TYPE = 0x60, CHUNKMASK_SIZE = 0x1f, - + CHUNKTYPE_SNAPSHOT = 1, CHUNKTYPE_MESSAGE = 2, CHUNKTYPE_DELTA = 3, @@ -152,7 +152,7 @@ void CDemoRecorder::WriteTickMarker(int Tick, int Keyframe) if(Keyframe) aChunk[0] |= CHUNKTICKFLAG_KEYFRAME; - + io_write(m_File, aChunk, sizeof(aChunk)); } else @@ -160,7 +160,7 @@ void CDemoRecorder::WriteTickMarker(int Tick, int Keyframe) unsigned char aChunk[1]; aChunk[0] = CHUNKTYPEFLAG_TICKMARKER | (Tick-m_LastTickMarker); io_write(m_File, aChunk, sizeof(aChunk)); - } + } m_LastTickMarker = Tick; if(m_FirstTick < 0) @@ -172,7 +172,7 @@ void CDemoRecorder::Write(int Type, const void *pData, int Size) char aBuffer[64*1024]; char aBuffer2[64*1024]; unsigned char aChunk[3]; - + if(!m_File) return; @@ -183,8 +183,8 @@ void CDemoRecorder::Write(int Type, const void *pData, int Size) aBuffer2[Size++] = 0; Size = CVariableInt::Compress(aBuffer2, Size, aBuffer); // buffer2 -> buffer Size = CNetBase::Compress(aBuffer, Size, aBuffer2, sizeof(aBuffer2)); // buffer -> buffer2 - - + + aChunk[0] = ((Type&0x3)<<5); if(Size < 30) { @@ -207,7 +207,7 @@ void CDemoRecorder::Write(int Type, const void *pData, int Size) io_write(m_File, aChunk, 3); } } - + io_write(m_File, aBuffer2, Size); } @@ -217,10 +217,10 @@ void CDemoRecorder::RecordSnapshot(int Tick, const void *pData, int Size) { // write full tickmarker WriteTickMarker(Tick, 1); - + // write snapshot Write(CHUNKTYPE_SNAPSHOT, pData, Size); - + m_LastKeyFrame = Tick; mem_copy(m_aLastSnapshotData, pData, Size); } @@ -232,7 +232,7 @@ void CDemoRecorder::RecordSnapshot(int Tick, const void *pData, int Size) // write tickmarker WriteTickMarker(Tick, 0); - + DeltaSize = m_pSnapshotDelta->CreateDelta((CSnapshot*)m_aLastSnapshotData, (CSnapshot*)pData, &aDeltaData); if(DeltaSize) { @@ -262,7 +262,7 @@ int CDemoRecorder::Stop() aLength[2] = (DemoLength>>8)&0xff; aLength[3] = (DemoLength)&0xff; io_write(m_File, aLength, sizeof(aLength)); - + io_close(m_File); m_File = 0; m_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, "demo_recorder", "Stopped recording"); @@ -290,19 +290,19 @@ void CDemoPlayer::SetListner(IListner *pListner) int CDemoPlayer::ReadChunkHeader(int *pType, int *pSize, int *pTick) { unsigned char Chunk = 0; - + *pSize = 0; *pType = 0; - + if(io_read(m_File, &Chunk, sizeof(Chunk)) != sizeof(Chunk)) return -1; - + if(Chunk&CHUNKTYPEFLAG_TICKMARKER) { // decode tick marker int Tickdelta = Chunk&(CHUNKMASK_TICK); *pType = Chunk&(CHUNKTYPEFLAG_TICKMARKER|CHUNKTICKFLAG_KEYFRAME); - + if(Tickdelta == 0) { unsigned char aTickdata[4]; @@ -314,21 +314,21 @@ int CDemoPlayer::ReadChunkHeader(int *pType, int *pSize, int *pTick) { *pTick += Tickdelta; } - + } else { // decode normal chunk *pType = (Chunk&CHUNKMASK_TYPE)>>5; *pSize = Chunk&CHUNKMASK_SIZE; - + if(*pSize == 30) { unsigned char aSizedata[1]; if(io_read(m_File, aSizedata, sizeof(aSizedata)) != sizeof(aSizedata)) return -1; *pSize = aSizedata[0]; - + } else if(*pSize == 31) { @@ -338,7 +338,7 @@ int CDemoPlayer::ReadChunkHeader(int *pType, int *pSize, int *pTick) *pSize = (aSizedata[1]<<8) | aSizedata[0]; } } - + return 0; } @@ -358,17 +358,17 @@ void CDemoPlayer::ScanFile() while(1) { long CurrentPos = io_tell(m_File); - + if(ReadChunkHeader(&ChunkType, &ChunkSize, &ChunkTick)) break; - + // read the chunk if(ChunkType&CHUNKTYPEFLAG_TICKMARKER) { if(ChunkType&CHUNKTICKFLAG_KEYFRAME) { CKeyFrameSearch *pKey; - + // save the position pKey = (CKeyFrameSearch *)Heap.Allocate(sizeof(CKeyFrameSearch)); pKey->m_Frame.m_Filepos = CurrentPos; @@ -381,21 +381,21 @@ void CDemoPlayer::ScanFile() pCurrentKey = pKey; m_Info.m_SeekablePoints++; } - + if(m_Info.m_Info.m_FirstTick == -1) m_Info.m_Info.m_FirstTick = ChunkTick; m_Info.m_Info.m_LastTick = ChunkTick; } else if(ChunkSize) io_skip(m_File, ChunkSize); - + } // copy all the frames to an array instead for fast access m_pKeyFrames = (CKeyFrame*)mem_alloc(m_Info.m_SeekablePoints*sizeof(CKeyFrame), 1); for(pCurrentKey = pFirstKey, i = 0; pCurrentKey; pCurrentKey = pCurrentKey->m_pNext, i++) m_pKeyFrames[i] = pCurrentKey->m_Frame; - + // destroy the temporary heap and seek back to the start io_seek(m_File, StartPos, IOSEEK_START); } @@ -429,7 +429,7 @@ void CDemoPlayer::DoTick() Pause(); break; } - + // read the chunk if(ChunkSize) { @@ -440,7 +440,7 @@ void CDemoPlayer::DoTick() Stop(); break; } - + DataSize = CNetBase::Decompress(aCompresseddata, ChunkSize, aDecompressed, sizeof(aDecompressed)); if(DataSize < 0) { @@ -449,7 +449,7 @@ void CDemoPlayer::DoTick() Stop(); break; } - + DataSize = CVariableInt::Decompress(aDecompressed, DataSize, aData); if(DataSize < 0) @@ -459,16 +459,16 @@ void CDemoPlayer::DoTick() break; } } - + if(ChunkType == CHUNKTYPE_DELTA) { // process delta snapshot static char aNewsnap[CSnapshot::MAX_SIZE]; - + GotSnapshot = 1; - + DataSize = m_pSnapshotDelta->UnpackDelta((CSnapshot*)m_aLastSnapshotData, (CSnapshot*)aNewsnap, aData, DataSize); - + if(DataSize >= 0) { if(m_pListner) @@ -488,7 +488,7 @@ void CDemoPlayer::DoTick() { // process full snapshot GotSnapshot = 1; - + m_LastSnapshotDataSize = DataSize; mem_copy(m_aLastSnapshotData, aData, DataSize); if(m_pListner) @@ -502,7 +502,7 @@ void CDemoPlayer::DoTick() GotSnapshot = 1; m_pListner->OnDemoPlayerSnapshot(m_aLastSnapshotData, m_LastSnapshotDataSize); } - + // check the remaining types if(ChunkType&CHUNKTYPEFLAG_TICKMARKER) { @@ -544,7 +544,7 @@ int CDemoPlayer::Load(class IStorage *pStorage, class IConsole *pConsole, const m_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, "demo_player", aBuf); return -1; } - + // store the filename str_copy(m_aFilename, pFilename, sizeof(m_aFilename)); @@ -556,7 +556,7 @@ int CDemoPlayer::Load(class IStorage *pStorage, class IConsole *pConsole, const m_Info.m_Info.m_CurrentTick = -1; m_Info.m_PreviousTick = -1; m_Info.m_Info.m_Speed = 1; - + m_LastSnapshotDataSize = -1; // read the header @@ -580,7 +580,7 @@ int CDemoPlayer::Load(class IStorage *pStorage, class IConsole *pConsole, const m_File = 0; return -1; } - + // get demo type if(!str_comp(m_Info.m_Header.m_aType, "client")) m_DemoType = DEMOTYPE_CLIENT; @@ -588,17 +588,17 @@ int CDemoPlayer::Load(class IStorage *pStorage, class IConsole *pConsole, const m_DemoType = DEMOTYPE_SERVER; else m_DemoType = DEMOTYPE_INVALID; - + // read map unsigned MapSize = (m_Info.m_Header.m_aMapSize[0]<<24) | (m_Info.m_Header.m_aMapSize[1]<<16) | (m_Info.m_Header.m_aMapSize[2]<<8) | (m_Info.m_Header.m_aMapSize[3]); - + // check if we already have the map // TODO: improve map checking (maps folder, check crc) unsigned Crc = (m_Info.m_Header.m_aMapCrc[0]<<24) | (m_Info.m_Header.m_aMapCrc[1]<<16) | (m_Info.m_Header.m_aMapCrc[2]<<8) | (m_Info.m_Header.m_aMapCrc[3]); char aMapFilename[128]; str_format(aMapFilename, sizeof(aMapFilename), "downloadedmaps/%s_%08x.map", m_Info.m_Header.m_aMapName, Crc); IOHANDLE MapFile = pStorage->OpenFile(aMapFilename, IOFLAG_READ, IStorage::TYPE_ALL); - + if(MapFile) { io_skip(m_File, MapSize); @@ -609,20 +609,20 @@ int CDemoPlayer::Load(class IStorage *pStorage, class IConsole *pConsole, const // get map data unsigned char *pMapData = (unsigned char *)mem_alloc(MapSize, 1); io_read(m_File, pMapData, MapSize); - + // save map MapFile = pStorage->OpenFile(aMapFilename, IOFLAG_WRITE, IStorage::TYPE_SAVE); io_write(MapFile, pMapData, MapSize); io_close(MapFile); - + // free data mem_free(pMapData); } - - + + // scan the file for interessting points ScanFile(); - + // ready for playback return 0; } @@ -638,7 +638,7 @@ int CDemoPlayer::Play() // fill in previous and next tick while(m_Info.m_PreviousTick == -1 && IsPlaying()) DoTick(); - + // set start info /*m_Info.start_tick = m_Info.previous_tick; m_Info.start_time = time_get();*/ @@ -653,15 +653,15 @@ int CDemoPlayer::SetPos(float Percent) int WantedTick; if(!m_File) return -1; - + // -5 because we have to have a current tick and previous tick when we do the playback WantedTick = m_Info.m_Info.m_FirstTick + (int)((m_Info.m_Info.m_LastTick-m_Info.m_Info.m_FirstTick)*Percent) - 5; - + Keyframe = (int)(m_Info.m_SeekablePoints*Percent); if(Keyframe < 0 || Keyframe >= m_Info.m_SeekablePoints) return -1; - + // get correct key frame if(m_pKeyFrames[Keyframe].m_Tick < WantedTick) while(Keyframe < m_Info.m_SeekablePoints-1 && m_pKeyFrames[Keyframe].m_Tick < WantedTick) @@ -669,7 +669,7 @@ int CDemoPlayer::SetPos(float Percent) while(Keyframe && m_pKeyFrames[Keyframe].m_Tick > WantedTick) Keyframe--; - + // seek to the correct keyframe io_seek(m_File, m_pKeyFrames[Keyframe].m_Filepos, IOSEEK_START); @@ -681,9 +681,9 @@ int CDemoPlayer::SetPos(float Percent) // playback everything until we hit our tick while(m_Info.m_PreviousTick < WantedTick) DoTick(); - + Play(); - + return 0; } @@ -697,19 +697,19 @@ int CDemoPlayer::Update() int64 Now = time_get(); int64 Deltatime = Now-m_Info.m_LastUpdate; m_Info.m_LastUpdate = Now; - + if(!IsPlaying()) return 0; - + if(m_Info.m_Info.m_Paused) { - + } else { int64 Freq = time_freq(); m_Info.m_CurrentTime += (int64)(Deltatime*(double)m_Info.m_Info.m_Speed); - + while(1) { int64 CurtickStart = (m_Info.m_Info.m_CurrentTick)*Freq/SERVER_TICK_SPEED; @@ -717,22 +717,22 @@ int CDemoPlayer::Update() // break if we are ready if(CurtickStart > m_Info.m_CurrentTime) break; - + // do one more tick DoTick(); - + if(m_Info.m_Info.m_Paused) return 0; } // update intratick - { + { int64 CurtickStart = (m_Info.m_Info.m_CurrentTick)*Freq/SERVER_TICK_SPEED; int64 PrevtickStart = (m_Info.m_PreviousTick)*Freq/SERVER_TICK_SPEED; m_Info.m_IntraTick = (m_Info.m_CurrentTime - PrevtickStart) / (float)(CurtickStart-PrevtickStart); m_Info.m_TickTime = (m_Info.m_CurrentTime - PrevtickStart) / (float)Freq; } - + if(m_Info.m_Info.m_CurrentTick == m_Info.m_PreviousTick || m_Info.m_Info.m_CurrentTick == m_Info.m_NextTick) { @@ -742,7 +742,7 @@ int CDemoPlayer::Update() m_pConsole->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "demo_player", aBuf); } } - + return 0; } @@ -750,7 +750,7 @@ int CDemoPlayer::Stop() { if(!m_File) return -1; - + m_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, "demo_player", "Stopped playback"); io_close(m_File); m_File = 0; @@ -776,20 +776,20 @@ bool CDemoPlayer::GetDemoInfo(class IStorage *pStorage, const char *pFilename, i { if(!pDemoHeader) return false; - + mem_zero(pDemoHeader, sizeof(CDemoHeader)); IOHANDLE File = pStorage->OpenFile(pFilename, IOFLAG_READ, StorageType); if(!File) return false; - + io_read(File, pDemoHeader, sizeof(CDemoHeader)); if(mem_comp(pDemoHeader->m_aMarker, gs_aHeaderMarker, sizeof(gs_aHeaderMarker)) || pDemoHeader->m_Version < gs_ActVersion) { io_close(File); return false; } - + io_close(File); return true; } diff --git a/src/engine/shared/demo.h b/src/engine/shared/demo.h index c877536d..f1897f21 100644 --- a/src/engine/shared/demo.h +++ b/src/engine/shared/demo.h @@ -17,12 +17,12 @@ class CDemoRecorder : public IDemoRecorder int m_FirstTick; unsigned char m_aLastSnapshotData[CSnapshot::MAX_SIZE]; class CSnapshotDelta *m_pSnapshotDelta; - + void WriteTickMarker(int Tick, int Keyframe); void Write(int Type, const void *pData, int Size); public: CDemoRecorder(class CSnapshotDelta *pSnapshotDelta); - + int Start(class IStorage *pStorage, class IConsole *pConsole, const char *pFilename, const char *pNetversion, const char *pMap, unsigned MapCrc, const char *pType); int Stop(); @@ -44,21 +44,21 @@ public: virtual void OnDemoPlayerSnapshot(void *pData, int Size) = 0; virtual void OnDemoPlayerMessage(void *pData, int Size) = 0; }; - + struct CPlaybackInfo { CDemoHeader m_Header; - + IDemoPlayer::CInfo m_Info; int64 m_LastUpdate; int64 m_CurrentTime; - + int m_SeekablePoints; - + int m_NextTick; int m_PreviousTick; - + float m_IntraTick; float m_TickTime; }; @@ -73,12 +73,12 @@ private: long m_Filepos; int m_Tick; }; - + struct CKeyFrameSearch { CKeyFrame m_Frame; CKeyFrameSearch *m_pNext; - }; + }; class IConsole *m_pConsole; IOHANDLE m_File; @@ -97,25 +97,25 @@ private: int NextFrame(); public: - + CDemoPlayer(class CSnapshotDelta *m_pSnapshotDelta); - + void SetListner(IListner *pListner); - + int Load(class IStorage *pStorage, class IConsole *pConsole, const char *pFilename, int StorageType); int Play(); void Pause(); void Unpause(); - int Stop(); + int Stop(); void SetSpeed(float Speed); int SetPos(float Precent); const CInfo *BaseInfo() const { return &m_Info.m_Info; } char *GetDemoName(); bool GetDemoInfo(class IStorage *pStorage, const char *pFilename, int StorageType, CDemoHeader *pDemoHeader) const; int GetDemoType() const; - + int Update(); - + const CPlaybackInfo *Info() const { return &m_Info; } int IsPlaying() const { return m_File != 0; } }; diff --git a/src/engine/shared/engine.cpp b/src/engine/shared/engine.cpp index b4b4f2a5..5cc19c00 100644 --- a/src/engine/shared/engine.cpp +++ b/src/engine/shared/engine.cpp @@ -43,7 +43,7 @@ public: pEngine->m_Logging = false; } else - { + { char aBuf[32]; str_timestamp(aBuf, sizeof(aBuf)); char aFilenameSent[128], aFilenameRecv[128]; @@ -59,7 +59,7 @@ public: { dbg_logger_stdout(); dbg_logger_debugger(); - + // dbg_msg("engine", "running on %s-%s-%s", CONF_FAMILY_STRING, CONF_PLATFORM_STRING, CONF_ARCH_STRING); #ifdef CONF_ARCH_ENDIAN_LITTLE @@ -73,7 +73,7 @@ public: // init the network net_init(); CNetBase::Init(); - + m_JobPool.Init(1); m_Logging = false; diff --git a/src/engine/shared/huffman.cpp b/src/engine/shared/huffman.cpp index feb35b96..c88502b5 100644 --- a/src/engine/shared/huffman.cpp +++ b/src/engine/shared/huffman.cpp @@ -15,7 +15,7 @@ void CHuffman::Setbits_r(CNode *pNode, int Bits, unsigned Depth) Setbits_r(&m_aNodes[pNode->m_aLeafs[1]], Bits|(1<<Depth), Depth+1); if(pNode->m_aLeafs[0] != 0xffff) Setbits_r(&m_aNodes[pNode->m_aLeafs[0]], Bits, Depth+1); - + if(pNode->m_NumBits) { pNode->m_Bits = Bits; @@ -28,7 +28,7 @@ static void BubbleSort(CHuffmanConstructNode **ppList, int Size) { int Changed = 1; CHuffmanConstructNode *pTemp; - + while(Changed) { Changed = 0; @@ -68,15 +68,15 @@ void CHuffman::ConstructTree(const unsigned *pFrequencies) apNodesLeft[i] = &aNodesLeftStorage[i]; } - + m_NumNodes = HUFFMAN_MAX_SYMBOLS; - + // construct the table while(NumNodesLeft > 1) { // we can't rely on stdlib's qsort for this, it can generate different results on different implementations BubbleSort(apNodesLeft, NumNodesLeft); - + m_aNodes[m_NumNodes].m_NumBits = 0; m_aNodes[m_NumNodes].m_aLeafs[0] = apNodesLeft[NumNodesLeft-1]->m_NodeId; m_aNodes[m_NumNodes].m_aLeafs[1] = apNodesLeft[NumNodesLeft-2]->m_NodeId; @@ -89,7 +89,7 @@ void CHuffman::ConstructTree(const unsigned *pFrequencies) // set start node m_pStartNode = &m_aNodes[m_NumNodes-1]; - + // build symbol bits Setbits_r(m_pStartNode, 0, 0); } @@ -230,7 +230,7 @@ int CHuffman::Decompress(const void *pInput, int InputSize, void *pOutput, int O // {C} load symbol now if we didn't that earlier at location {A} if(!pNode) pNode = m_apDecodeLut[Bits&HUFFMAN_LUTMASK]; - + if(!pNode) return -1; diff --git a/src/engine/shared/huffman.h b/src/engine/shared/huffman.h index 0edc36c6..0d15ed99 100644 --- a/src/engine/shared/huffman.h +++ b/src/engine/shared/huffman.h @@ -13,7 +13,7 @@ class CHuffman HUFFMAN_MAX_SYMBOLS=HUFFMAN_EOF_SYMBOL+1, HUFFMAN_MAX_NODES=HUFFMAN_MAX_SYMBOLS*2-1, - + HUFFMAN_LUTBITS = 10, HUFFMAN_LUTSIZE = (1<<HUFFMAN_LUTBITS), HUFFMAN_LUTMASK = (HUFFMAN_LUTSIZE-1) @@ -36,10 +36,10 @@ class CHuffman CNode *m_apDecodeLut[HUFFMAN_LUTSIZE]; CNode *m_pStartNode; int m_NumNodes; - + void Setbits_r(CNode *pNode, int Bits, unsigned Depth); void ConstructTree(const unsigned *pFrequencies); - + public: /* Function: huffman_init @@ -86,6 +86,6 @@ public: Returns the size of the uncompressed data. Negative value on failure. */ int Decompress(const void *pInput, int InputSize, void *pOutput, int OutputSize); - + }; #endif // __HUFFMAN_HEADER__ diff --git a/src/engine/shared/jobs.cpp b/src/engine/shared/jobs.cpp index 4bc09325..02db4634 100644 --- a/src/engine/shared/jobs.cpp +++ b/src/engine/shared/jobs.cpp @@ -14,11 +14,11 @@ CJobPool::CJobPool() void CJobPool::WorkerThread(void *pUser) { CJobPool *pPool = (CJobPool *)pUser; - + while(1) { CJob *pJob = 0; - + // fetch job from queue lock_wait(pPool->m_Lock); if(pPool->m_pFirstJob) @@ -31,7 +31,7 @@ void CJobPool::WorkerThread(void *pUser) pPool->m_pLastJob = 0; } lock_release(pPool->m_Lock); - + // do the job if we have one if(pJob) { @@ -42,7 +42,7 @@ void CJobPool::WorkerThread(void *pUser) else thread_sleep(10); } - + } int CJobPool::Init(int NumThreads) @@ -58,9 +58,9 @@ int CJobPool::Add(CJob *pJob, JOBFUNC pfnFunc, void *pData) mem_zero(pJob, sizeof(CJob)); pJob->m_pfnFunc = pfnFunc; pJob->m_pFuncData = pData; - + lock_wait(m_Lock); - + // add job to queue pJob->m_pPrev = m_pLastJob; if(m_pLastJob) @@ -68,7 +68,7 @@ int CJobPool::Add(CJob *pJob, JOBFUNC pfnFunc, void *pData) m_pLastJob = pJob; if(!m_pFirstJob) m_pFirstJob = pJob; - + lock_release(m_Lock); return 0; } diff --git a/src/engine/shared/jobs.h b/src/engine/shared/jobs.h index 2b0d7d15..9e15228a 100644 --- a/src/engine/shared/jobs.h +++ b/src/engine/shared/jobs.h @@ -9,14 +9,14 @@ class CJobPool; class CJob { friend class CJobPool; - + CJobPool *m_pPool; CJob *m_pPrev; CJob *m_pNext; - + volatile int m_Status; volatile int m_Result; - + JOBFUNC m_pfnFunc; void *m_pFuncData; public: @@ -25,14 +25,14 @@ public: m_Status = STATE_DONE; m_pFuncData = 0; } - + enum { STATE_PENDING=0, STATE_RUNNING, STATE_DONE }; - + int Status() const { return m_Status; } int Result() const {return m_Result; } }; @@ -42,12 +42,12 @@ class CJobPool LOCK m_Lock; CJob *m_pFirstJob; CJob *m_pLastJob; - + static void WorkerThread(void *pUser); - + public: CJobPool(); - + int Init(int NumThreads); int Add(CJob *pJob, JOBFUNC pfnFunc, void *pData); }; diff --git a/src/engine/shared/kernel.cpp b/src/engine/shared/kernel.cpp index f59af8c7..b422b591 100644 --- a/src/engine/shared/kernel.cpp +++ b/src/engine/shared/kernel.cpp @@ -9,7 +9,7 @@ class CKernel : public IKernel { MAX_INTERFACES=32, }; - + class CInterfaceInfo { public: @@ -18,14 +18,14 @@ class CKernel : public IKernel m_aName[0] = 0; m_pInterface = 0x0; } - + char m_aName[64]; IInterface *m_pInterface; }; CInterfaceInfo m_aInterfaces[MAX_INTERFACES]; int m_NumInterfaces; - + CInterfaceInfo *FindInterfaceInfo(const char *pName) { for(int i = 0; i < m_NumInterfaces; i++) @@ -35,7 +35,7 @@ class CKernel : public IKernel } return 0x0; } - + public: CKernel() @@ -58,18 +58,18 @@ public: dbg_msg("kernel", "ERROR: couldn't register interface '%s'. maximum of interfaces reached", pName); return false; } - + if(FindInterfaceInfo(pName) != 0) { dbg_msg("kernel", "ERROR: couldn't register interface '%s'. interface already exists", pName); return false; } - + pInterface->m_pKernel = this; m_aInterfaces[m_NumInterfaces].m_pInterface = pInterface; str_copy(m_aInterfaces[m_NumInterfaces].m_aName, pName, sizeof(m_aInterfaces[m_NumInterfaces].m_aName)); m_NumInterfaces++; - + return true; } @@ -80,12 +80,12 @@ public: dbg_msg("kernel", "ERROR: couldn't reregister interface '%s'. interface doesn't exist"); return false; } - + pInterface->m_pKernel = this; - + return true; } - + virtual IInterface *RequestInterfaceImpl(const char *pName) { CInterfaceInfo *pInfo = FindInterfaceInfo(pName); diff --git a/src/engine/shared/map.cpp b/src/engine/shared/map.cpp index c57dd708..36c89cdc 100644 --- a/src/engine/shared/map.cpp +++ b/src/engine/shared/map.cpp @@ -10,7 +10,7 @@ class CMap : public IEngineMap CDataFileReader m_DataFile; public: CMap() {} - + virtual void *GetData(int Index) { return m_DataFile.GetData(Index); } virtual void *GetDataSwapped(int Index) { return m_DataFile.GetDataSwapped(Index); } virtual void UnloadData(int Index) { m_DataFile.UnloadData(Index); } @@ -18,7 +18,7 @@ public: virtual void GetType(int Type, int *pStart, int *pNum) { m_DataFile.GetType(Type, pStart, pNum); } virtual void *FindItem(int Type, int ID) { return m_DataFile.FindItem(Type, ID); } virtual int NumItems() { return m_DataFile.NumItems(); } - + virtual void Unload() { m_DataFile.Close(); @@ -31,12 +31,12 @@ public: return false; return m_DataFile.Open(pStorage, pMapName, IStorage::TYPE_ALL); } - + virtual bool IsLoaded() { return m_DataFile.IsOpen(); } - + virtual unsigned Crc() { return m_DataFile.Crc(); diff --git a/src/engine/shared/mapchecker.cpp b/src/engine/shared/mapchecker.cpp index dec4271d..f8ba30ae 100644 --- a/src/engine/shared/mapchecker.cpp +++ b/src/engine/shared/mapchecker.cpp @@ -42,7 +42,7 @@ void CMapChecker::AddMaplist(CMapVersion *pMaplist, int Num) m_pFirst = pEntry; str_copy(pEntry->m_aMapName, pMaplist[i].m_aName, sizeof(pEntry->m_aMapName)); - pEntry->m_MapCrc = (pMaplist[i].m_aCrc[0]<<24) | (pMaplist[i].m_aCrc[1]<<16) | (pMaplist[i].m_aCrc[2]<<8) | pMaplist[i].m_aCrc[3]; + pEntry->m_MapCrc = (pMaplist[i].m_aCrc[0]<<24) | (pMaplist[i].m_aCrc[1]<<16) | (pMaplist[i].m_aCrc[2]<<8) | pMaplist[i].m_aCrc[3]; pEntry->m_MapSize = (pMaplist[i].m_aSize[0]<<24) | (pMaplist[i].m_aSize[1]<<16) | (pMaplist[i].m_aSize[2]<<8) | pMaplist[i].m_aSize[3]; } } diff --git a/src/engine/shared/mapchecker.h b/src/engine/shared/mapchecker.h index 0d4332d9..6d9568d0 100644 --- a/src/engine/shared/mapchecker.h +++ b/src/engine/shared/mapchecker.h @@ -19,7 +19,7 @@ class CMapChecker unsigned m_MapSize; CWhitelistEntry *m_pNext; }; - + class CHeap m_Whitelist; CWhitelistEntry *m_pFirst; diff --git a/src/engine/shared/masterserver.cpp b/src/engine/shared/masterserver.cpp index 0e8cb394..1bf402ca 100644 --- a/src/engine/shared/masterserver.cpp +++ b/src/engine/shared/masterserver.cpp @@ -19,7 +19,7 @@ public: char m_aHostname[128]; NETADDR m_Addr; bool m_Valid; - + CHostLookup m_Lookup; } ; @@ -27,7 +27,7 @@ public: int m_NeedsUpdate; IEngine *m_pEngine; IStorage *m_pStorage; - + CMasterServer() { SetDefault(); @@ -38,10 +38,10 @@ public: virtual int RefreshAddresses(int Nettype) { int i; - + if(m_NeedsUpdate != -1) return 0; - + dbg_msg("engine/mastersrv", "refreshing master server addresses"); // add lookup jobs @@ -50,7 +50,7 @@ public: m_pEngine->HostLookup(&m_aMasterServers[i].m_Lookup, m_aMasterServers[i].m_aHostname, Nettype); m_aMasterServers[i].m_Valid = false; } - + m_NeedsUpdate = 1; return 0; } @@ -61,7 +61,7 @@ public: if(m_NeedsUpdate != 1) return; m_NeedsUpdate = 0; - + for(int i = 0; i < MAX_MASTERSERVERS; i++) { if(m_aMasterServers[i].m_Lookup.m_Job.Status() != CJob::STATE_DONE) @@ -78,7 +78,7 @@ public: m_aMasterServers[i].m_Valid = false; } } - + if(!m_NeedsUpdate) { dbg_msg("engine/mastersrv", "saving addresses"); @@ -91,12 +91,12 @@ public: return m_NeedsUpdate; } - virtual NETADDR GetAddr(int Index) + virtual NETADDR GetAddr(int Index) { return m_aMasterServers[Index].m_Addr; } - virtual const char *GetName(int Index) + virtual const char *GetName(int Index) { return m_aMasterServers[Index].m_aHostname; } @@ -136,12 +136,12 @@ public: int Count = 0; if(!m_pStorage) return -1; - + // try to open file File = m_pStorage->OpenFile("masters.cfg", IOFLAG_READ, IStorage::TYPE_SAVE); if(!File) return -1; - + LineReader.Init(File); while(1) { @@ -166,7 +166,7 @@ public: //else // dbg_msg("engine/mastersrv", "warning: couldn't parse master server '%s'", pLine); } - + io_close(File); return 0; } @@ -177,7 +177,7 @@ public: if(!m_pStorage) return -1; - + // try to open file File = m_pStorage->OpenFile("masters.cfg", IOFLAG_WRITE, IStorage::TYPE_SAVE); if(!File) @@ -189,10 +189,10 @@ public: net_addr_str(&m_aMasterServers[i].m_Addr, aAddrStr, sizeof(aAddrStr)); char aBuf[1024]; str_format(aBuf, sizeof(aBuf), "%s %s\n", m_aMasterServers[i].m_aHostname, aAddrStr); - + io_write(File, aBuf, str_length(aBuf)); } - + io_close(File); return 0; } diff --git a/src/engine/shared/memheap.cpp b/src/engine/shared/memheap.cpp index 850577dd..c1c09eaf 100644 --- a/src/engine/shared/memheap.cpp +++ b/src/engine/shared/memheap.cpp @@ -10,7 +10,7 @@ void CHeap::NewChunk() { CChunk *pChunk; char *pMem; - + // allocate memory pMem = (char*)mem_alloc(sizeof(CChunk)+CHUNK_SIZE, 1); if(!pMem) @@ -25,14 +25,14 @@ void CHeap::NewChunk() pChunk->m_pNext = (CChunk *)0x0; pChunk->m_pNext = m_pCurrent; - m_pCurrent = pChunk; + m_pCurrent = pChunk; } //**************** void *CHeap::AllocateFromChunk(unsigned int Size) { char *pMem; - + // check if we need can fit the allocation if(m_pCurrent->m_pCurrent + Size > m_pCurrent->m_pEnd) return (void*)0x0; @@ -66,14 +66,14 @@ void CHeap::Clear() { CChunk *pChunk = m_pCurrent; CChunk *pNext; - + while(pChunk) { pNext = pChunk->m_pNext; mem_free(pChunk); pChunk = pNext; } - + m_pCurrent = 0x0; } @@ -88,10 +88,10 @@ void *CHeap::Allocate(unsigned Size) { // allocate new chunk and add it to the heap NewChunk(); - + // try to allocate again pMem = (char *)AllocateFromChunk(Size); } - + return pMem; } diff --git a/src/engine/shared/memheap.h b/src/engine/shared/memheap.h index 7228212a..39adf2b1 100644 --- a/src/engine/shared/memheap.h +++ b/src/engine/shared/memheap.h @@ -11,20 +11,20 @@ class CHeap char *m_pEnd; CChunk *m_pNext; }; - + enum { // how large each chunk should be CHUNK_SIZE = 1025*64, }; - + CChunk *m_pCurrent; - - + + void Clear(); void NewChunk(); void *AllocateFromChunk(unsigned int Size); - + public: CHeap(); ~CHeap(); diff --git a/src/engine/shared/network.cpp b/src/engine/shared/network.cpp index 89ffae6d..ada4b18a 100644 --- a/src/engine/shared/network.cpp +++ b/src/engine/shared/network.cpp @@ -26,35 +26,35 @@ int CNetRecvUnpacker::FetchChunk(CNetChunk *pChunk) { CNetChunkHeader Header; unsigned char *pEnd = m_Data.m_aChunkData + m_Data.m_DataSize; - + while(1) { unsigned char *pData = m_Data.m_aChunkData; - + // check for old data to unpack if(!m_Valid || m_CurrentChunk >= m_Data.m_NumChunks) { Clear(); return 0; } - + // TODO: add checking here so we don't read too far for(int i = 0; i < m_CurrentChunk; i++) { pData = Header.Unpack(pData); pData += Header.m_Size; } - + // unpack the header pData = Header.Unpack(pData); m_CurrentChunk++; - + if(pData+Header.m_Size > pEnd) { Clear(); return 0; } - + // handle sequence stuff if(m_pConnection && (Header.m_Flags&NET_CHUNKFLAG_VITAL)) { @@ -76,7 +76,7 @@ int CNetRecvUnpacker::FetchChunk(CNetChunk *pChunk) continue; // take the next chunk in the packet } } - + // fill in the info pChunk->m_ClientID = m_ClientID; pChunk->m_Address = m_Addr; @@ -116,7 +116,7 @@ void CNetBase::SendPacket(NETSOCKET Socket, NETADDR *pAddr, CNetPacketConstruct io_write(ms_DataLogSent, &pPacket->m_aChunkData, pPacket->m_DataSize); io_flush(ms_DataLogSent); } - + // compress CompressedSize = ms_Huffman.Compress(pPacket->m_aChunkData, pPacket->m_DataSize, &aBuffer[3], NET_MAX_PACKETSIZE-4); @@ -174,7 +174,7 @@ int CNetBase::UnpackPacket(unsigned char *pBuffer, int Size, CNetPacketConstruct io_write(ms_DataLogRecv, pBuffer, Size); io_flush(ms_DataLogRecv); } - + // read the packet pPacket->m_Flags = pBuffer[0]>>4; pPacket->m_Ack = ((pBuffer[0]&0xf)<<8) | pBuffer[1]; @@ -188,7 +188,7 @@ int CNetBase::UnpackPacket(unsigned char *pBuffer, int Size, CNetPacketConstruct dbg_msg("", "connection less packet too small, %d", Size); return -1; } - + pPacket->m_Flags = NET_PACKETFLAG_CONNLESS; pPacket->m_Ack = 0; pPacket->m_NumChunks = 0; @@ -220,7 +220,7 @@ int CNetBase::UnpackPacket(unsigned char *pBuffer, int Size, CNetPacketConstruct io_write(ms_DataLogRecv, pPacket->m_aChunkData, pPacket->m_DataSize); io_flush(ms_DataLogRecv); } - + // return success return 0; } @@ -235,7 +235,7 @@ void CNetBase::SendControlMsg(NETSOCKET Socket, NETADDR *pAddr, int Ack, int Con Construct.m_DataSize = 1+ExtraSize; Construct.m_aChunkData[0] = ControlMsg; mem_copy(&Construct.m_aChunkData[1], pExtra, ExtraSize); - + // send the control message CNetBase::SendPacket(Socket, pAddr, &Construct); } @@ -284,7 +284,7 @@ int CNetBase::IsSeqInBackroom(int Seq, int Ack) if(Seq <= Ack && Seq >= Bottom) return 1; } - + return 0; } diff --git a/src/engine/shared/network.h b/src/engine/shared/network.h index cb1ec33a..f344049e 100644 --- a/src/engine/shared/network.h +++ b/src/engine/shared/network.h @@ -13,7 +13,7 @@ CURRENT: unsigned char flags_ack; // 4bit flags, 4bit ack unsigned char ack; // 8 bit ack unsigned char num_chunks; // 8 bit chunks - + (unsigned char padding[3]) // 24 bit extra incase it's a connection less packet // this is to make sure that it's compatible with the // old protocol @@ -30,11 +30,11 @@ enum NETSENDFLAG_VITAL=1, NETSENDFLAG_CONNLESS=2, NETSENDFLAG_FLUSH=4, - + NETSTATE_OFFLINE=0, NETSTATE_CONNECTING, NETSTATE_ONLINE, - + NETBANTYPE_SOFT=1, NETBANTYPE_DROP=2 }; @@ -65,17 +65,17 @@ enum NET_CHUNKFLAG_VITAL=1, NET_CHUNKFLAG_RESEND=2, - + NET_CTRLMSG_KEEPALIVE=0, NET_CTRLMSG_CONNECT=1, NET_CTRLMSG_CONNECTACCEPT=2, NET_CTRLMSG_ACCEPT=3, NET_CTRLMSG_CLOSE=4, - + NET_SERVER_MAXBANS=1024, - + NET_CONN_BUFFERSIZE=1024*32, - + NET_ENUM_TERMINATOR }; @@ -100,7 +100,7 @@ public: int m_Flags; int m_Size; int m_Sequence; - + unsigned char *Pack(unsigned char *pData); unsigned char *Unpack(unsigned char *pData); }; @@ -138,30 +138,30 @@ private: unsigned short m_Sequence; unsigned short m_Ack; unsigned m_State; - + int m_Token; int m_RemoteClosed; - + TStaticRingBuffer<CNetChunkResend, NET_CONN_BUFFERSIZE> m_Buffer; - + int64 m_LastUpdateTime; int64 m_LastRecvTime; int64 m_LastSendTime; - + char m_ErrorString[256]; - + CNetPacketConstruct m_Construct; - + NETADDR m_PeerAddr; NETSOCKET m_Socket; NETSTATS m_Stats; - + // void Reset(); void ResetStats(); void SetError(const char *pString); void AckChunks(int Ack); - + int QueueChunkEx(int Flags, int DataSize, const void *pData, int Sequence); void SendControl(int ControlMsg, const void *pExtra, int ExtraSize); void ResendChunk(CNetChunkResend *pResend); @@ -173,7 +173,7 @@ public: void Disconnect(const char *pReason); int Update(); - int Flush(); + int Flush(); int Feed(CNetPacketConstruct *pPacket, NETADDR *pAddr); int QueueChunk(int Flags, int DataSize, const void *pData); @@ -182,13 +182,13 @@ public: void SignalResend(); int State() const { return m_State; } NETADDR PeerAddress() const { return m_PeerAddr; } - + void ResetErrorString() { m_ErrorString[0] = 0; } const char *ErrorString() const { return m_ErrorString; } - + // Needed for GotProblems in NetClient int64 LastRecvTime() const { return m_LastRecvTime; } - + int AckSequence() const { return m_Ack; } }; @@ -196,7 +196,7 @@ struct CNetRecvUnpacker { public: bool m_Valid; - + NETADDR m_Addr; CNetConnection *m_pConnection; int m_CurrentChunk; @@ -207,7 +207,7 @@ public: CNetRecvUnpacker() { Clear(); } void Clear(); void Start(const NETADDR *pAddr, CNetConnection *pConnection, int ClientID); - int FetchChunk(CNetChunk *pChunk); + int FetchChunk(CNetChunk *pChunk); }; // server side @@ -220,29 +220,29 @@ public: int m_Expires; char m_Reason[128]; }; - + private: class CSlot { public: CNetConnection m_Connection; }; - + class CBan { public: CBanInfo m_Info; - + // hash list CBan *m_pHashNext; CBan *m_pHashPrev; - + // used or free list CBan *m_pNext; CBan *m_pPrev; }; - - + + NETSOCKET m_Socket; CSlot m_aSlots[NET_MAX_CLIENTS]; int m_MaxClients; @@ -256,23 +256,23 @@ private: NETFUNC_NEWCLIENT m_pfnNewClient; NETFUNC_DELCLIENT m_pfnDelClient; void *m_UserPtr; - + CNetRecvUnpacker m_RecvUnpacker; - + void BanRemoveByObject(CBan *pBan); - + public: int SetCallbacks(NETFUNC_NEWCLIENT pfnNewClient, NETFUNC_DELCLIENT pfnDelClient, void *pUser); // bool Open(NETADDR BindAddr, int MaxClients, int MaxClientsPerIP, int Flags); int Close(); - + // int Recv(CNetChunk *pChunk); int Send(CNetChunk *pChunk); int Update(); - + // int Drop(int ClientID, const char *pReason); @@ -304,21 +304,21 @@ public: // openness bool Open(NETADDR BindAddr, int Flags); int Close(); - + // connection state int Disconnect(const char *Reason); int Connect(NETADDR *Addr); - + // communication int Recv(CNetChunk *Chunk); int Send(CNetChunk *Chunk); - + // pumping int Update(); int Flush(); int ResetErrorString(); - + // error and state int State(); int GotProblems(); @@ -339,14 +339,14 @@ public: static void Init(); static int Compress(const void *pData, int DataSize, void *pOutput, int OutputSize); static int Decompress(const void *pData, int DataSize, void *pOutput, int OutputSize); - + static void SendControlMsg(NETSOCKET Socket, NETADDR *pAddr, int Ack, int ControlMsg, const void *pExtra, int ExtraSize); static void SendPacketConnless(NETSOCKET Socket, NETADDR *pAddr, const void *pData, int DataSize); static void SendPacket(NETSOCKET Socket, NETADDR *pAddr, CNetPacketConstruct *pPacket); static int UnpackPacket(unsigned char *pBuffer, int Size, CNetPacketConstruct *pPacket); // The backroom is ack-NET_MAX_SEQUENCE/2. Used for knowing if we acked a packet or not - static int IsSeqInBackroom(int Seq, int Ack); + static int IsSeqInBackroom(int Seq, int Ack); }; diff --git a/src/engine/shared/network_client.cpp b/src/engine/shared/network_client.cpp index 82a09474..2c035606 100644 --- a/src/engine/shared/network_client.cpp +++ b/src/engine/shared/network_client.cpp @@ -61,7 +61,7 @@ int CNetClient::Recv(CNetChunk *pChunk) // check for a chunk if(m_RecvUnpacker.FetchChunk(pChunk)) return 1; - + // TODO: empty the recvinfo NETADDR Addr; int Bytes = net_udp_recv(m_Socket, &Addr, m_RecvUnpacker.m_aBuffer, NET_MAX_PACKETSIZE); @@ -98,7 +98,7 @@ int CNetClient::Send(CNetChunk *pChunk) dbg_msg("netclient", "chunk payload too big. %d. dropping chunk", pChunk->m_DataSize); return -1; } - + if(pChunk->m_Flags&NETSENDFLAG_CONNLESS) { // send connectionless packet @@ -108,10 +108,10 @@ int CNetClient::Send(CNetChunk *pChunk) { int Flags = 0; dbg_assert(pChunk->m_ClientID == 0, "errornous client id"); - + if(pChunk->m_Flags&NETSENDFLAG_VITAL) Flags = NET_CHUNKFLAG_VITAL; - + m_Connection.QueueChunk(Flags, pChunk->m_DataSize, pChunk->m_pData); if(pChunk->m_Flags&NETSENDFLAG_FLUSH) diff --git a/src/engine/shared/network_conn.cpp b/src/engine/shared/network_conn.cpp index dd61de86..6531f5aa 100644 --- a/src/engine/shared/network_conn.cpp +++ b/src/engine/shared/network_conn.cpp @@ -14,16 +14,16 @@ void CNetConnection::Reset() m_Sequence = 0; m_Ack = 0; m_RemoteClosed = 0; - + m_State = NET_CONNSTATE_OFFLINE; m_LastSendTime = 0; m_LastRecvTime = 0; m_LastUpdateTime = 0; m_Token = -1; mem_zero(&m_PeerAddr, sizeof(m_PeerAddr)); - + m_Buffer.Init(); - + mem_zero(&m_Construct, sizeof(m_Construct)); } @@ -41,7 +41,7 @@ void CNetConnection::Init(NETSOCKET Socket) { Reset(); ResetStats(); - + m_Socket = Socket; mem_zero(m_ErrorString, sizeof(m_ErrorString)); } @@ -53,7 +53,7 @@ void CNetConnection::AckChunks(int Ack) CNetChunkResend *pResend = m_Buffer.First(); if(!pResend) break; - + if(CNetBase::IsSeqInBackroom(pResend->m_Sequence, Ack)) m_Buffer.PopFirst(); else @@ -75,10 +75,10 @@ int CNetConnection::Flush() // send of the packets m_Construct.m_Ack = m_Ack; CNetBase::SendPacket(m_Socket, &m_PeerAddr, &m_Construct); - + // update send times m_LastSendTime = time_get(); - + // clear construct so we can start building a new package mem_zero(&m_Construct, sizeof(m_Construct)); return NumChunks; @@ -87,7 +87,7 @@ int CNetConnection::Flush() int CNetConnection::QueueChunkEx(int Flags, int DataSize, const void *pData, int Sequence) { unsigned char *pChunkData; - + // check if we have space for it, if not, flush the connection if(m_Construct.m_DataSize + DataSize + NET_MAX_CHUNKHEADERSIZE > (int)sizeof(m_Construct.m_aChunkData)) Flush(); @@ -105,9 +105,9 @@ int CNetConnection::QueueChunkEx(int Flags, int DataSize, const void *pData, int // m_Construct.m_NumChunks++; m_Construct.m_DataSize = (int)(pChunkData-m_Construct.m_aChunkData); - + // set packet flags aswell - + if(Flags&NET_CHUNKFLAG_VITAL && !(Flags&NET_CHUNKFLAG_RESEND)) { // save packet if we need to resend @@ -163,7 +163,7 @@ int CNetConnection::Connect(NETADDR *pAddr) { if(State() != NET_CONNSTATE_OFFLINE) return -1; - + // init connection Reset(); m_PeerAddr = *pAddr; @@ -189,14 +189,14 @@ void CNetConnection::Disconnect(const char *pReason) if(pReason) str_copy(m_ErrorString, pReason, sizeof(m_ErrorString)); } - + Reset(); } int CNetConnection::Feed(CNetPacketConstruct *pPacket, NETADDR *pAddr) { int64 Now = time_get(); - + // check if resend is requested if(pPacket->m_Flags&NET_PACKETFLAG_RESEND) Resend(); @@ -205,14 +205,14 @@ int CNetConnection::Feed(CNetPacketConstruct *pPacket, NETADDR *pAddr) if(pPacket->m_Flags&NET_PACKETFLAG_CONTROL) { int CtrlMsg = pPacket->m_aChunkData[0]; - + if(CtrlMsg == NET_CTRLMSG_CLOSE) { if(net_addr_comp(&m_PeerAddr, pAddr) == 0) { m_State = NET_CONNSTATE_ERROR; m_RemoteClosed = 1; - + if(pPacket->m_DataSize) { // make sure to sanitize the error string form the other party @@ -222,17 +222,17 @@ int CNetConnection::Feed(CNetPacketConstruct *pPacket, NETADDR *pAddr) else str_copy(Str, (char *)pPacket->m_aChunkData, sizeof(Str)); str_sanitize_strong(Str); - + // set the error string SetError(Str); } else SetError("No reason given"); - + if(g_Config.m_Debug) dbg_msg("conn", "closed reason='%s'", ErrorString()); } - return 0; + return 0; } else { @@ -249,7 +249,7 @@ int CNetConnection::Feed(CNetPacketConstruct *pPacket, NETADDR *pAddr) m_LastUpdateTime = Now; SendControl(NET_CTRLMSG_CONNECTACCEPT, 0, 0); if(g_Config.m_Debug) - dbg_msg("connection", "got connection, sending connect+accept"); + dbg_msg("connection", "got connection, sending connect+accept"); } } else if(State() == NET_CONNSTATE_CONNECT) @@ -276,13 +276,13 @@ int CNetConnection::Feed(CNetPacketConstruct *pPacket, NETADDR *pAddr) dbg_msg("connection", "connecting online"); } } - + if(State() == NET_CONNSTATE_ONLINE) { m_LastRecvTime = Now; AckChunks(pPacket->m_Ack); } - + return 1; } @@ -292,7 +292,7 @@ int CNetConnection::Update() if(State() == NET_CONNSTATE_OFFLINE || State() == NET_CONNSTATE_ERROR) return 0; - + // check for timeout if(State() != NET_CONNSTATE_OFFLINE && State() != NET_CONNSTATE_CONNECT && @@ -320,7 +320,7 @@ int CNetConnection::Update() ResendChunk(pResend); } } - + // send keep alives if nothing has happend for 250ms if(State() == NET_CONNSTATE_ONLINE) { @@ -330,7 +330,7 @@ int CNetConnection::Update() if(NumFlushedChunks && g_Config.m_Debug) dbg_msg("connection", "flushed connection due to timeout. %d chunks.", NumFlushedChunks); } - + if(time_get()-m_LastSendTime > time_freq()) SendControl(NET_CTRLMSG_KEEPALIVE, 0, 0); } @@ -344,6 +344,6 @@ int CNetConnection::Update() if(time_get()-m_LastSendTime > time_freq()/2) // send a new connect/accept every 500ms SendControl(NET_CTRLMSG_CONNECTACCEPT, 0, 0); } - + return 0; } diff --git a/src/engine/shared/network_server.cpp b/src/engine/shared/network_server.cpp index 76d5f695..3078ab9f 100644 --- a/src/engine/shared/network_server.cpp +++ b/src/engine/shared/network_server.cpp @@ -8,7 +8,7 @@ Object->Prev = (struct CBan *)0; \ Object->Next = First; \ First = Object; } - + #define MACRO_LIST_LINK_AFTER(Object, After, Prev, Next) \ { Object->Prev = After; \ Object->Next = After->Next; \ @@ -22,7 +22,7 @@ if(Object->Prev) Object->Prev->Next = Object->Next; \ else First = Object->Next; \ Object->Next = 0; Object->Prev = 0; } - + #define MACRO_LIST_FIND(Start, Next, Expression) \ { while(Start && !(Expression)) Start = Start->Next; } @@ -30,12 +30,12 @@ bool CNetServer::Open(NETADDR BindAddr, int MaxClients, int MaxClientsPerIP, int { // zero out the whole structure mem_zero(this, sizeof(*this)); - + // open socket m_Socket = net_udp_create(BindAddr); if(!m_Socket.type) return false; - + // clamp clients m_MaxClients = MaxClients; if(m_MaxClients > NET_MAX_CLIENTS) @@ -44,17 +44,17 @@ bool CNetServer::Open(NETADDR BindAddr, int MaxClients, int MaxClientsPerIP, int m_MaxClients = 1; m_MaxClientsPerIP = MaxClientsPerIP; - + for(int i = 0; i < NET_MAX_CLIENTS; i++) m_aSlots[i].m_Connection.Init(m_Socket); - + // setup all pointers for bans for(int i = 1; i < NET_SERVER_MAXBANS-1; i++) { m_BanPool[i].m_pNext = &m_BanPool[i+1]; m_BanPool[i].m_pPrev = &m_BanPool[i-1]; } - + m_BanPool[0].m_pNext = &m_BanPool[1]; m_BanPool[NET_SERVER_MAXBANS-1].m_pPrev = &m_BanPool[NET_SERVER_MAXBANS-2]; m_BanPool_FirstFree = &m_BanPool[0]; @@ -88,9 +88,9 @@ int CNetServer::Drop(int ClientID, const char *pReason) );*/ if(m_pfnDelClient) m_pfnDelClient(ClientID, pReason, m_UserPtr); - + m_aSlots[ClientID].m_Connection.Disconnect(pReason); - + return 0; } @@ -99,7 +99,7 @@ int CNetServer::BanGet(int Index, CBanInfo *pInfo) CBan *pBan; for(pBan = m_BanPool_FirstUsed; pBan && Index; pBan = pBan->m_pNext, Index--) {} - + if(!pBan) return 0; *pInfo = pBan->m_Info; @@ -134,15 +134,15 @@ int CNetServer::BanRemove(NETADDR Addr) int IpHash = (Addr.ip[0]+Addr.ip[1]+Addr.ip[2]+Addr.ip[3]+Addr.ip[4]+Addr.ip[5]+Addr.ip[6]+Addr.ip[7]+ Addr.ip[8]+Addr.ip[9]+Addr.ip[10]+Addr.ip[11]+Addr.ip[12]+Addr.ip[13]+Addr.ip[14]+Addr.ip[15])&0xff; CBan *pBan = m_aBans[IpHash]; - + MACRO_LIST_FIND(pBan, m_pHashNext, net_addr_comp(&pBan->m_Info.m_Addr, &Addr) == 0); - + if(pBan) { BanRemoveByObject(pBan); return 0; } - + return -1; } @@ -152,13 +152,13 @@ int CNetServer::BanAdd(NETADDR Addr, int Seconds, const char *pReason) Addr.ip[8]+Addr.ip[9]+Addr.ip[10]+Addr.ip[11]+Addr.ip[12]+Addr.ip[13]+Addr.ip[14]+Addr.ip[15])&0xff; int Stamp = -1; CBan *pBan; - + // remove the port Addr.port = 0; - + if(Seconds) Stamp = time_timestamp() + Seconds; - + // search to see if it already exists pBan = m_aBans[IpHash]; MACRO_LIST_FIND(pBan, m_pHashNext, net_addr_comp(&pBan->m_Info.m_Addr, &Addr) == 0); @@ -168,29 +168,29 @@ int CNetServer::BanAdd(NETADDR Addr, int Seconds, const char *pReason) pBan->m_Info.m_Expires = Stamp; return 0; } - + if(!m_BanPool_FirstFree) return -1; // fetch and clear the new ban pBan = m_BanPool_FirstFree; MACRO_LIST_UNLINK(pBan, m_BanPool_FirstFree, m_pPrev, m_pNext); - + // setup the ban info pBan->m_Info.m_Expires = Stamp; pBan->m_Info.m_Addr = Addr; str_copy(pBan->m_Info.m_Reason, pReason, sizeof(pBan->m_Info.m_Reason)); - + // add it to the ban hash MACRO_LIST_LINK_FIRST(pBan, m_aBans[IpHash], m_pHashPrev, m_pHashNext); - + // insert it into the used list { if(m_BanPool_FirstUsed) { CBan *pInsertAfter = m_BanPool_FirstUsed; MACRO_LIST_FIND(pInsertAfter, m_pNext, Stamp < pInsertAfter->m_Info.m_Expires); - + if(pInsertAfter) pInsertAfter = pInsertAfter->m_pPrev; else @@ -200,7 +200,7 @@ int CNetServer::BanAdd(NETADDR Addr, int Seconds, const char *pReason) while(pInsertAfter->m_pNext) pInsertAfter = pInsertAfter->m_pNext; } - + if(pInsertAfter) { MACRO_LIST_LINK_AFTER(pBan, pInsertAfter, m_pPrev, m_pNext); @@ -220,7 +220,7 @@ int CNetServer::BanAdd(NETADDR Addr, int Seconds, const char *pReason) { char Buf[128]; NETADDR BanAddr; - + int Mins = (Seconds + 59) / 60; if(Mins) { @@ -231,12 +231,12 @@ int CNetServer::BanAdd(NETADDR Addr, int Seconds, const char *pReason) } else str_format(Buf, sizeof(Buf), "You have been banned for life (%s)", pReason); - + for(int i = 0; i < MaxClients(); i++) { BanAddr = m_aSlots[i].m_Connection.PeerAddress(); BanAddr.port = 0; - + if(net_addr_comp(&Addr, &BanAddr) == 0) Drop(i, Buf); } @@ -253,14 +253,14 @@ int CNetServer::Update() if(m_aSlots[i].m_Connection.State() == NET_CONNSTATE_ERROR) Drop(i, m_aSlots[i].m_Connection.ErrorString()); } - + // remove expired bans while(m_BanPool_FirstUsed && m_BanPool_FirstUsed->m_Info.m_Expires < Now) { CBan *pBan = m_BanPool_FirstUsed; BanRemoveByObject(pBan); } - + return 0; } @@ -270,22 +270,22 @@ int CNetServer::Update() int CNetServer::Recv(CNetChunk *pChunk) { unsigned Now = time_timestamp(); - + while(1) { NETADDR Addr; - + // check for a chunk if(m_RecvUnpacker.FetchChunk(pChunk)) return 1; - + // TODO: empty the recvinfo int Bytes = net_udp_recv(m_Socket, &Addr, m_RecvUnpacker.m_aBuffer, NET_MAX_PACKETSIZE); // no more packets for now if(Bytes <= 0) break; - + if(CNetBase::UnpackPacket(m_RecvUnpacker.m_aBuffer, Bytes, &m_RecvUnpacker.m_Data) == 0) { CBan *pBan = 0; @@ -294,14 +294,14 @@ int CNetServer::Recv(CNetChunk *pChunk) BanAddr.ip[8]+BanAddr.ip[9]+BanAddr.ip[10]+BanAddr.ip[11]+BanAddr.ip[12]+BanAddr.ip[13]+BanAddr.ip[14]+BanAddr.ip[15])&0xff; int Found = 0; BanAddr.port = 0; - + // search a ban for(pBan = m_aBans[IpHash]; pBan; pBan = pBan->m_pHashNext) { if(net_addr_comp(&pBan->m_Info.m_Addr, &BanAddr) == 0) break; } - + // check if we just should drop the packet if(pBan) { @@ -320,7 +320,7 @@ int CNetServer::Recv(CNetChunk *pChunk) CNetBase::SendControlMsg(m_Socket, &Addr, 0, NET_CTRLMSG_CLOSE, BanStr, str_length(BanStr)+1); continue; } - + if(m_RecvUnpacker.m_Data.m_Flags&NET_PACKETFLAG_CONNLESS) { pChunk->m_Flags = NETSENDFLAG_CONNLESS; @@ -331,12 +331,12 @@ int CNetServer::Recv(CNetChunk *pChunk) return 1; } else - { + { // TODO: check size here if(m_RecvUnpacker.m_Data.m_Flags&NET_PACKETFLAG_CONTROL && m_RecvUnpacker.m_Data.m_aChunkData[0] == NET_CTRLMSG_CONNECT) { Found = 0; - + // check if we already got this client for(int i = 0; i < MaxClients(); i++) { @@ -348,7 +348,7 @@ int CNetServer::Recv(CNetChunk *pChunk) break; } } - + // client that wants to connect if(!Found) { @@ -386,7 +386,7 @@ int CNetServer::Recv(CNetChunk *pChunk) break; } } - + if(!Found) { const char FullMsg[] = "This server is full"; @@ -423,7 +423,7 @@ int CNetServer::Send(CNetChunk *pChunk) dbg_msg("netserver", "packet payload too big. %d. dropping packet", pChunk->m_DataSize); return -1; } - + if(pChunk->m_Flags&NETSENDFLAG_CONNLESS) { // send connectionless packet @@ -434,10 +434,10 @@ int CNetServer::Send(CNetChunk *pChunk) int Flags = 0; dbg_assert(pChunk->m_ClientID >= 0, "errornous client id"); dbg_assert(pChunk->m_ClientID < MaxClients(), "errornous client id"); - + if(pChunk->m_Flags&NETSENDFLAG_VITAL) Flags = NET_CHUNKFLAG_VITAL; - + if(m_aSlots[pChunk->m_ClientID].m_Connection.QueueChunk(Flags, pChunk->m_DataSize, pChunk->m_pData) == 0) { if(pChunk->m_Flags&NETSENDFLAG_FLUSH) diff --git a/src/engine/shared/packer.cpp b/src/engine/shared/packer.cpp index cd211468..cc218825 100644 --- a/src/engine/shared/packer.cpp +++ b/src/engine/shared/packer.cpp @@ -17,7 +17,7 @@ void CPacker::AddInt(int i) { if(m_Error) return; - + // make sure that we have space enough if(m_pEnd - m_pCurrent < 6) { @@ -32,7 +32,7 @@ void CPacker::AddString(const char *pStr, int Limit) { if(m_Error) return; - + // if(Limit > 0) { @@ -40,7 +40,7 @@ void CPacker::AddString(const char *pStr, int Limit) { *m_pCurrent++ = *pStr++; Limit--; - + if(m_pCurrent >= m_pEnd) { m_Error = 1; @@ -69,13 +69,13 @@ void CPacker::AddRaw(const void *pData, int Size) { if(m_Error) return; - + if(m_pCurrent+Size >= m_pEnd) { m_Error = 1; return; } - + const unsigned char *pSrc = (const unsigned char *)pData; while(Size) { @@ -97,13 +97,13 @@ int CUnpacker::GetInt() { if(m_Error) return 0; - + if(m_pCurrent >= m_pEnd) { m_Error = 1; return 0; } - + int i; m_pCurrent = CVariableInt::Unpack(m_pCurrent, &i); if(m_pCurrent > m_pEnd) @@ -118,7 +118,7 @@ const char *CUnpacker::GetString(int SanitizeType) { if(m_Error || m_pCurrent >= m_pEnd) return ""; - + char *pPtr = (char *)m_pCurrent; while(*m_pCurrent) // skip the string { @@ -130,7 +130,7 @@ const char *CUnpacker::GetString(int SanitizeType) } } m_pCurrent++; - + // sanitize all strings if(SanitizeType&SANITIZE) str_sanitize(pPtr); @@ -144,7 +144,7 @@ const unsigned char *CUnpacker::GetRaw(int Size) const unsigned char *pPtr = m_pCurrent; if(m_Error) return 0; - + // check for nasty sizes if(Size < 0 || m_pCurrent+Size > m_pEnd) { diff --git a/src/engine/shared/packer.h b/src/engine/shared/packer.h index 9091370a..bd04e36e 100644 --- a/src/engine/shared/packer.h +++ b/src/engine/shared/packer.h @@ -21,7 +21,7 @@ public: void AddInt(int i); void AddString(const char *pStr, int Limit); void AddRaw(const void *pData, int Size); - + int Size() const { return (int)(m_pCurrent-m_aBuffer); } const unsigned char *Data() const { return m_aBuffer; } bool Error() const { return m_Error; } diff --git a/src/engine/shared/protocol.h b/src/engine/shared/protocol.h index 859f4941..4a4895ad 100644 --- a/src/engine/shared/protocol.h +++ b/src/engine/shared/protocol.h @@ -7,13 +7,13 @@ /* Connection diagram - How the initilization works. - + Client -> INFO -> Server Contains version info, name, and some other info. - + Client <- MAP <- Server Contains current map. - + Client -> READY -> Server The client has loaded the map and is ready to go, but the mod needs to send it's information aswell. @@ -21,7 +21,7 @@ mods_connected is called on the server. The client should call client_entergame when the mod has done it's initilization. - + Client -> ENTERGAME -> Server Tells the server to start sending snapshots. client_entergame and server_client_enter is called. @@ -31,11 +31,11 @@ enum { NETMSG_NULL=0, - + // the first thing sent by the client // contains the version info for the client NETMSG_INFO=1, - + // sent by server NETMSG_MAP_CHANGE, // sent when client should switch map NETMSG_MAP_DATA, // map transfer, contains a chunk of the map file @@ -50,18 +50,18 @@ enum NETMSG_AUTH_CHALLANGE, // NETMSG_AUTH_RESULT, // - + // sent by client NETMSG_READY, // NETMSG_ENTERGAME, NETMSG_INPUT, // contains the inputdata from the client - NETMSG_RCON_CMD, // + NETMSG_RCON_CMD, // NETMSG_RCON_AUTH, // NETMSG_REQUEST_MAP_DATA,// NETMSG_AUTH_START, // NETMSG_AUTH_RESPONSE, // - + // sent by both NETMSG_PING, NETMSG_PING_REPLY, diff --git a/src/engine/shared/ringbuffer.cpp b/src/engine/shared/ringbuffer.cpp index 172508d7..b9f55d73 100644 --- a/src/engine/shared/ringbuffer.cpp +++ b/src/engine/shared/ringbuffer.cpp @@ -3,7 +3,7 @@ #include <base/system.h> #include "ringbuffer.h" - + CRingBufferBase::CItem *CRingBufferBase::NextBlock(CItem *pItem) { if(pItem->m_pNext) @@ -27,19 +27,19 @@ CRingBufferBase::CItem *CRingBufferBase::MergeBack(CItem *pItem) // merge the blocks pItem->m_pPrev->m_Size += pItem->m_Size; pItem->m_pPrev->m_pNext = pItem->m_pNext; - + // fixup pointers if(pItem->m_pNext) pItem->m_pNext->m_pPrev = pItem->m_pPrev; else m_pLast = pItem->m_pPrev; - + if(pItem == m_pProduce) m_pProduce = pItem->m_pPrev; - + if(pItem == m_pConsume) m_pConsume = pItem->m_pPrev; - + // return the current block return pItem->m_pPrev; } @@ -54,8 +54,8 @@ void CRingBufferBase::Init(void *pMemory, int Size, int Flags) m_pLast = m_pFirst; m_pProduce = m_pFirst; m_pConsume = m_pFirst; - m_Flags = Flags; - + m_Flags = Flags; + } void *CRingBufferBase::Allocate(int Size) @@ -67,7 +67,7 @@ void *CRingBufferBase::Allocate(int Size) if(WantedSize > m_Size) return 0; - while(1) + while(1) { // check for space if(m_pProduce->m_Free) @@ -81,7 +81,7 @@ void *CRingBufferBase::Allocate(int Size) pBlock = m_pFirst; } } - + if(pBlock) break; else @@ -96,9 +96,9 @@ void *CRingBufferBase::Allocate(int Size) return 0; } } - + // okey, we have our block - + // split the block if needed if(pBlock->m_Size > WantedSize+(int)sizeof(CItem)) { @@ -108,19 +108,19 @@ void *CRingBufferBase::Allocate(int Size) if(pNewItem->m_pNext) pNewItem->m_pNext->m_pPrev = pNewItem; pBlock->m_pNext = pNewItem; - + pNewItem->m_Free = 1; pNewItem->m_Size = pBlock->m_Size - WantedSize; pBlock->m_Size = WantedSize; - + if(!pNewItem->m_pNext) m_pLast = pNewItem; } - - + + // set next block m_pProduce = NextBlock(pBlock); - + // set as used and return the item pointer pBlock->m_Free = 0; return (void *)(pBlock+1); @@ -130,13 +130,13 @@ int CRingBufferBase::PopFirst() { if(m_pConsume->m_Free) return 0; - + // set the free flag m_pConsume->m_Free = 1; - + // previous block is also free, merge them m_pConsume = MergeBack(m_pConsume); - + // advance the consume pointer m_pConsume = NextBlock(m_pConsume); while(m_pConsume->m_Free && m_pConsume != m_pProduce) @@ -144,7 +144,7 @@ int CRingBufferBase::PopFirst() m_pConsume = MergeBack(m_pConsume); m_pConsume = NextBlock(m_pConsume); } - + // in the case that we have catched up with the produce pointer // we might stand on a free block so merge em MergeBack(m_pConsume); @@ -155,7 +155,7 @@ int CRingBufferBase::PopFirst() void *CRingBufferBase::Prev(void *pCurrent) { CItem *pItem = ((CItem *)pCurrent) - 1; - + while(1) { pItem = PrevBlock(pItem); @@ -169,7 +169,7 @@ void *CRingBufferBase::Prev(void *pCurrent) void *CRingBufferBase::Next(void *pCurrent) { CItem *pItem = ((CItem *)pCurrent) - 1; - + while(1) { pItem = NextBlock(pItem); diff --git a/src/engine/shared/ringbuffer.h b/src/engine/shared/ringbuffer.h index 9f0c5a1d..c4774528 100644 --- a/src/engine/shared/ringbuffer.h +++ b/src/engine/shared/ringbuffer.h @@ -15,28 +15,28 @@ class CRingBufferBase int m_Free; int m_Size; }; - + CItem *m_pProduce; CItem *m_pConsume; - + CItem *m_pFirst; CItem *m_pLast; - + void *m_pMemory; int m_Size; int m_Flags; - + CItem *NextBlock(CItem *pItem); CItem *PrevBlock(CItem *pItem); CItem *MergeBack(CItem *pItem); protected: void *Allocate(int Size); - + void *Prev(void *pCurrent); void *Next(void *pCurrent); void *First(); void *Last(); - + void Init(void *pMemory, int Size, int Flags); int PopFirst(); public: @@ -53,9 +53,9 @@ class TStaticRingBuffer : public CRingBufferBase unsigned char m_aBuffer[TSIZE]; public: TStaticRingBuffer() { Init(); } - + void Init() { CRingBufferBase::Init(m_aBuffer, TSIZE, TFLAGS); } - + T *Allocate(int Size) { return (T*)CRingBufferBase::Allocate(Size); } int PopFirst() { return CRingBufferBase::PopFirst(); } diff --git a/src/engine/shared/snapshot.cpp b/src/engine/shared/snapshot.cpp index fee6afa2..9ef8fdc3 100644 --- a/src/engine/shared/snapshot.cpp +++ b/src/engine/shared/snapshot.cpp @@ -12,31 +12,31 @@ CSnapshotItem *CSnapshot::GetItem(int Index) int CSnapshot::GetItemSize(int Index) { - if(Index == m_NumItems-1) - return (m_DataSize - Offsets()[Index]) - sizeof(CSnapshotItem); - return (Offsets()[Index+1] - Offsets()[Index]) - sizeof(CSnapshotItem); + if(Index == m_NumItems-1) + return (m_DataSize - Offsets()[Index]) - sizeof(CSnapshotItem); + return (Offsets()[Index+1] - Offsets()[Index]) - sizeof(CSnapshotItem); } int CSnapshot::GetItemIndex(int Key) { - // TODO: OPT: this should not be a linear search. very bad - for(int i = 0; i < m_NumItems; i++) - { - if(GetItem(i)->Key() == Key) - return i; - } - return -1; + // TODO: OPT: this should not be a linear search. very bad + for(int i = 0; i < m_NumItems; i++) + { + if(GetItem(i)->Key() == Key) + return i; + } + return -1; } int CSnapshot::Crc() { int Crc = 0; - + for(int i = 0; i < m_NumItems; i++) { CSnapshotItem *pItem = GetItem(i); int Size = GetItemSize(i); - + for(int b = 0; b < Size/4; b++) Crc += pItem->Data()[b]; } @@ -75,7 +75,7 @@ static void GenerateHash(CItemList *pHashlist, CSnapshot *pSnapshot) { for(int i = 0; i < HASHLIST_SIZE; i++) pHashlist[i].m_Num = 0; - + for(int i = 0; i < pSnapshot->NumItems(); i++) { int Key = pSnapshot->GetItem(i)->Key(); @@ -97,7 +97,7 @@ static int GetItemIndexHashed(int Key, const CItemList *pHashlist) if(pHashlist[HashID].m_aKeys[i] == Key) return pHashlist[HashID].m_aIndex[i]; } - + return -1; } @@ -113,7 +113,7 @@ static int DiffItem(int *pPast, int *pCurrent, int *pOut, int Size) pCurrent++; Size--; } - + return Needed; } @@ -122,16 +122,16 @@ void CSnapshotDelta::UndiffItem(int *pPast, int *pDiff, int *pOut, int Size) while(Size) { *pOut = *pPast+*pDiff; - + if(*pDiff == 0) m_aSnapshotDataRate[m_SnapshotCurrent] += 1; else { unsigned char aBuf[16]; - unsigned char *pEnd = CVariableInt::Pack(aBuf, *pDiff); + unsigned char *pEnd = CVariableInt::Pack(aBuf, *pDiff); m_aSnapshotDataRate[m_SnapshotCurrent] += (int)(pEnd - (unsigned char*)aBuf) * 8; } - + pOut++; pPast++; pDiff++; @@ -169,11 +169,11 @@ int CSnapshotDelta::CreateDelta(CSnapshot *pFrom, CSnapshot *pTo, void *pDstData CSnapshotItem *pPastItem; int Count = 0; int SizeCount = 0; - + pDelta->m_NumDeletedItems = 0; pDelta->m_NumUpdateItems = 0; pDelta->m_NumTempItems = 0; - + CItemList Hashlist[HASHLIST_SIZE]; GenerateHash(Hashlist, pTo); @@ -189,7 +189,7 @@ int CSnapshotDelta::CreateDelta(CSnapshot *pFrom, CSnapshot *pTo, void *pDstData pData++; } } - + GenerateHash(Hashlist, pFrom); int aPastIndecies[1024]; @@ -197,29 +197,29 @@ int CSnapshotDelta::CreateDelta(CSnapshot *pFrom, CSnapshot *pTo, void *pDstData // we do this as a separate pass because it helps the cache for(i = 0; i < pTo->NumItems(); i++) { - pCurItem = pTo->GetItem(i); // O(1) .. O(n) + pCurItem = pTo->GetItem(i); // O(1) .. O(n) aPastIndecies[i] = GetItemIndexHashed(pCurItem->Key(), Hashlist); // O(n) .. O(n^n) } - + for(i = 0; i < pTo->NumItems(); i++) { // do delta ItemSize = pTo->GetItemSize(i); // O(1) .. O(n) - pCurItem = pTo->GetItem(i); // O(1) .. O(n) + pCurItem = pTo->GetItem(i); // O(1) .. O(n) PastIndex = aPastIndecies[i]; - + if(PastIndex != -1) { int *pItemDataDst = pData+3; - + pPastItem = pFrom->GetItem(PastIndex); - + if(m_aItemSizes[pCurItem->Type()]) pItemDataDst = pData+2; - + if(DiffItem((int*)pPastItem->Data(), (int*)pCurItem->Data(), pItemDataDst, ItemSize/4)) { - + *pData++ = pCurItem->Type(); *pData++ = pCurItem->ID(); if(!m_aItemSizes[pCurItem->Type()]) @@ -234,7 +234,7 @@ int CSnapshotDelta::CreateDelta(CSnapshot *pFrom, CSnapshot *pTo, void *pDstData *pData++ = pCurItem->ID(); if(!m_aItemSizes[pCurItem->Type()]) *pData++ = ItemSize/4; - + mem_copy(pData, pCurItem->Data(), ItemSize); SizeCount += ItemSize; pData += ItemSize/4; @@ -242,7 +242,7 @@ int CSnapshotDelta::CreateDelta(CSnapshot *pFrom, CSnapshot *pTo, void *pDstData Count++; } } - + if(0) { dbg_msg("snapshot", "%d %d %d", @@ -253,7 +253,7 @@ int CSnapshotDelta::CreateDelta(CSnapshot *pFrom, CSnapshot *pTo, void *pDstData /* // TODO: pack temp stuff - + // finish //mem_copy(pDelta->offsets, deleted, pDelta->num_deleted_items*sizeof(int)); //mem_copy(&(pDelta->offsets[pDelta->num_deleted_items]), update, pDelta->num_update_items*sizeof(int)); @@ -261,10 +261,10 @@ int CSnapshotDelta::CreateDelta(CSnapshot *pFrom, CSnapshot *pTo, void *pDstData //mem_copy(pDelta->data_start(), data, data_size); //pDelta->data_size = data_size; * */ - + if(!pDelta->m_NumDeletedItems && !pDelta->m_NumUpdateItems && !pDelta->m_NumTempItems) return 0; - + return (int)((char*)pData-(char*)pDstData); } @@ -281,16 +281,16 @@ int CSnapshotDelta::UnpackDelta(CSnapshot *pFrom, CSnapshot *pTo, void *pSrcData CData *pDelta = (CData *)pSrcData; int *pData = (int *)pDelta->m_pData; int *pEnd = (int *)(((char *)pSrcData + DataSize)); - + CSnapshotItem *pFromItem; int Keep, ItemSize; int *pDeleted; int ID, Type, Key; int FromIndex; int *pNewData; - + Builder.Init(); - + // unpack deleted stuff pDeleted = pData; pData += pDelta->m_NumDeletedItems; @@ -302,7 +302,7 @@ int CSnapshotDelta::UnpackDelta(CSnapshot *pFrom, CSnapshot *pTo, void *pSrcData { // dbg_assert(0, "fail!"); pFromItem = pFrom->GetItem(i); - ItemSize = pFrom->GetItemSize(i); + ItemSize = pFrom->GetItemSize(i); Keep = 1; for(int d = 0; d < pDelta->m_NumDeletedItems; d++) { @@ -312,7 +312,7 @@ int CSnapshotDelta::UnpackDelta(CSnapshot *pFrom, CSnapshot *pTo, void *pSrcData break; } } - + if(Keep) { // keep it @@ -321,13 +321,13 @@ int CSnapshotDelta::UnpackDelta(CSnapshot *pFrom, CSnapshot *pTo, void *pSrcData pFromItem->Data(), ItemSize); } } - + // unpack updated stuff for(int i = 0; i < pDelta->m_NumUpdateItems; i++) { if(pData+2 > pEnd) return -1; - + Type = *pData++; ID = *pData++; if(m_aItemSizes[Type]) @@ -339,18 +339,18 @@ int CSnapshotDelta::UnpackDelta(CSnapshot *pFrom, CSnapshot *pTo, void *pSrcData ItemSize = (*pData++) * 4; } m_SnapshotCurrent = Type; - + if(RangeCheck(pEnd, pData, ItemSize) || ItemSize < 0) return -3; - + Key = (Type<<16)|ID; - + // create the item if needed pNewData = Builder.GetItemData(Key); if(!pNewData) pNewData = (int *)Builder.NewItem(Key>>16, Key&0xffff, ItemSize); //if(range_check(pEnd, pNewData, ItemSize)) return -4; - + FromIndex = pFrom->GetItemIndex(Key); if(FromIndex != -1) { @@ -364,10 +364,10 @@ int CSnapshotDelta::UnpackDelta(CSnapshot *pFrom, CSnapshot *pTo, void *pSrcData m_aSnapshotDataRate[m_SnapshotCurrent] += ItemSize*8; m_aSnapshotDataUpdates[m_SnapshotCurrent]++; } - + pData += ItemSize/4; } - + // finish up return Builder.Finish(pTo); } @@ -402,24 +402,24 @@ void CSnapshotStorage::PurgeUntil(int Tick) { CHolder *pHolder = m_pFirst; CHolder *pNext; - + while(pHolder) { pNext = pHolder->m_pNext; if(pHolder->m_Tick >= Tick) return; // no more to remove mem_free(pHolder); - + // did we come to the end of the list? - if (!pNext) - break; + if (!pNext) + break; m_pFirst = pNext; pNext->m_pPrev = 0x0; - + pHolder = pNext; } - + // no more snapshots in storage m_pFirst = 0; m_pLast = 0; @@ -429,12 +429,12 @@ void CSnapshotStorage::Add(int Tick, int64 Tagtime, int DataSize, void *pData, i { // allocate memory for holder + snapshot_data int TotalSize = sizeof(CHolder)+DataSize; - + if(CreateAlt) TotalSize += DataSize; - + CHolder *pHolder = (CHolder *)mem_alloc(TotalSize, 1); - + // set data pHolder->m_Tick = Tick; pHolder->m_Tagtime = Tagtime; @@ -449,8 +449,8 @@ void CSnapshotStorage::Add(int Tick, int64 Tagtime, int DataSize, void *pData, i } else pHolder->m_pAltSnap = 0; - - + + // link pHolder->m_pNext = 0; pHolder->m_pPrev = m_pLast; @@ -464,7 +464,7 @@ void CSnapshotStorage::Add(int Tick, int64 Tagtime, int DataSize, void *pData, i int CSnapshotStorage::Get(int Tick, int64 *pTagtime, CSnapshot **ppData, CSnapshot **ppAltData) { CHolder *pHolder = m_pFirst; - + while(pHolder) { if(pHolder->m_Tick == Tick) @@ -477,10 +477,10 @@ int CSnapshotStorage::Get(int Tick, int64 *pTagtime, CSnapshot **ppData, CSnapsh *ppData = pHolder->m_pAltSnap; return pHolder->m_SnapSize; } - + pHolder = pHolder->m_pNext; } - + return -1; } @@ -492,7 +492,7 @@ void CSnapshotBuilder::Init() m_NumItems = 0; } -CSnapshotItem *CSnapshotBuilder::GetItem(int Index) +CSnapshotItem *CSnapshotBuilder::GetItem(int Index) { return (CSnapshotItem *)&(m_aData[m_aOffsets[Index]]); } diff --git a/src/engine/shared/snapshot.h b/src/engine/shared/snapshot.h index 34c3a548..ebd13f20 100644 --- a/src/engine/shared/snapshot.h +++ b/src/engine/shared/snapshot.h @@ -11,7 +11,7 @@ class CSnapshotItem { public: int m_TypeAndID; - + int *Data() { return (int *)(this+1); } int Type() { return m_TypeAndID>>16; } int ID() { return m_TypeAndID&0xffff; } @@ -90,15 +90,15 @@ public: public: CHolder *m_pPrev; CHolder *m_pNext; - + int64 m_Tagtime; int m_Tick; - + int m_SnapSize; CSnapshot *m_pSnap; CSnapshot *m_pAltSnap; }; - + CHolder *m_pFirst; CHolder *m_pLast; @@ -125,12 +125,12 @@ class CSnapshotBuilder public: void Init(); - + void *NewItem(int Type, int ID, int Size); - + CSnapshotItem *GetItem(int Index); int *GetItemData(int Key); - + int Finish(void *Snapdata); }; diff --git a/src/engine/shared/storage.cpp b/src/engine/shared/storage.cpp index db19fcdc..d6f83dc8 100644 --- a/src/engine/shared/storage.cpp +++ b/src/engine/shared/storage.cpp @@ -21,7 +21,7 @@ public: char m_aDatadir[MAX_PATH_LENGTH]; char m_aUserdir[MAX_PATH_LENGTH]; char m_aCurrentdir[MAX_PATH_LENGTH]; - + CStorage() { mem_zero(m_aaStoragePaths, sizeof(m_aaStoragePaths)); @@ -29,7 +29,7 @@ public: m_aDatadir[0] = 0; m_aUserdir[0] = 0; } - + int Init(const char *pApplicationName, int NumArgs, const char **ppArguments) { // get userdir @@ -85,7 +85,7 @@ public: str_append(aBuffer, "/storage.cfg", sizeof(aBuffer)); File = io_open(aBuffer, IOFLAG_READ); } - + if(Pos >= MAX_PATH_LENGTH || !File) { dbg_msg("storage", "couldn't open storage.cfg"); @@ -151,7 +151,7 @@ public: } } } - + void FindDatadir(const char *pArgv0) { // 1) use data-dir in PWD if present @@ -160,35 +160,35 @@ public: str_copy(m_aDatadir, "data", sizeof(m_aDatadir)); return; } - + // 2) use compiled-in data-dir if present if(fs_is_dir(DATA_DIR "/mapres")) { str_copy(m_aDatadir, DATA_DIR, sizeof(m_aDatadir)); return; } - + // 3) check for usable path in argv[0] { unsigned int Pos = ~0U; for(unsigned i = 0; pArgv0[i]; i++) if(pArgv0[i] == '/' || pArgv0[i] == '\\') Pos = i; - + if(Pos < MAX_PATH_LENGTH) { char aBaseDir[MAX_PATH_LENGTH]; str_copy(aBaseDir, pArgv0, Pos+1); str_format(m_aDatadir, sizeof(m_aDatadir), "%s/data", aBaseDir); str_append(aBaseDir, "/data/mapres", sizeof(aBaseDir)); - + if(fs_is_dir(aBaseDir)) return; else m_aDatadir[0] = 0; } } - + #if defined(CONF_FAMILY_UNIX) // 4) check for all default locations { @@ -200,7 +200,7 @@ public: "/opt/teeworlds/data" }; const int DirsCount = sizeof(aDirs) / sizeof(aDirs[0]); - + int i; for (i = 0; i < DirsCount; i++) { @@ -214,7 +214,7 @@ public: } } #endif - + // no data-dir found dbg_msg("storage", "warning no data directory found"); } @@ -240,7 +240,7 @@ public: str_format(pBuffer, BufferSize, "%s%s%s", m_aaStoragePaths[Type], !m_aaStoragePaths[Type][0] ? "" : "/", pDir); return pBuffer; } - + virtual IOHANDLE OpenFile(const char *pFilename, int Flags, int Type, char *pBuffer = 0, int BufferSize = 0) { char aBuffer[MAX_PATH_LENGTH]; @@ -249,7 +249,7 @@ public: pBuffer = aBuffer; BufferSize = sizeof(aBuffer); } - + if(Flags&IOFLAG_WRITE) { return io_open(GetPath(TYPE_SAVE, pFilename, pBuffer, BufferSize), Flags); @@ -276,11 +276,11 @@ public: return Handle; } } - + pBuffer[0] = 0; - return 0; + return 0; } - + struct CFindCBData { CStorage *pStorage; @@ -321,7 +321,7 @@ public: { if(BufferSize < 1) return false; - + pBuffer[0] = 0; char aBuf[MAX_PATH_LENGTH]; CFindCBData Data; diff --git a/src/engine/storage.h b/src/engine/storage.h index e0cab12f..1fd48f6a 100644 --- a/src/engine/storage.h +++ b/src/engine/storage.h @@ -14,7 +14,7 @@ public: TYPE_SAVE = 0, TYPE_ALL = -1 }; - + virtual void ListDirectory(int Type, const char *pPath, FS_LISTDIR_CALLBACK pfnCallback, void *pUser) = 0; virtual IOHANDLE OpenFile(const char *pFilename, int Flags, int Type, char *pBuffer = 0, int BufferSize = 0) = 0; virtual bool FindFile(const char *pFilename, const char *pPath, int Type, char *pBuffer, int BufferSize) = 0; diff --git a/src/engine/textrender.h b/src/engine/textrender.h index 8d13f605..ddd2be5b 100644 --- a/src/engine/textrender.h +++ b/src/engine/textrender.h @@ -20,12 +20,12 @@ public: int m_LineCount; int m_CharCount; int m_MaxLines; - + float m_StartX; float m_StartY; float m_LineWidth; float m_X, m_Y; - + CFont *m_pFont; float m_FontSize; }; @@ -35,15 +35,15 @@ class ITextRender : public IInterface MACRO_INTERFACE("textrender", 0) public: virtual void SetCursor(CTextCursor *pCursor, float x, float y, float FontSize, int Flags) = 0; - + virtual CFont *LoadFont(const char *pFilename) = 0; virtual void DestroyFont(CFont *pFont) = 0; - + virtual void SetDefaultFont(CFont *pFont) = 0; // virtual void TextEx(CTextCursor *pCursor, const char *pText, int Length) = 0; - + // old foolish interface virtual void TextColor(float r, float g, float b, float a) = 0; virtual void TextOutlineColor(float r, float g, float b, float a) = 0; diff --git a/src/game/client/animstate.cpp b/src/game/client/animstate.cpp index 096ff63c..1289126b 100644 --- a/src/game/client/animstate.cpp +++ b/src/game/client/animstate.cpp @@ -84,13 +84,13 @@ CAnimState *CAnimState::GetIdle() { static CAnimState State; static bool Init = true; - + if(Init) { State.Set(&g_pData->m_aAnimations[ANIM_BASE], 0); State.Add(&g_pData->m_aAnimations[ANIM_IDLE], 0, 1.0f); Init = false; } - + return &State; } diff --git a/src/game/client/animstate.h b/src/game/client/animstate.h index cb3b0e18..63b6a80a 100644 --- a/src/game/client/animstate.h +++ b/src/game/client/animstate.h @@ -17,7 +17,7 @@ public: ANIM_KEYFRAME *GetAttach() { return &m_Attach; }; void Set(ANIMATION *pAnim, float Time); void Add(ANIMATION *pAdded, float Time, float Amount); - + static CAnimState *GetIdle(); }; diff --git a/src/game/client/component.h b/src/game/client/component.h index 244f5daf..858b456f 100644 --- a/src/game/client/component.h +++ b/src/game/client/component.h @@ -12,7 +12,7 @@ protected: friend class CGameClient; CGameClient *m_pClient; - + // perhaps propagte pointers for these as well class IKernel *Kernel() const { return m_pClient->Kernel(); } class IGraphics *Graphics() const { return m_pClient->Graphics(); } @@ -31,7 +31,7 @@ protected: class CCollision *Collision() const { return m_pClient->Collision(); } public: virtual ~CComponent() {} - + virtual void OnStateChange(int NewState, int OldState) {}; virtual void OnConsoleInit() {}; virtual void OnInit() {}; diff --git a/src/game/client/components/binds.cpp b/src/game/client/components/binds.cpp index 1632b26f..3feba98e 100644 --- a/src/game/client/components/binds.cpp +++ b/src/game/client/components/binds.cpp @@ -12,11 +12,11 @@ bool CBinds::CBindsSpecial::OnInput(IInput::CEvent Event) int Stroke = 0; if(Event.m_Flags&IInput::FLAG_PRESS) Stroke = 1; - + m_pBinds->GetConsole()->ExecuteLineStroked(Stroke, m_pBinds->m_aaKeyBindings[Event.m_Key]); return true; } - + return false; } @@ -30,7 +30,7 @@ void CBinds::Bind(int KeyID, const char *pStr) { if(KeyID < 0 || KeyID >= KEY_LAST) return; - + str_copy(m_aaKeyBindings[KeyID], pStr, sizeof(m_aaKeyBindings[KeyID])); char aBuf[256]; if(!m_aaKeyBindings[KeyID][0]) @@ -74,11 +74,11 @@ const char *CBinds::GetKey(const char *pBindStr) const char *pBind = Get(KeyId); if(!pBind[0]) continue; - + if(str_comp(pBind, pBindStr) == 0) return Input()->KeyName(KeyId); } - + return ""; } @@ -108,15 +108,15 @@ void CBinds::SetDefaults() Bind('3', "+weapon3"); Bind('4', "+weapon4"); Bind('5', "+weapon5"); - + Bind(KEY_MOUSE_WHEEL_UP, "+prevweapon"); Bind(KEY_MOUSE_WHEEL_DOWN, "+nextweapon"); - + Bind('t', "chat all"); - Bind('y', "chat team"); + Bind('y', "chat team"); Bind(KEY_F3, "vote yes"); - Bind(KEY_F4, "vote no"); + Bind(KEY_F4, "vote no"); } void CBinds::OnConsoleInit() @@ -125,12 +125,12 @@ void CBinds::OnConsoleInit() IConfig *pConfig = Kernel()->RequestInterface<IConfig>(); if(pConfig) pConfig->RegisterCallback(ConfigSaveCallback, this); - + Console()->Register("bind", "sr", CFGFLAG_CLIENT, ConBind, this, "Bind key to execute the command"); Console()->Register("unbind", "s", CFGFLAG_CLIENT, ConUnbind, this, "Unbind key"); Console()->Register("unbindall", "", CFGFLAG_CLIENT, ConUnbindAll, this, "Unbind all keys"); Console()->Register("dump_binds", "", CFGFLAG_CLIENT, ConDumpBinds, this, "Dump binds"); - + // default bindings SetDefaults(); } @@ -140,7 +140,7 @@ void CBinds::ConBind(IConsole::IResult *pResult, void *pUserData) CBinds *pBinds = (CBinds *)pUserData; const char *pKeyName = pResult->GetString(0); int id = pBinds->GetKeyID(pKeyName); - + if(!id) { char aBuf[256]; @@ -148,7 +148,7 @@ void CBinds::ConBind(IConsole::IResult *pResult, void *pUserData) pBinds->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "binds", aBuf); return; } - + pBinds->Bind(id, pResult->GetString(1)); } @@ -158,7 +158,7 @@ void CBinds::ConUnbind(IConsole::IResult *pResult, void *pUserData) CBinds *pBinds = (CBinds *)pUserData; const char *pKeyName = pResult->GetString(0); int id = pBinds->GetKeyID(pKeyName); - + if(!id) { char aBuf[256]; @@ -166,7 +166,7 @@ void CBinds::ConUnbind(IConsole::IResult *pResult, void *pUserData) pBinds->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "binds", aBuf); return; } - + pBinds->Bind(id, ""); } @@ -200,21 +200,21 @@ int CBinds::GetKeyID(const char *pKeyName) if(i > 0 && i < KEY_LAST) return i; // numeric } - + // search for key for(int i = 0; i < KEY_LAST; i++) { if(str_comp(pKeyName, Input()->KeyName(i)) == 0) return i; } - + return 0; } void CBinds::ConfigSaveCallback(IConfig *pConfig, void *pUserData) { CBinds *pSelf = (CBinds *)pUserData; - + char aBuffer[256]; char *pEnd = aBuffer+sizeof(aBuffer)-8; pConfig->WriteLine("unbindall"); @@ -223,7 +223,7 @@ void CBinds::ConfigSaveCallback(IConfig *pConfig, void *pUserData) if(pSelf->m_aaKeyBindings[i][0] == 0) continue; str_format(aBuffer, sizeof(aBuffer), "bind %s ", pSelf->Input()->KeyName(i)); - + // process the string. we need to escape some characters const char *pSrc = pSelf->m_aaKeyBindings[i]; char *pDst = aBuffer + str_length(aBuffer); @@ -236,7 +236,7 @@ void CBinds::ConfigSaveCallback(IConfig *pConfig, void *pUserData) } *pDst++ = '"'; *pDst++ = 0; - + pConfig->WriteLine(aBuffer); } } diff --git a/src/game/client/components/binds.h b/src/game/client/components/binds.h index ad51a47c..7812242c 100644 --- a/src/game/client/components/binds.h +++ b/src/game/client/components/binds.h @@ -16,27 +16,27 @@ class CBinds : public CComponent static void ConUnbindAll(IConsole::IResult *pResult, void *pUserData); static void ConDumpBinds(IConsole::IResult *pResult, void *pUserData); class IConsole *GetConsole() const { return Console(); } - + static void ConfigSaveCallback(class IConfig *pConfig, void *pUserData); - + public: CBinds(); - + class CBindsSpecial : public CComponent { public: CBinds *m_pBinds; virtual bool OnInput(IInput::CEvent Event); }; - + CBindsSpecial m_SpecialBinds; - + void Bind(int KeyID, const char *pStr); void SetDefaults(); void UnbindAll(); const char *Get(int KeyID); const char *GetKey(const char *pBindStr); - + virtual void OnConsoleInit(); virtual bool OnInput(IInput::CEvent Event); }; diff --git a/src/game/client/components/broadcast.cpp b/src/game/client/components/broadcast.cpp index 17b2d66b..ccf49bf6 100644 --- a/src/game/client/components/broadcast.cpp +++ b/src/game/client/components/broadcast.cpp @@ -12,7 +12,7 @@ #include <game/client/components/scoreboard.h> #include "broadcast.h" - + void CBroadcast::OnReset() { m_BroadcastTime = 0; @@ -24,7 +24,7 @@ void CBroadcast::OnRender() return; Graphics()->MapScreen(0, 0, 300*Graphics()->ScreenAspect(), 300); - + if(time_get() < m_BroadcastTime) { CTextCursor Cursor; diff --git a/src/game/client/components/camera.cpp b/src/game/client/components/camera.cpp index f02b2861..5a8dc8c8 100644 --- a/src/game/client/components/camera.cpp +++ b/src/game/client/components/camera.cpp @@ -20,7 +20,7 @@ void CCamera::OnRender() //vec2 center; m_Zoom = 1.0f; - // update camera center + // update camera center if(m_pClient->m_Snap.m_SpecInfo.m_Active && !m_pClient->m_Snap.m_SpecInfo.m_UsePosition) { if(m_CamType != CAMTYPE_SPEC) @@ -50,7 +50,7 @@ void CCamera::OnRender() CameraOffset = normalize(m_pClient->m_pControls->m_MousePos)*OffsetAmount; } - + if(m_pClient->m_Snap.m_SpecInfo.m_Active) m_Center = m_pClient->m_Snap.m_SpecInfo.m_Position + CameraOffset; else diff --git a/src/game/client/components/chat.cpp b/src/game/client/components/chat.cpp index 19264194..ee294dc4 100644 --- a/src/game/client/components/chat.cpp +++ b/src/game/client/components/chat.cpp @@ -32,7 +32,7 @@ void CChat::OnReset() m_aLines[i].m_aText[0] = 0; m_aLines[i].m_aName[0] = 0; } - + m_Show = false; m_InputUpdate = false; m_ChatStringOffset = 0; @@ -126,7 +126,7 @@ bool CChat::OnInput(IInput::CEvent Event) for(m_PlaceholderLength = 0; *pCursor && *pCursor != ' '; ++pCursor) ++m_PlaceholderLength; - + str_copy(m_aCompletionBuffer, m_Input.GetString()+m_PlaceholderOffset, min(static_cast<int>(sizeof(m_aCompletionBuffer)), m_PlaceholderLength+1)); } @@ -204,7 +204,7 @@ bool CChat::OnInput(IInput::CEvent Event) else m_Input.Clear(); } - + return true; } @@ -220,7 +220,7 @@ void CChat::EnableMode(int Team) m_Mode = MODE_TEAM; else m_Mode = MODE_ALL; - + m_Input.Clear(); Input()->ClearEvents(); m_CompletionChosen = -1; @@ -241,7 +241,7 @@ void CChat::AddLine(int ClientID, int Team, const char *pLine) if(ClientID != -1 && (m_pClient->m_aClients[ClientID].m_aName[0] == '\0' || // unknown client m_pClient->m_aClients[ClientID].m_ChatIgnore)) return; - + bool Highlighted = false; char *p = const_cast<char*>(pLine); while(*p) @@ -285,11 +285,11 @@ void CChat::AddLine(int ClientID, int Team, const char *pLine) else if(m_pClient->m_aClients[ClientID].m_Team == TEAM_BLUE) m_aLines[m_CurrentLine].m_NameColor = TEAM_BLUE; } - + str_copy(m_aLines[m_CurrentLine].m_aName, m_pClient->m_aClients[ClientID].m_aName, sizeof(m_aLines[m_CurrentLine].m_aName)); str_format(m_aLines[m_CurrentLine].m_aText, sizeof(m_aLines[m_CurrentLine].m_aText), ": %s", pLine); } - + char aBuf[1024]; str_format(aBuf, sizeof(aBuf), "%s%s", m_aLines[m_CurrentLine].m_aName, m_aLines[m_CurrentLine].m_aText); Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "chat", aBuf); @@ -317,7 +317,7 @@ void CChat::OnRender() TextRender()->SetCursor(&Cursor, x, y, 8.0f, TEXTFLAG_RENDER); Cursor.m_LineWidth = Width-190.0f; Cursor.m_MaxLines = 2; - + if(m_Mode == MODE_ALL) TextRender()->TextEx(&Cursor, Localize("All"), -1); else if(m_Mode == MODE_TEAM) @@ -326,7 +326,7 @@ void CChat::OnRender() TextRender()->TextEx(&Cursor, Localize("Chat"), -1); TextRender()->TextEx(&Cursor, ": ", -1); - + // check if the visible text has to be moved if(m_InputUpdate) { @@ -373,7 +373,7 @@ void CChat::OnRender() int r = ((m_CurrentLine-i)+MAX_LINES)%MAX_LINES; if(Now > m_aLines[r].m_Time+16*time_freq() && !m_Show) break; - + // get the y offset (calculate it if we haven't done that yet) if(m_aLines[r].m_YOffset[OffsetType] < 0.0f) { @@ -388,7 +388,7 @@ void CChat::OnRender() // cut off if msgs waste too much space if(y < HeightLimit) break; - + float Blend = Now > m_aLines[r].m_Time+14*time_freq() && !m_Show ? 1.0f-(Now-m_aLines[r].m_Time-14*time_freq())/(2.0f*time_freq()) : 1.0f; // reset the cursor @@ -408,7 +408,7 @@ void CChat::OnRender() TextRender()->TextColor(0.75f, 0.5f, 0.75f, Blend); // spectator else TextRender()->TextColor(0.8f, 0.8f, 0.8f, Blend); - + TextRender()->TextEx(&Cursor, m_aLines[r].m_aName, -1); // render line diff --git a/src/game/client/components/chat.h b/src/game/client/components/chat.h index bb68d7be..60e18387 100644 --- a/src/game/client/components/chat.h +++ b/src/game/client/components/chat.h @@ -9,8 +9,8 @@ class CChat : public CComponent { CLineInput m_Input; - - enum + + enum { MAX_LINES = 25, }; @@ -49,23 +49,23 @@ class CChat : public CComponent int m_PlaceholderLength; char *m_pHistoryEntry; TStaticRingBuffer<char, 64*1024, CRingBufferBase::FLAG_RECYCLE> m_History; - + static void ConSay(IConsole::IResult *pResult, void *pUserData); static void ConSayTeam(IConsole::IResult *pResult, void *pUserData); static void ConChat(IConsole::IResult *pResult, void *pUserData); static void ConShowChat(IConsole::IResult *pResult, void *pUserData); - + public: CChat(); bool IsActive() const { return m_Mode != MODE_NONE; } - + void AddLine(int ClientID, int Team, const char *pLine); - + void EnableMode(int Team); - + void Say(int Team, const char *pLine); - + virtual void OnReset(); virtual void OnConsoleInit(); virtual void OnStateChange(int NewState, int OldState); diff --git a/src/game/client/components/console.cpp b/src/game/client/components/console.cpp index a7da3075..33c6db43 100644 --- a/src/game/client/components/console.cpp +++ b/src/game/client/components/console.cpp @@ -39,9 +39,9 @@ enum CGameConsole::CInstance::CInstance(int Type) { m_pHistoryEntry = 0x0; - + m_Type = Type; - + if(Type == CGameConsole::CONSOLETYPE_LOCAL) m_CompletionFlagmask = CFGFLAG_CLIENT; else @@ -50,7 +50,7 @@ CGameConsole::CInstance::CInstance(int Type) m_aCompletionBuffer[0] = 0; m_CompletionChosen = -1; m_CompletionRenderOffset = 0.0f; - + m_pCommand = 0x0; } @@ -95,7 +95,7 @@ void CGameConsole::CInstance::PossibleCommandsCompleteCallback(const char *pStr, void CGameConsole::CInstance::OnInput(IInput::CEvent Event) { bool Handled = false; - + if(Event.m_Flags&IInput::FLAG_PRESS) { if(Event.m_Key == KEY_RETURN || Event.m_Key == KEY_KP_ENTER) @@ -111,7 +111,7 @@ void CGameConsole::CInstance::OnInput(IInput::CEvent Event) m_Input.Clear(); m_pHistoryEntry = 0x0; } - + Handled = true; } else if (Event.m_Key == KEY_UP) @@ -197,7 +197,7 @@ void CGameConsole::CInstance::OnInput(IInput::CEvent Event) for(; i < (int)sizeof(aBuf)-1 && *pSrc && *pSrc != ' '; i++, pSrc++) aBuf[i] = *pSrc; aBuf[i] = 0; - + m_pCommand = m_pGameConsole->m_pConsole->GetCommandInfo(aBuf, m_CompletionFlagmask); } } @@ -233,9 +233,9 @@ float CGameConsole::TimeNow() CGameConsole::CInstance *CGameConsole::CurrentConsole() { - if(m_ConsoleType == CONSOLETYPE_REMOTE) - return &m_RemoteConsole; - return &m_LocalConsole; + if(m_ConsoleType == CONSOLETYPE_REMOTE) + return &m_RemoteConsole; + return &m_LocalConsole; } void CGameConsole::OnReset() @@ -263,7 +263,7 @@ struct CRenderInfo void CGameConsole::PossibleCommandsRenderCallback(const char *pStr, void *pUser) { CRenderInfo *pInfo = static_cast<CRenderInfo *>(pUser); - + if(pInfo->m_EnumCount == pInfo->m_WantedCompletion) { float tw = pInfo->m_pSelf->TextRender()->TextWidth(pInfo->m_Cursor.m_pFont, pInfo->m_Cursor.m_FontSize, pStr, -1); @@ -272,7 +272,7 @@ void CGameConsole::PossibleCommandsRenderCallback(const char *pStr, void *pUser) pInfo->m_pSelf->Graphics()->SetColor(229.0f/255.0f,185.0f/255.0f,4.0f/255.0f,0.85f); pInfo->m_pSelf->RenderTools()->DrawRoundRect(pInfo->m_Cursor.m_X-3, pInfo->m_Cursor.m_Y, tw+5, pInfo->m_Cursor.m_FontSize+4, pInfo->m_Cursor.m_FontSize/3); pInfo->m_pSelf->Graphics()->QuadsEnd(); - + // scroll when out of sight if(pInfo->m_Cursor.m_X < 3.0f) pInfo->m_Offset = 0.0f; @@ -285,7 +285,7 @@ void CGameConsole::PossibleCommandsRenderCallback(const char *pStr, void *pUser) else { const char *pMatchStart = str_find_nocase(pStr, pInfo->m_pCurrentCmd); - + if(pMatchStart) { pInfo->m_pSelf->TextRender()->TextColor(0.5f,0.5f,0.5f,1); @@ -301,14 +301,14 @@ void CGameConsole::PossibleCommandsRenderCallback(const char *pStr, void *pUser) pInfo->m_pSelf->TextRender()->TextEx(&pInfo->m_Cursor, pStr, -1); } } - + pInfo->m_EnumCount++; pInfo->m_Cursor.m_X += 7.0f; } void CGameConsole::OnRender() { - CUIRect Screen = *UI()->Screen(); + CUIRect Screen = *UI()->Screen(); float ConsoleMaxHeight = Screen.h*3/5.0f; float ConsoleHeight; @@ -325,11 +325,11 @@ void CGameConsole::OnRender() } if (m_ConsoleState == CONSOLE_OPEN && g_Config.m_ClEditor) - Toggle(CONSOLETYPE_LOCAL); - + Toggle(CONSOLETYPE_LOCAL); + if (m_ConsoleState == CONSOLE_CLOSED) return; - + if (m_ConsoleState == CONSOLE_OPEN) Input()->MouseModeAbsolute(); @@ -348,31 +348,31 @@ void CGameConsole::OnRender() // do console shadow Graphics()->TextureSet(-1); - Graphics()->QuadsBegin(); + Graphics()->QuadsBegin(); IGraphics::CColorVertex Array[4] = { - IGraphics::CColorVertex(0, 0,0,0, 0.5f), - IGraphics::CColorVertex(1, 0,0,0, 0.5f), - IGraphics::CColorVertex(2, 0,0,0, 0.0f), + IGraphics::CColorVertex(0, 0,0,0, 0.5f), + IGraphics::CColorVertex(1, 0,0,0, 0.5f), + IGraphics::CColorVertex(2, 0,0,0, 0.0f), IGraphics::CColorVertex(3, 0,0,0, 0.0f)}; Graphics()->SetColorVertex(Array, 4); IGraphics::CQuadItem QuadItem(0, ConsoleHeight, Screen.w, 10.0f); Graphics()->QuadsDrawTL(&QuadItem, 1); - Graphics()->QuadsEnd(); + Graphics()->QuadsEnd(); // do background Graphics()->TextureSet(g_pData->m_aImages[IMAGE_CONSOLE_BG].m_Id); - Graphics()->QuadsBegin(); - Graphics()->SetColor(0.2f, 0.2f, 0.2f,0.9f); - if(m_ConsoleType == CONSOLETYPE_REMOTE) - Graphics()->SetColor(0.4f, 0.2f, 0.2f,0.9f); - Graphics()->QuadsSetSubset(0,-ConsoleHeight*0.075f,Screen.w*0.075f*0.5f,0); + Graphics()->QuadsBegin(); + Graphics()->SetColor(0.2f, 0.2f, 0.2f,0.9f); + if(m_ConsoleType == CONSOLETYPE_REMOTE) + Graphics()->SetColor(0.4f, 0.2f, 0.2f,0.9f); + Graphics()->QuadsSetSubset(0,-ConsoleHeight*0.075f,Screen.w*0.075f*0.5f,0); QuadItem = IGraphics::CQuadItem(0, 0, Screen.w, ConsoleHeight); Graphics()->QuadsDrawTL(&QuadItem, 1); - Graphics()->QuadsEnd(); + Graphics()->QuadsEnd(); // do small bar shadow Graphics()->TextureSet(-1); - Graphics()->QuadsBegin(); + Graphics()->QuadsBegin(); Array[0] = IGraphics::CColorVertex(0, 0,0,0, 0.0f); Array[1] = IGraphics::CColorVertex(1, 0,0,0, 0.0f); Array[2] = IGraphics::CColorVertex(2, 0,0,0, 0.25f); @@ -380,20 +380,20 @@ void CGameConsole::OnRender() Graphics()->SetColorVertex(Array, 4); QuadItem = IGraphics::CQuadItem(0, ConsoleHeight-20, Screen.w, 10); Graphics()->QuadsDrawTL(&QuadItem, 1); - Graphics()->QuadsEnd(); + Graphics()->QuadsEnd(); // do the lower bar Graphics()->TextureSet(g_pData->m_aImages[IMAGE_CONSOLE_BAR].m_Id); - Graphics()->QuadsBegin(); - Graphics()->SetColor(1.0f, 1.0f, 1.0f, 0.9f); - Graphics()->QuadsSetSubset(0,0.1f,Screen.w*0.015f,1-0.1f); + Graphics()->QuadsBegin(); + Graphics()->SetColor(1.0f, 1.0f, 1.0f, 0.9f); + Graphics()->QuadsSetSubset(0,0.1f,Screen.w*0.015f,1-0.1f); QuadItem = IGraphics::CQuadItem(0,ConsoleHeight-10.0f,Screen.w,10.0f); Graphics()->QuadsDrawTL(&QuadItem, 1); - Graphics()->QuadsEnd(); - - ConsoleHeight -= 22.0f; - - CInstance *pConsole = CurrentConsole(); + Graphics()->QuadsEnd(); + + ConsoleHeight -= 22.0f; + + CInstance *pConsole = CurrentConsole(); { float FontSize = 10.0f; @@ -410,7 +410,7 @@ void CGameConsole::OnRender() Info.m_pCurrentCmd = pConsole->m_aCompletionBuffer; TextRender()->SetCursor(&Info.m_Cursor, x+Info.m_Offset, y+RowHeight+2.0f, FontSize, TEXTFLAG_RENDER); - // render prompt + // render prompt CTextCursor Cursor; TextRender()->SetCursor(&Cursor, x, y, FontSize, TEXTFLAG_RENDER); const char *pPrompt = "> "; @@ -427,7 +427,7 @@ void CGameConsole::OnRender() pPrompt = "NOT CONNECTED> "; } TextRender()->TextEx(&Cursor, pPrompt, -1); - + x = Cursor.m_X; // render console input (wrap line) @@ -435,7 +435,7 @@ void CGameConsole::OnRender() y -= (Lines - 1) * FontSize; TextRender()->SetCursor(&Cursor, x, y, FontSize, TEXTFLAG_RENDER); Cursor.m_LineWidth = Screen.w - 10.0f - x; - + //hide rcon password char aInputString[256]; str_copy(aInputString, pConsole->m_Input.GetString(), sizeof(aInputString)); @@ -444,12 +444,12 @@ void CGameConsole::OnRender() for(int i = 0; i < pConsole->m_Input.GetLength(); ++i) aInputString[i] = '*'; } - + TextRender()->TextEx(&Cursor, aInputString, pConsole->m_Input.GetCursorOffset()); CTextCursor Marker = Cursor; TextRender()->TextEx(&Marker, "|", -1); TextRender()->TextEx(&Cursor, aInputString+pConsole->m_Input.GetCursorOffset(), -1); - + // render possible commands if(m_ConsoleType == CONSOLETYPE_LOCAL || Client()->RconAuthed()) { @@ -457,12 +457,12 @@ void CGameConsole::OnRender() { m_pConsole->PossibleCommands(pConsole->m_aCompletionBuffer, pConsole->m_CompletionFlagmask, PossibleCommandsRenderCallback, &Info); pConsole->m_CompletionRenderOffset = Info.m_Offset; - + if(Info.m_EnumCount <= 0) { if(pConsole->m_pCommand) { - + char aBuf[512]; str_format(aBuf, sizeof(aBuf), "Help: %s ", pConsole->m_pCommand->m_pHelp); TextRender()->TextEx(&Info.m_Cursor, aBuf, -1); @@ -492,7 +492,7 @@ void CGameConsole::OnRender() pEntry->m_YOffset = Cursor.m_Y+Cursor.m_FontSize+LineOffset; } OffsetY += pEntry->m_YOffset; - + // next page when lines reach the top if(y-OffsetY <= RowHeight) break; @@ -533,7 +533,7 @@ void CGameConsole::OnRender() str_format(aBuf, sizeof(aBuf), "v%s", GAME_VERSION); float Width = TextRender()->TextWidth(0, FontSize, aBuf, -1); TextRender()->Text(0, Screen.w-Width-10.0f, 0.0f, FontSize, aBuf, -1); - } + } } void CGameConsole::OnMessage(int MsgType, void *pRawMsg) @@ -551,7 +551,7 @@ bool CGameConsole::OnInput(IInput::CEvent Event) Toggle(m_ConsoleType); else CurrentConsole()->OnInput(Event); - + return true; } @@ -562,7 +562,7 @@ void CGameConsole::Toggle(int Type) // don't toggle console, just switch what console to use } else - { + { if (m_ConsoleState == CONSOLE_CLOSED || m_ConsoleState == CONSOLE_OPEN) { m_StateChangeEnd = TimeNow()+m_StateChangeDuration; @@ -671,10 +671,10 @@ void CGameConsole::OnConsoleInit() m_RemoteConsole.Init(this); m_pConsole = Kernel()->RequestInterface<IConsole>(); - + // Console()->RegisterPrintCallback(ClientConsolePrintCallback, this); - + Console()->Register("toggle_local_console", "", CFGFLAG_CLIENT, ConToggleLocalConsole, this, "Toggle local console"); Console()->Register("toggle_remote_console", "", CFGFLAG_CLIENT, ConToggleRemoteConsole, this, "Toggle remote console"); Console()->Register("clear_local_console", "", CFGFLAG_CLIENT, ConClearLocalConsole, this, "Clear local console"); diff --git a/src/game/client/components/console.h b/src/game/client/components/console.h index 2739724b..003a9423 100644 --- a/src/game/client/components/console.h +++ b/src/game/client/components/console.h @@ -24,15 +24,15 @@ class CGameConsole : public CComponent int m_Type; int m_CompletionEnumerationCount; int m_BacklogActPage; - + public: CGameConsole *m_pGameConsole; - + char m_aCompletionBuffer[128]; int m_CompletionChosen; int m_CompletionFlagmask; float m_CompletionRenderOffset; - + IConsole::CCommandInfo *m_pCommand; CInstance(int t); @@ -42,22 +42,22 @@ class CGameConsole : public CComponent void ClearHistory(); void ExecuteLine(const char *pLine); - + void OnInput(IInput::CEvent Event); void PrintLine(const char *pLine); - + const char *GetString() const { return m_Input.GetString(); } static void PossibleCommandsCompleteCallback(const char *pStr, void *pUser); }; - + class IConsole *m_pConsole; - + CInstance m_LocalConsole; CInstance m_RemoteConsole; - + CInstance *CurrentConsole(); float TimeNow(); - + int m_ConsoleType; int m_ConsoleState; float m_StateChangeEnd; @@ -74,7 +74,7 @@ class CGameConsole : public CComponent static void ConClearRemoteConsole(IConsole::IResult *pResult, void *pUserData); static void ConDumpLocalConsole(IConsole::IResult *pResult, void *pUserData); static void ConDumpRemoteConsole(IConsole::IResult *pResult, void *pUserData); - + public: enum { diff --git a/src/game/client/components/controls.cpp b/src/game/client/components/controls.cpp index 56b6e63b..81c4d5ae 100644 --- a/src/game/client/components/controls.cpp +++ b/src/game/client/components/controls.cpp @@ -28,7 +28,7 @@ void CControls::OnReset() m_LastData.m_Fire &= INPUT_STATE_MASK; m_LastData.m_Jump = 0; m_InputData = m_LastData; - + m_InputDirectionLeft = 0; m_InputDirectionRight = 0; } @@ -86,31 +86,31 @@ void CControls::OnConsoleInit() Console()->Register("+hook", "", CFGFLAG_CLIENT, ConKeyInputState, &m_InputData.m_Hook, "Hook"); Console()->Register("+fire", "", CFGFLAG_CLIENT, ConKeyInputCounter, &m_InputData.m_Fire, "Fire"); - { static CInputSet s_Set = {this, &m_InputData.m_WantedWeapon, 1}; Console()->Register("+weapon1", "", CFGFLAG_CLIENT, ConKeyInputSet, (void *)&s_Set, "Switch to hammer"); } - { static CInputSet s_Set = {this, &m_InputData.m_WantedWeapon, 2}; Console()->Register("+weapon2", "", CFGFLAG_CLIENT, ConKeyInputSet, (void *)&s_Set, "Switch to gun"); } - { static CInputSet s_Set = {this, &m_InputData.m_WantedWeapon, 3}; Console()->Register("+weapon3", "", CFGFLAG_CLIENT, ConKeyInputSet, (void *)&s_Set, "Switch to shotgun"); } - { static CInputSet s_Set = {this, &m_InputData.m_WantedWeapon, 4}; Console()->Register("+weapon4", "", CFGFLAG_CLIENT, ConKeyInputSet, (void *)&s_Set, "Switch to grenade"); } - { static CInputSet s_Set = {this, &m_InputData.m_WantedWeapon, 5}; Console()->Register("+weapon5", "", CFGFLAG_CLIENT, ConKeyInputSet, (void *)&s_Set, "Switch to rifle"); } + { static CInputSet s_Set = {this, &m_InputData.m_WantedWeapon, 1}; Console()->Register("+weapon1", "", CFGFLAG_CLIENT, ConKeyInputSet, (void *)&s_Set, "Switch to hammer"); } + { static CInputSet s_Set = {this, &m_InputData.m_WantedWeapon, 2}; Console()->Register("+weapon2", "", CFGFLAG_CLIENT, ConKeyInputSet, (void *)&s_Set, "Switch to gun"); } + { static CInputSet s_Set = {this, &m_InputData.m_WantedWeapon, 3}; Console()->Register("+weapon3", "", CFGFLAG_CLIENT, ConKeyInputSet, (void *)&s_Set, "Switch to shotgun"); } + { static CInputSet s_Set = {this, &m_InputData.m_WantedWeapon, 4}; Console()->Register("+weapon4", "", CFGFLAG_CLIENT, ConKeyInputSet, (void *)&s_Set, "Switch to grenade"); } + { static CInputSet s_Set = {this, &m_InputData.m_WantedWeapon, 5}; Console()->Register("+weapon5", "", CFGFLAG_CLIENT, ConKeyInputSet, (void *)&s_Set, "Switch to rifle"); } - { static CInputSet s_Set = {this, &m_InputData.m_NextWeapon, 0}; Console()->Register("+nextweapon", "", CFGFLAG_CLIENT, ConKeyInputNextPrevWeapon, (void *)&s_Set, "Switch to next weapon"); } - { static CInputSet s_Set = {this, &m_InputData.m_PrevWeapon, 0}; Console()->Register("+prevweapon", "", CFGFLAG_CLIENT, ConKeyInputNextPrevWeapon, (void *)&s_Set, "Switch to previous weapon"); } + { static CInputSet s_Set = {this, &m_InputData.m_NextWeapon, 0}; Console()->Register("+nextweapon", "", CFGFLAG_CLIENT, ConKeyInputNextPrevWeapon, (void *)&s_Set, "Switch to next weapon"); } + { static CInputSet s_Set = {this, &m_InputData.m_PrevWeapon, 0}; Console()->Register("+prevweapon", "", CFGFLAG_CLIENT, ConKeyInputNextPrevWeapon, (void *)&s_Set, "Switch to previous weapon"); } } void CControls::OnMessage(int Msg, void *pRawMsg) { - if(Msg == NETMSGTYPE_SV_WEAPONPICKUP) - { - CNetMsg_Sv_WeaponPickup *pMsg = (CNetMsg_Sv_WeaponPickup *)pRawMsg; - if(g_Config.m_ClAutoswitchWeapons) - m_InputData.m_WantedWeapon = pMsg->m_Weapon+1; - } + if(Msg == NETMSGTYPE_SV_WEAPONPICKUP) + { + CNetMsg_Sv_WeaponPickup *pMsg = (CNetMsg_Sv_WeaponPickup *)pRawMsg; + if(g_Config.m_ClAutoswitchWeapons) + m_InputData.m_WantedWeapon = pMsg->m_Weapon+1; + } } int CControls::SnapInput(int *pData) { static int64 LastSendTime = 0; bool Send = false; - + // update player state if(m_pClient->m_pChat->IsActive()) m_InputData.m_PlayerFlags = PLAYERFLAG_CHATTING; @@ -118,20 +118,20 @@ int CControls::SnapInput(int *pData) m_InputData.m_PlayerFlags = PLAYERFLAG_IN_MENU; else m_InputData.m_PlayerFlags = PLAYERFLAG_PLAYING; - + if(m_pClient->m_pScoreboard->Active()) m_InputData.m_PlayerFlags |= PLAYERFLAG_SCOREBOARD; if(m_LastData.m_PlayerFlags != m_InputData.m_PlayerFlags) Send = true; - + m_LastData.m_PlayerFlags = m_InputData.m_PlayerFlags; - + // we freeze the input if chat or menu is activated if(!(m_InputData.m_PlayerFlags&PLAYERFLAG_PLAYING)) { OnReset(); - + mem_copy(pData, &m_InputData, sizeof(m_InputData)); // send once a second just to be sure @@ -140,7 +140,7 @@ int CControls::SnapInput(int *pData) } else { - + m_InputData.m_TargetX = (int)m_MousePos.x; m_InputData.m_TargetY = (int)m_MousePos.y; if(!m_InputData.m_TargetX && !m_InputData.m_TargetY) @@ -148,7 +148,7 @@ int CControls::SnapInput(int *pData) m_InputData.m_TargetX = 1; m_MousePos.x = 1; } - + // set direction m_InputData.m_Direction = 0; if(m_InputDirectionLeft && !m_InputDirectionRight) @@ -184,16 +184,16 @@ int CControls::SnapInput(int *pData) if(time_get() > LastSendTime + time_freq()/25) Send = true; } - - // copy and return size + + // copy and return size m_LastData = m_InputData; - + if(!Send) return 0; - + LastSendTime = time_get(); mem_copy(pData, &m_InputData, sizeof(m_InputData)); - return sizeof(m_InputData); + return sizeof(m_InputData); } void CControls::OnRender() @@ -211,7 +211,7 @@ bool CControls::OnMouseMove(float x, float y) { if(m_pClient->m_Snap.m_pGameInfoObj && m_pClient->m_Snap.m_pGameInfoObj->m_GameStateFlags&GAMESTATEFLAG_PAUSED) return false; - + m_MousePos += vec2(x, y); // TODO: ugly ClampMousePos(); @@ -224,14 +224,14 @@ void CControls::ClampMousePos() { m_MousePos.x = clamp(m_MousePos.x, 200.0f, Collision()->GetWidth()*32-200.0f); m_MousePos.y = clamp(m_MousePos.y, 200.0f, Collision()->GetHeight()*32-200.0f); - + } else { float CameraMaxDistance = 200.0f; float FollowFactor = g_Config.m_ClMouseFollowfactor/100.0f; float MouseMax = min(CameraMaxDistance/FollowFactor + g_Config.m_ClMouseDeadzone, (float)g_Config.m_ClMouseMaxDistance); - + if(length(m_MousePos) > MouseMax) m_MousePos = normalize(m_MousePos)*MouseMax; } diff --git a/src/game/client/components/controls.h b/src/game/client/components/controls.h index a50318f5..aefc850c 100644 --- a/src/game/client/components/controls.h +++ b/src/game/client/components/controls.h @@ -6,7 +6,7 @@ #include <game/client/component.h> class CControls : public CComponent -{ +{ public: vec2 m_MousePos; vec2 m_TargetPos; @@ -17,7 +17,7 @@ public: int m_InputDirectionRight; CControls(); - + virtual void OnReset(); virtual void OnRelease(); virtual void OnRender(); @@ -25,7 +25,7 @@ public: virtual bool OnMouseMove(float x, float y); virtual void OnConsoleInit(); virtual void OnPlayerDeath(); - + int SnapInput(int *pData); void ClampMousePos(); }; diff --git a/src/game/client/components/countryflags.cpp b/src/game/client/components/countryflags.cpp index ae0217b2..2429ad3f 100644 --- a/src/game/client/components/countryflags.cpp +++ b/src/game/client/components/countryflags.cpp @@ -19,7 +19,7 @@ void CCountryFlags::LoadCountryflagsIndexfile() Console()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "countryflags", "couldn't open index file"); return; } - + char aOrigin[128]; CLineReader LineReader; LineReader.Init(File); @@ -28,7 +28,7 @@ void CCountryFlags::LoadCountryflagsIndexfile() { if(!str_length(pLine) || pLine[0] == '#') // skip empty lines and comments continue; - + str_copy(aOrigin, pLine, sizeof(aOrigin)); char *pReplacement = LineReader.Get(); if(!pReplacement) @@ -36,7 +36,7 @@ void CCountryFlags::LoadCountryflagsIndexfile() Console()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "countryflags", "unexpected end of index file"); break; } - + if(pReplacement[0] != '=' || pReplacement[1] != '=' || pReplacement[2] != ' ') { char aBuf[128]; @@ -44,7 +44,7 @@ void CCountryFlags::LoadCountryflagsIndexfile() Console()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "countryflags", aBuf); continue; } - + // load the graphic file char aBuf[128]; str_format(aBuf, sizeof(aBuf), "countryflags/%s.png", aOrigin); diff --git a/src/game/client/components/countryflags.h b/src/game/client/components/countryflags.h index b0960661..cd629094 100644 --- a/src/game/client/components/countryflags.h +++ b/src/game/client/components/countryflags.h @@ -13,16 +13,16 @@ public: { int m_CountryCode; int m_Texture; - + bool operator<(const CCountryFlag &Other) { return m_CountryCode < Other.m_CountryCode; } }; - + void OnInit(); - + int Num() const; const CCountryFlag *Get(int Index) const; int Find(int CountryCode) const; - + private: sorted_array<CCountryFlag> m_aCountryFlags; diff --git a/src/game/client/components/damageind.h b/src/game/client/components/damageind.h index 0515f646..2f89e422 100644 --- a/src/game/client/components/damageind.h +++ b/src/game/client/components/damageind.h @@ -27,7 +27,7 @@ class CDamageInd : public CComponent CItem *CreateI(); void DestroyI(CItem *i); -public: +public: CDamageInd(); void Create(vec2 Pos, vec2 Dir); diff --git a/src/game/client/components/debughud.cpp b/src/game/client/components/debughud.cpp index b904f60a..7145705c 100644 --- a/src/game/client/components/debughud.cpp +++ b/src/game/client/components/debughud.cpp @@ -22,16 +22,16 @@ void CDebugHud::RenderNetCorrections() if(!g_Config.m_Debug || g_Config.m_DbgGraphs || !m_pClient->m_Snap.m_pLocalCharacter || !m_pClient->m_Snap.m_pLocalPrevCharacter) return; - float Width = 300*Graphics()->ScreenAspect(); + float Width = 300*Graphics()->ScreenAspect(); Graphics()->MapScreen(0, 0, Width, 300); - + /*float speed = distance(vec2(netobjects.local_prev_character->x, netobjects.local_prev_character->y), vec2(netobjects.local_character->x, netobjects.local_character->y));*/ float Velspeed = length(vec2(m_pClient->m_Snap.m_pLocalCharacter->m_VelX/256.0f, m_pClient->m_Snap.m_pLocalCharacter->m_VelY/256.0f))*50; float Ramp = VelocityRamp(Velspeed, m_pClient->m_Tuning.m_VelrampStart, m_pClient->m_Tuning.m_VelrampRange, m_pClient->m_Tuning.m_VelrampCurvature); - - const char *paStrings[] = {"velspeed:", "velspeed*ramp:", "ramp:", "Pos", " x:", " y:", "netobj corrections", " num:", " on:"}; + + const char *paStrings[] = {"velspeed:", "velspeed*ramp:", "ramp:", "Pos", " x:", " y:", "netobj corrections", " num:", " on:"}; const int Num = sizeof(paStrings)/sizeof(char *); const float LineHeight = 6.0f; const float Fontsize = 5.0f; @@ -75,11 +75,11 @@ void CDebugHud::RenderTuning() // render tuning debugging if(!g_Config.m_DbgTuning) return; - + CTuningParams StandardTuning; - + Graphics()->MapScreen(0, 0, 300*Graphics()->ScreenAspect(), 300); - + float y = 50.0f; int Count = 0; for(int i = 0; i < m_pClient->m_Tuning.Num(); i++) @@ -88,7 +88,7 @@ void CDebugHud::RenderTuning() float Current, Standard; m_pClient->m_Tuning.Get(i, &Current); StandardTuning.Get(i, &Standard); - + if(Standard == Current) TextRender()->TextColor(1,1,1,1.0f); else @@ -96,7 +96,7 @@ void CDebugHud::RenderTuning() float w; float x = 5.0f; - + str_format(aBuf, sizeof(aBuf), "%.2f", Standard); x += 20.0f; w = TextRender()->TextWidth(0, 5, aBuf, -1); @@ -109,12 +109,12 @@ void CDebugHud::RenderTuning() x += 5.0f; TextRender()->Text(0x0, x, y+Count*6, 5, m_pClient->m_Tuning.m_apNames[i], -1); - + Count++; } - + y = y+Count*6; - + Graphics()->TextureSet(-1); Graphics()->BlendNormal(); Graphics()->LinesBegin(); diff --git a/src/game/client/components/debughud.h b/src/game/client/components/debughud.h index ad378dc8..145f921a 100644 --- a/src/game/client/components/debughud.h +++ b/src/game/client/components/debughud.h @@ -5,7 +5,7 @@ #include <game/client/component.h> class CDebugHud : public CComponent -{ +{ void RenderNetCorrections(); void RenderTuning(); public: diff --git a/src/game/client/components/effects.cpp b/src/game/client/components/effects.cpp index 9a5ff2d3..573ac410 100644 --- a/src/game/client/components/effects.cpp +++ b/src/game/client/components/effects.cpp @@ -43,7 +43,7 @@ void CEffects::AirJump(vec2 Pos) p.m_Pos = Pos + vec2(6.0f, 16.0f); m_pClient->m_pParticles->Add(CParticles::GROUP_GENERAL, &p); - + m_pClient->m_pSounds->Play(CSounds::CHN_WORLD, SOUND_PLAYER_AIRJUMP, 1.0f, Pos); } @@ -56,7 +56,7 @@ void CEffects::PowerupShine(vec2 Pos, vec2 size) { if(!m_Add50hz) return; - + CParticle p; p.SetDefault(); p.m_Spr = SPRITE_PART_SLICE; @@ -77,7 +77,7 @@ void CEffects::SmokeTrail(vec2 Pos, vec2 Vel) { if(!m_Add50hz) return; - + CParticle p; p.SetDefault(); p.m_Spr = SPRITE_PART_SMOKE; @@ -96,7 +96,7 @@ void CEffects::SkidTrail(vec2 Pos, vec2 Vel) { if(!m_Add100hz) return; - + CParticle p; p.SetDefault(); p.m_Spr = SPRITE_PART_SMOKE; @@ -108,14 +108,14 @@ void CEffects::SkidTrail(vec2 Pos, vec2 Vel) p.m_Friction = 0.7f; p.m_Gravity = frandom()*-500.0f; p.m_Color = vec4(0.75f,0.75f,0.75f,1.0f); - m_pClient->m_pParticles->Add(CParticles::GROUP_GENERAL, &p); + m_pClient->m_pParticles->Add(CParticles::GROUP_GENERAL, &p); } void CEffects::BulletTrail(vec2 Pos) { if(!m_Add100hz) return; - + CParticle p; p.SetDefault(); p.m_Spr = SPRITE_PART_BALL; @@ -145,7 +145,7 @@ void CEffects::PlayerSpawn(vec2 Pos) p.m_Friction = 0.7f; p.m_Color = vec4(0xb5/255.0f, 0x50/255.0f, 0xcb/255.0f, 1.0f); m_pClient->m_pParticles->Add(CParticles::GROUP_GENERAL, &p); - + } m_pClient->m_pSounds->Play(CSounds::CHN_WORLD, SOUND_PLAYER_SPAWN, 1.0f, Pos); } @@ -154,7 +154,7 @@ void CEffects::PlayerDeath(vec2 Pos, int ClientID) { vec3 BloodColor(1.0f,1.0f,1.0f); - if(ClientID >= 0) + if(ClientID >= 0) { if(m_pClient->m_aClients[ClientID].m_UseCustomColor) BloodColor = m_pClient->m_pSkins->GetColorV3(m_pClient->m_aClients[ClientID].m_ColorBody); @@ -165,7 +165,7 @@ void CEffects::PlayerDeath(vec2 Pos, int ClientID) BloodColor = s->m_BloodColor; } } - + for(int i = 0; i < 64; i++) { CParticle p; @@ -195,11 +195,11 @@ void CEffects::Explosion(vec2 Pos) { if(x == 0 && y == 0) continue; - + float a = 1 - (length(vec2(x,y)) / length(vec2(8,8))); m_pClient->m_pFlow->Add(Pos+vec2(x,y)*16, normalize(vec2(x,y))*5000.0f*a, 10.0f); } - + // add the explosion CParticle p; p.SetDefault(); @@ -210,7 +210,7 @@ void CEffects::Explosion(vec2 Pos) p.m_EndSize = 0; p.m_Rot = frandom()*pi*2; m_pClient->m_pParticles->Add(CParticles::GROUP_EXPLOSIONS, &p); - + // add the smoke for(int i = 0; i < 24; i++) { @@ -241,7 +241,7 @@ void CEffects::HammerHit(vec2 Pos) p.m_StartSize = 120.0f; p.m_EndSize = 0; p.m_Rot = frandom()*pi*2; - m_pClient->m_pParticles->Add(CParticles::GROUP_EXPLOSIONS, &p); + m_pClient->m_pParticles->Add(CParticles::GROUP_EXPLOSIONS, &p); m_pClient->m_pSounds->Play(CSounds::CHN_WORLD, SOUND_HAMMER_HIT, 1.0f, Pos); } @@ -253,7 +253,7 @@ void CEffects::OnRender() if(Client()->State() == IClient::STATE_DEMOPLAYBACK) { const IDemoPlayer::CInfo *pInfo = DemoPlayer()->BaseInfo(); - + if(time_get()-LastUpdate100hz > time_freq()/(100*pInfo->m_Speed)) { m_Add100hz = true; @@ -269,10 +269,10 @@ void CEffects::OnRender() } else m_Add50hz = false; - + if(m_Add50hz) m_pClient->m_pFlow->Update(); - + return; } @@ -291,7 +291,7 @@ void CEffects::OnRender() } else m_Add50hz = false; - + if(m_Add50hz) m_pClient->m_pFlow->Update(); } diff --git a/src/game/client/components/effects.h b/src/game/client/components/effects.h index b3924382..9ededb83 100644 --- a/src/game/client/components/effects.h +++ b/src/game/client/components/effects.h @@ -5,7 +5,7 @@ #include <game/client/component.h> class CEffects : public CComponent -{ +{ bool m_Add50hz; bool m_Add100hz; public: diff --git a/src/game/client/components/emoticon.cpp b/src/game/client/components/emoticon.cpp index 64b47b74..741a604f 100644 --- a/src/game/client/components/emoticon.cpp +++ b/src/game/client/components/emoticon.cpp @@ -53,7 +53,7 @@ bool CEmoticon::OnMouseMove(float x, float y) { if(!m_Active) return false; - + m_SelectorMouse += vec2(x,y); return true; } @@ -90,7 +90,7 @@ void CEmoticon::DrawCircle(float x, float y, float r, int Segments) m_pClient->Graphics()->QuadsDrawFreeform(Array, NumItems); } - + void CEmoticon::OnRender() { if(!m_Active) @@ -100,9 +100,9 @@ void CEmoticon::OnRender() m_WasActive = false; return; } - + m_WasActive = true; - + if (length(m_SelectorMouse) > 140) m_SelectorMouse = normalize(m_SelectorMouse) * 140; @@ -113,7 +113,7 @@ void CEmoticon::OnRender() if (length(m_SelectorMouse) > 100) m_SelectedEmote = (int)(SelectedAngle / (2*pi) * NUM_EMOTICONS); - CUIRect Screen = *UI()->Screen(); + CUIRect Screen = *UI()->Screen(); Graphics()->MapScreen(Screen.x, Screen.y, Screen.w, Screen.h); @@ -147,12 +147,12 @@ void CEmoticon::OnRender() Graphics()->QuadsEnd(); - Graphics()->TextureSet(g_pData->m_aImages[IMAGE_CURSOR].m_Id); - Graphics()->QuadsBegin(); - Graphics()->SetColor(1,1,1,1); + Graphics()->TextureSet(g_pData->m_aImages[IMAGE_CURSOR].m_Id); + Graphics()->QuadsBegin(); + Graphics()->SetColor(1,1,1,1); IGraphics::CQuadItem QuadItem(m_SelectorMouse.x+Screen.w/2,m_SelectorMouse.y+Screen.h/2,24,24); Graphics()->QuadsDrawTL(&QuadItem, 1); - Graphics()->QuadsEnd(); + Graphics()->QuadsEnd(); } void CEmoticon::Emote(int Emoticon) diff --git a/src/game/client/components/emoticon.h b/src/game/client/components/emoticon.h index add6c9b9..37bc8372 100644 --- a/src/game/client/components/emoticon.h +++ b/src/game/client/components/emoticon.h @@ -8,19 +8,19 @@ class CEmoticon : public CComponent { void DrawCircle(float x, float y, float r, int Segments); - + bool m_WasActive; bool m_Active; - + vec2 m_SelectorMouse; int m_SelectedEmote; static void ConKeyEmoticon(IConsole::IResult *pResult, void *pUserData); static void ConEmote(IConsole::IResult *pResult, void *pUserData); - + public: CEmoticon(); - + virtual void OnReset(); virtual void OnConsoleInit(); virtual void OnRender(); diff --git a/src/game/client/components/flow.cpp b/src/game/client/components/flow.cpp index 824687c0..8cfc54e7 100644 --- a/src/game/client/components/flow.cpp +++ b/src/game/client/components/flow.cpp @@ -12,7 +12,7 @@ CFlow::CFlow() m_Width = 0; m_Spacing = 16; } - + void CFlow::DbgRender() { if(!m_pCells) @@ -34,7 +34,7 @@ void CFlow::DbgRender() NumItems = 0; } } - + if(NumItems) Graphics()->LinesDraw(Array, NumItems); Graphics()->LinesEnd(); @@ -47,12 +47,12 @@ void CFlow::Init() mem_free(m_pCells); m_pCells = 0; } - + CMapItemLayerTilemap *pTilemap = Layers()->GameLayer(); m_Width = pTilemap->m_Width*32/m_Spacing; m_Height = pTilemap->m_Height*32/m_Spacing; - // allocate and clear + // allocate and clear m_pCells = (CCell *)mem_alloc(sizeof(CCell)*m_Width*m_Height, 1); for(int y = 0; y < m_Height; y++) for(int x = 0; x < m_Width; x++) @@ -63,7 +63,7 @@ void CFlow::Update() { if(!m_pCells) return; - + for(int y = 0; y < m_Height; y++) for(int x = 0; x < m_Width; x++) m_pCells[y*m_Width+x].m_Vel *= 0.85f; @@ -73,24 +73,24 @@ vec2 CFlow::Get(vec2 Pos) { if(!m_pCells) return vec2(0,0); - + int x = (int)(Pos.x / m_Spacing); int y = (int)(Pos.y / m_Spacing); if(x < 0 || y < 0 || x >= m_Width || y >= m_Height) return vec2(0,0); - - return m_pCells[y*m_Width+x].m_Vel; + + return m_pCells[y*m_Width+x].m_Vel; } void CFlow::Add(vec2 Pos, vec2 Vel, float Size) { if(!m_pCells) return; - + int x = (int)(Pos.x / m_Spacing); int y = (int)(Pos.y / m_Spacing); if(x < 0 || y < 0 || x >= m_Width || y >= m_Height) return; - + m_pCells[y*m_Width+x].m_Vel += Vel; } diff --git a/src/game/client/components/flow.h b/src/game/client/components/flow.h index 3785ab56..0b8e590f 100644 --- a/src/game/client/components/flow.h +++ b/src/game/client/components/flow.h @@ -16,12 +16,12 @@ class CFlow : public CComponent int m_Height; int m_Width; int m_Spacing; - + void DbgRender(); void Init(); public: CFlow(); - + vec2 Get(vec2 Pos); void Add(vec2 Pos, vec2 Vel, float Size); void Update(); diff --git a/src/game/client/components/hud.cpp b/src/game/client/components/hud.cpp index 00fdd88d..188691a1 100644 --- a/src/game/client/components/hud.cpp +++ b/src/game/client/components/hud.cpp @@ -22,7 +22,7 @@ CHud::CHud() // won't work if zero m_AverageFPS = 1.0f; } - + void CHud::OnReset() { } @@ -30,7 +30,7 @@ void CHud::OnReset() void CHud::RenderGameTimer() { float Half = 300.0f*Graphics()->ScreenAspect()/2.0f; - + if(!(m_pClient->m_Snap.m_pGameInfoObj->m_GameStateFlags&GAMESTATEFLAG_SUDDENDEATH)) { char Buf[32]; @@ -40,7 +40,7 @@ void CHud::RenderGameTimer() Time = m_pClient->m_Snap.m_pGameInfoObj->m_TimeLimit*60 - ((Client()->GameTick()-m_pClient->m_Snap.m_pGameInfoObj->m_RoundStartTick)/Client()->GameTickSpeed()); if(m_pClient->m_Snap.m_pGameInfoObj->m_GameStateFlags&GAMESTATEFLAG_GAMEOVER) - Time = 0; + Time = 0; } else Time = (Client()->GameTick()-m_pClient->m_Snap.m_pGameInfoObj->m_RoundStartTick)/Client()->GameTickSpeed(); @@ -72,7 +72,7 @@ void CHud::RenderSuddenDeath() } void CHud::RenderScoreHud() -{ +{ // render small score hud if(!(m_pClient->m_Snap.m_pGameInfoObj->m_GameStateFlags&GAMESTATEFLAG_GAMEOVER)) { @@ -89,7 +89,7 @@ void CHud::RenderScoreHud() float ScoreWidthMax = max(max(aScoreTeamWidth[TEAM_RED], aScoreTeamWidth[TEAM_BLUE]), TextRender()->TextWidth(0, 14.0f, "100", -1)); float Split = 3.0f; float ImageSize = GameFlags&GAMEFLAG_FLAGS ? 16.0f : Split; - + for(int t = 0; t < 2; t++) { // draw box @@ -178,7 +178,7 @@ void CHud::RenderScoreHud() float aScoreWidth[2] = {TextRender()->TextWidth(0, 14.0f, aScore[0], -1), TextRender()->TextWidth(0, 14.0f, aScore[1], -1)}; float ScoreWidthMax = max(max(aScoreWidth[0], aScoreWidth[1]), TextRender()->TextWidth(0, 14.0f, "10", -1)); float Split = 3.0f, ImageSize = 16.0f, PosSize = 16.0f; - + for(int t = 0; t < 2; t++) { // draw box @@ -230,7 +230,7 @@ void CHud::RenderWarmupTimer() str_format(Buf, sizeof(Buf), "%d", Seconds); w = TextRender()->TextWidth(0, FontSize, Buf, -1); TextRender()->Text(0, 150*Graphics()->ScreenAspect()+-w/2, 75, FontSize, Buf, -1); - } + } } void CHud::MapscreenToGroup(float CenterX, float CenterY, CMapItemGroup *pGroup) @@ -269,7 +269,7 @@ void CHud::RenderTeambalanceWarning() // render prompt about team-balance bool Flash = time_get()/(time_freq()/2)%2 == 0; if(m_pClient->m_Snap.m_pGameInfoObj->m_GameFlags&GAMEFLAG_TEAMS) - { + { int TeamDiff = m_pClient->m_Snap.m_aTeamSize[TEAM_RED]-m_pClient->m_Snap.m_aTeamSize[TEAM_BLUE]; if (g_Config.m_ClWarningTeambalance && (TeamDiff >= 2 || TeamDiff <= -2)) { @@ -289,7 +289,7 @@ void CHud::RenderVoting() { if(!m_pClient->m_pVoting->IsVoting() || Client()->State() == IClient::STATE_DEMOPLAYBACK) return; - + Graphics()->TextureSet(-1); Graphics()->QuadsBegin(); Graphics()->SetColor(0,0,0,0.40f); @@ -309,7 +309,7 @@ void CHud::RenderVoting() Cursor.m_LineWidth = 100.0f-tw; Cursor.m_MaxLines = 3; TextRender()->TextEx(&Cursor, m_pClient->m_pVoting->VoteDescription(), -1); - + // reason str_format(aBuf, sizeof(aBuf), "%s %s", Localize("Reason:"), m_pClient->m_pVoting->VoteReason()); TextRender()->SetCursor(&Cursor, 5.0f, 79.0f, 6.0f, TEXTFLAG_RENDER|TEXTFLAG_STOP_AT_END); @@ -318,7 +318,7 @@ void CHud::RenderVoting() CUIRect Base = {5, 88, 100, 4}; m_pClient->m_pVoting->RenderBars(Base, false); - + const char *pYesKey = m_pClient->m_pBinds->GetKey("vote yes"); const char *pNoKey = m_pClient->m_pBinds->GetKey("vote no"); str_format(aBuf, sizeof(aBuf), "%s - %s", pYesKey, Localize("Vote yes")); @@ -333,7 +333,7 @@ void CHud::RenderCursor() { if(!m_pClient->m_Snap.m_pLocalCharacter || Client()->State() == IClient::STATE_DEMOPLAYBACK) return; - + MapscreenToGroup(m_pClient->m_pCamera->m_Center.x, m_pClient->m_pCamera->m_Center.y, Layers()->GameGroup()); Graphics()->TextureSet(g_pData->m_aImages[IMAGE_GAME].m_Id); Graphics()->QuadsBegin(); @@ -359,9 +359,9 @@ void CHud::RenderHealthAndAmmo(const CNetObj_Character *pCharacter) // render gui stuff Graphics()->TextureSet(g_pData->m_aImages[IMAGE_GAME].m_Id); - + Graphics()->QuadsBegin(); - + // if weaponstage is active, put a "glow" around the stage ammo RenderTools()->SelectSprite(g_pData->m_Weapons.m_aId[pCharacter->m_Weapon%NUM_WEAPONS].m_pSpriteProj); IGraphics::CQuadItem Array[10]; @@ -421,7 +421,7 @@ void CHud::OnRender() { if(!m_pClient->m_Snap.m_pGameInfoObj) return; - + m_Width = 300.0f*Graphics()->ScreenAspect(); m_Height = 300.0f; Graphics()->MapScreen(0.0f, 0.0f, m_Width, m_Height); diff --git a/src/game/client/components/hud.h b/src/game/client/components/hud.h index 75702d51..f0250c7b 100644 --- a/src/game/client/components/hud.h +++ b/src/game/client/components/hud.h @@ -5,12 +5,12 @@ #include <game/client/component.h> class CHud : public CComponent -{ +{ float m_Width, m_Height; float m_AverageFPS; - + void RenderCursor(); - + void RenderFps(); void RenderConnectionWarning(); void RenderTeambalanceWarning(); @@ -25,7 +25,7 @@ class CHud : public CComponent void MapscreenToGroup(float CenterX, float CenterY, struct CMapItemGroup *PGroup); public: CHud(); - + virtual void OnReset(); virtual void OnRender(); }; diff --git a/src/game/client/components/items.cpp b/src/game/client/components/items.cpp index 5eeb3209..827b28a7 100644 --- a/src/game/client/components/items.cpp +++ b/src/game/client/components/items.cpp @@ -45,7 +45,7 @@ void CItems::RenderProjectile(const CNetObj_Projectile *pCurrent, int ItemID) float Ct = (Client()->PrevGameTick()-pCurrent->m_StartTick)/(float)SERVER_TICK_SPEED + Client()->GameTickTime(); if(Ct < 0) return; // projectile havn't been shot yet - + vec2 StartPos(pCurrent->m_X, pCurrent->m_Y); vec2 StartVel(pCurrent->m_VelX/100.0f, pCurrent->m_VelY/100.0f); vec2 Pos = CalcPos(StartPos, StartVel, Curvature, Speed, Ct); @@ -54,29 +54,29 @@ void CItems::RenderProjectile(const CNetObj_Projectile *pCurrent, int ItemID) Graphics()->TextureSet(g_pData->m_aImages[IMAGE_GAME].m_Id); Graphics()->QuadsBegin(); - + RenderTools()->SelectSprite(g_pData->m_Weapons.m_aId[clamp(pCurrent->m_Type, 0, NUM_WEAPONS-1)].m_pSpriteProj); vec2 Vel = Pos-PrevPos; //vec2 pos = mix(vec2(prev->x, prev->y), vec2(current->x, current->y), Client()->IntraGameTick()); - + // add particle for this projectile if(pCurrent->m_Type == WEAPON_GRENADE) { m_pClient->m_pEffects->SmokeTrail(Pos, Vel*-1); m_pClient->m_pFlow->Add(Pos, Vel*1000*Client()->FrameTime(), 10.0f); - + if(Client()->State() == IClient::STATE_DEMOPLAYBACK) { const IDemoPlayer::CInfo *pInfo = DemoPlayer()->BaseInfo(); static float Time = 0; static float LastLocalTime = Client()->LocalTime(); - + if(!pInfo->m_Paused) Time += (Client()->LocalTime()-LastLocalTime)*pInfo->m_Speed; - + Graphics()->QuadsSetRotation(Time*pi*2*2 + ItemID); - + LastLocalTime = Client()->LocalTime(); } else @@ -139,13 +139,13 @@ void CItems::RenderPickup(const CNetObj_Pickup *pPrev, const CNetObj_Pickup *pCu const IDemoPlayer::CInfo *pInfo = DemoPlayer()->BaseInfo(); static float Time = 0; static float LastLocalTime = Client()->LocalTime(); - + if(!pInfo->m_Paused) Time += (Client()->LocalTime()-LastLocalTime)*pInfo->m_Speed; - + Pos.x += cosf(Time*2.0f+Offset)*2.5f; Pos.y += sinf(Time*2.0f+Offset)*2.5f; - + LastLocalTime = Client()->LocalTime(); } else @@ -174,7 +174,7 @@ void CItems::RenderFlag(const CNetObj_Flag *pPrev, const CNetObj_Flag *pCurrent, Graphics()->QuadsSetRotation(Angle); vec2 Pos = mix(vec2(pPrev->m_X, pPrev->m_Y), vec2(pCurrent->m_X, pCurrent->m_Y), Client()->IntraGameTick()); - + if(pCurGameData) { // make sure that the flag isn't interpolated between capture and return @@ -204,16 +204,16 @@ void CItems::RenderLaser(const struct CNetObj_Laser *pCurrent) float Ticks = Client()->GameTick() + Client()->IntraGameTick() - pCurrent->m_StartTick; float Ms = (Ticks/50.0f) * 1000.0f; - float a = Ms / m_pClient->m_Tuning.m_LaserBounceDelay; + float a = Ms / m_pClient->m_Tuning.m_LaserBounceDelay; a = clamp(a, 0.0f, 1.0f); float Ia = 1-a; - + vec2 Out, Border; - + Graphics()->BlendNormal(); Graphics()->TextureSet(-1); Graphics()->QuadsBegin(); - + //vec4 inner_color(0.15f,0.35f,0.75f,1.0f); //vec4 outer_color(0.65f,0.85f,1.0f,1.0f); @@ -229,20 +229,20 @@ void CItems::RenderLaser(const struct CNetObj_Laser *pCurrent) Pos.x+Out.x, Pos.y+Out.y); Graphics()->QuadsDrawFreeform(&Freeform, 1); - // do inner + // do inner vec4 InnerColor(0.5f, 0.5f, 1.0f, 1.0f); Out = vec2(Dir.y, -Dir.x) * (5.0f*Ia); Graphics()->SetColor(InnerColor.r, InnerColor.g, InnerColor.b, 1.0f); // center - + Freeform = IGraphics::CFreeformItem( From.x-Out.x, From.y-Out.y, From.x+Out.x, From.y+Out.y, Pos.x-Out.x, Pos.y-Out.y, Pos.x+Out.x, Pos.y+Out.y); Graphics()->QuadsDrawFreeform(&Freeform, 1); - + Graphics()->QuadsEnd(); - + // render head { Graphics()->BlendNormal(); @@ -260,8 +260,8 @@ void CItems::RenderLaser(const struct CNetObj_Laser *pCurrent) Graphics()->QuadsDraw(&QuadItem, 1); Graphics()->QuadsEnd(); } - - Graphics()->BlendNormal(); + + Graphics()->BlendNormal(); } void CItems::OnRender() @@ -302,7 +302,7 @@ void CItems::OnRender() const void *pPrev = Client()->SnapFindItem(IClient::SNAP_PREV, Item.m_Type, Item.m_ID); if (pPrev) { - const void *pPrevGameData = Client()->SnapFindItem(IClient::SNAP_PREV, NETOBJTYPE_GAMEDATA, m_pClient->m_Snap.m_GameDataSnapID); + const void *pPrevGameData = Client()->SnapFindItem(IClient::SNAP_PREV, NETOBJTYPE_GAMEDATA, m_pClient->m_Snap.m_GameDataSnapID); RenderFlag(static_cast<const CNetObj_Flag *>(pPrev), static_cast<const CNetObj_Flag *>(pData), static_cast<const CNetObj_GameData *>(pPrevGameData), m_pClient->m_Snap.m_pGameDataObj); } diff --git a/src/game/client/components/items.h b/src/game/client/components/items.h index c366b8d9..604c1b1c 100644 --- a/src/game/client/components/items.h +++ b/src/game/client/components/items.h @@ -5,24 +5,24 @@ #include <game/client/component.h> class CItems : public CComponent -{ +{ enum { MAX_EXTRA_PROJECTILES=32, }; - + CNetObj_Projectile aExtraProjectiles[MAX_EXTRA_PROJECTILES]; int ExtraProjectilesNum; - + void RenderProjectile(const CNetObj_Projectile *pCurrent, int ItemID); void RenderPickup(const CNetObj_Pickup *pPrev, const CNetObj_Pickup *pCurrent); void RenderFlag(const CNetObj_Flag *pPrev, const CNetObj_Flag *pCurrent, const CNetObj_GameData *pPrevGameData, const CNetObj_GameData *pCurGameData); void RenderLaser(const struct CNetObj_Laser *pCurrent); - + public: virtual void OnReset(); virtual void OnRender(); - + void AddExtraProjectile(CNetObj_Projectile *pProj); }; diff --git a/src/game/client/components/killmessages.cpp b/src/game/client/components/killmessages.cpp index 869199cf..03f6380a 100644 --- a/src/game/client/components/killmessages.cpp +++ b/src/game/client/components/killmessages.cpp @@ -21,7 +21,7 @@ void CKillMessages::OnMessage(int MsgType, void *pRawMsg) if(MsgType == NETMSGTYPE_SV_KILLMSG) { CNetMsg_Sv_KillMsg *pMsg = (CNetMsg_Sv_KillMsg *)pRawMsg; - + // unpack messages CKillMsg Kill; Kill.m_VictimID = pMsg->m_Victim; @@ -69,7 +69,7 @@ void CKillMessages::OnRender() // render victim tee x -= 24.0f; - + if(m_pClient->m_Snap.m_pGameInfoObj && m_pClient->m_Snap.m_pGameInfoObj->m_GameFlags&GAMEFLAG_FLAGS) { if(m_aKillmsgs[r].m_ModeSpecial&1) @@ -82,17 +82,17 @@ void CKillMessages::OnRender() RenderTools()->SelectSprite(SPRITE_FLAG_BLUE); else RenderTools()->SelectSprite(SPRITE_FLAG_RED); - + float Size = 56.0f; IGraphics::CQuadItem QuadItem(x, y-16, Size/2, Size); Graphics()->QuadsDrawTL(&QuadItem, 1); - Graphics()->QuadsEnd(); + Graphics()->QuadsEnd(); } } - + RenderTools()->RenderTee(CAnimState::GetIdle(), &m_aKillmsgs[r].m_VictimRenderInfo, EMOTE_PAIN, vec2(-1,0), vec2(x, y+28)); x -= 32.0f; - + // render weapon x -= 44.0f; if (m_aKillmsgs[r].m_Weapon >= 0) @@ -119,14 +119,14 @@ void CKillMessages::OnRender() RenderTools()->SelectSprite(SPRITE_FLAG_BLUE, SPRITE_FLAG_FLIP_X); else RenderTools()->SelectSprite(SPRITE_FLAG_RED, SPRITE_FLAG_FLIP_X); - + float Size = 56.0f; IGraphics::CQuadItem QuadItem(x-56, y-16, Size/2, Size); Graphics()->QuadsDrawTL(&QuadItem, 1); - Graphics()->QuadsEnd(); + Graphics()->QuadsEnd(); } - } - + } + // render killer tee x -= 24.0f; RenderTools()->RenderTee(CAnimState::GetIdle(), &m_aKillmsgs[r].m_KillerRenderInfo, EMOTE_ANGRY, vec2(1,0), vec2(x, y+28)); diff --git a/src/game/client/components/killmessages.h b/src/game/client/components/killmessages.h index 8bf93758..a4c3e40f 100644 --- a/src/game/client/components/killmessages.h +++ b/src/game/client/components/killmessages.h @@ -22,7 +22,7 @@ public: int m_ModeSpecial; // for CTF, if the guy is carrying a flag for example int m_Tick; }; - + enum { MAX_KILLMSGS = 5, diff --git a/src/game/client/components/mapimages.cpp b/src/game/client/components/mapimages.cpp index 2a9cecd4..dc136343 100644 --- a/src/game/client/components/mapimages.cpp +++ b/src/game/client/components/mapimages.cpp @@ -16,7 +16,7 @@ CMapImages::CMapImages() void CMapImages::OnMapLoad() { IMap *pMap = Kernel()->RequestInterface<IMap>(); - + // unload all textures for(int i = 0; i < m_Count; i++) { @@ -27,12 +27,12 @@ void CMapImages::OnMapLoad() int Start; pMap->GetType(MAPITEMTYPE_IMAGE, &Start, &m_Count); - + // load new textures for(int i = 0; i < m_Count; i++) { m_aTextures[i] = 0; - + CMapItemImage *pImg = (CMapItemImage *)pMap->GetItem(Start+i, 0, 0); if(pImg->m_External) { diff --git a/src/game/client/components/mapimages.h b/src/game/client/components/mapimages.h index 2aaa51fc..66101274 100644 --- a/src/game/client/components/mapimages.h +++ b/src/game/client/components/mapimages.h @@ -5,12 +5,12 @@ #include <game/client/component.h> class CMapImages : public CComponent -{ +{ int m_aTextures[64]; int m_Count; public: CMapImages(); - + int Get(int Index) const { return m_aTextures[Index]; } int Num() const { return m_Count; } diff --git a/src/game/client/components/maplayers.cpp b/src/game/client/components/maplayers.cpp index 2fdd2acc..848651ca 100644 --- a/src/game/client/components/maplayers.cpp +++ b/src/game/client/components/maplayers.cpp @@ -54,26 +54,26 @@ void CMapLayers::EnvelopeEval(float TimeOffset, int Env, float *pChannels, void if(Num) pPoints = (CEnvPoint *)pThis->m_pLayers->Map()->GetItem(Start, 0, 0); } - + int Start, Num; pThis->m_pLayers->Map()->GetType(MAPITEMTYPE_ENVELOPE, &Start, &Num); - + if(Env >= Num) return; - + CMapItemEnvelope *pItem = (CMapItemEnvelope *)pThis->m_pLayers->Map()->GetItem(Start+Env, 0, 0); - + if(pThis->Client()->State() == IClient::STATE_DEMOPLAYBACK) { const IDemoPlayer::CInfo *pInfo = pThis->DemoPlayer()->BaseInfo(); static float Time = 0; static float LastLocalTime = pThis->Client()->LocalTime(); - + if(!pInfo->m_Paused) Time += (pThis->Client()->LocalTime()-LastLocalTime)*pInfo->m_Speed; - + pThis->RenderTools()->RenderEvalEnvelope(pPoints+pItem->m_StartPoint, pItem->m_NumPoints, 4, Time+TimeOffset, pChannels); - + LastLocalTime = pThis->Client()->LocalTime(); } else @@ -84,20 +84,20 @@ void CMapLayers::OnRender() { if(Client()->State() != IClient::STATE_ONLINE && Client()->State() != IClient::STATE_DEMOPLAYBACK) return; - + CUIRect Screen; Graphics()->GetScreen(&Screen.x, &Screen.y, &Screen.w, &Screen.h); - + vec2 Center = m_pClient->m_pCamera->m_Center; //float center_x = gameclient.camera->center.x; //float center_y = gameclient.camera->center.y; - + bool PassedGameLayer = false; - + for(int g = 0; g < m_pLayers->NumGroups(); g++) { CMapItemGroup *pGroup = m_pLayers->GetGroup(g); - + if(!g_Config.m_GfxNoclip && pGroup->m_Version >= 2 && pGroup->m_UseClipping) { // set clipping @@ -108,29 +108,29 @@ void CMapLayers::OnRender() float y0 = (pGroup->m_ClipY - Points[1]) / (Points[3]-Points[1]); float x1 = ((pGroup->m_ClipX+pGroup->m_ClipW) - Points[0]) / (Points[2]-Points[0]); float y1 = ((pGroup->m_ClipY+pGroup->m_ClipH) - Points[1]) / (Points[3]-Points[1]); - + Graphics()->ClipEnable((int)(x0*Graphics()->ScreenWidth()), (int)(y0*Graphics()->ScreenHeight()), (int)((x1-x0)*Graphics()->ScreenWidth()), (int)((y1-y0)*Graphics()->ScreenHeight())); - } - + } + MapScreenToGroup(Center.x, Center.y, pGroup); - + for(int l = 0; l < pGroup->m_NumLayers; l++) { CMapItemLayer *pLayer = m_pLayers->GetLayer(pGroup->m_StartLayer+l); bool Render = false; bool IsGameLayer = false; - + if(pLayer == (CMapItemLayer*)m_pLayers->GameLayer()) { IsGameLayer = true; PassedGameLayer = 1; } - + // skip rendering if detail layers if not wanted if(pLayer->m_Flags&LAYERFLAG_DETAIL && !g_Config.m_GfxHighDetail && !IsGameLayer) continue; - + if(m_Type == -1) Render = true; else if(m_Type == 0) @@ -144,7 +144,7 @@ void CMapLayers::OnRender() if(PassedGameLayer && !IsGameLayer) Render = true; } - + if(Render && pLayer->m_Type == LAYERTYPE_TILES && Input()->KeyPressed(KEY_LCTRL) && Input()->KeyPressed(KEY_LSHIFT) && Input()->KeyDown(KEY_KP0)) { CMapItemLayerTilemap *pTMap = (CMapItemLayerTilemap *)pLayer; @@ -169,12 +169,12 @@ void CMapLayers::OnRender() } io_close(File); } - } - + } + if(Render && !IsGameLayer) { //layershot_begin(); - + if(pLayer->m_Type == LAYERTYPE_TILES) { CMapItemLayerTilemap *pTMap = (CMapItemLayerTilemap *)pLayer; @@ -182,7 +182,7 @@ void CMapLayers::OnRender() Graphics()->TextureSet(-1); else Graphics()->TextureSet(m_pClient->m_pMapimages->Get(pTMap->m_Image)); - + CTile *pTiles = (CTile *)m_pLayers->Map()->GetData(pTMap->m_Data); Graphics()->BlendNone(); vec4 Color = vec4(pTMap->m_Color.r/255.0f, pTMap->m_Color.g/255.0f, pTMap->m_Color.b/255.0f, pTMap->m_Color.a/255.0f); @@ -199,23 +199,23 @@ void CMapLayers::OnRender() Graphics()->TextureSet(m_pClient->m_pMapimages->Get(pQLayer->m_Image)); CQuad *pQuads = (CQuad *)m_pLayers->Map()->GetDataSwapped(pQLayer->m_Data); - + Graphics()->BlendNone(); RenderTools()->RenderQuads(pQuads, pQLayer->m_NumQuads, LAYERRENDERFLAG_OPAQUE, EnvelopeEval, this); Graphics()->BlendNormal(); RenderTools()->RenderQuads(pQuads, pQLayer->m_NumQuads, LAYERRENDERFLAG_TRANSPARENT, EnvelopeEval, this); } - - //layershot_end(); + + //layershot_end(); } } if(!g_Config.m_GfxNoclip) Graphics()->ClipDisable(); } - + if(!g_Config.m_GfxNoclip) Graphics()->ClipDisable(); - + // reset the screen like it was before Graphics()->MapScreen(Screen.x, Screen.y, Screen.w, Screen.h); } diff --git a/src/game/client/components/maplayers.h b/src/game/client/components/maplayers.h index ac78bebf..694633ee 100644 --- a/src/game/client/components/maplayers.h +++ b/src/game/client/components/maplayers.h @@ -5,7 +5,7 @@ #include <game/client/component.h> class CMapLayers : public CComponent -{ +{ CLayers *m_pLayers; // todo refactor: maybe remove it and access it through client* int m_Type; diff --git a/src/game/client/components/menus.cpp b/src/game/client/components/menus.cpp index 060384ec..53192714 100644 --- a/src/game/client/components/menus.cpp +++ b/src/game/client/components/menus.cpp @@ -52,20 +52,20 @@ CMenus::CMenus() m_Popup = POPUP_NONE; m_ActivePage = PAGE_INTERNET; m_GamePage = PAGE_GAME; - + m_NeedRestartGraphics = false; m_NeedRestartSound = false; m_NeedSendinfo = false; m_MenuActive = true; m_UseMouseButtons = true; - + m_EscapePressed = false; m_EnterPressed = false; m_DeletePressed = false; m_NumInputEvents = 0; - + m_LastInput = time_get(); - + str_copy(m_aCurrentDemoFolder, "demos", sizeof(m_aCurrentDemoFolder)); m_aCallvoteReason[0] = 0; @@ -84,13 +84,13 @@ vec4 CMenus::ButtonColorMul(const void *pID) int CMenus::DoButton_Icon(int ImageId, int SpriteId, const CUIRect *pRect) { Graphics()->TextureSet(g_pData->m_aImages[ImageId].m_Id); - + Graphics()->QuadsBegin(); RenderTools()->SelectSprite(SpriteId); IGraphics::CQuadItem QuadItem(pRect->x, pRect->y, pRect->w, pRect->h); Graphics()->QuadsDrawTL(&QuadItem, 1); Graphics()->QuadsEnd(); - + return 0; } @@ -108,7 +108,7 @@ int CMenus::DoButton_Toggle(const void *pID, int Checked, const CUIRect *pRect) Graphics()->QuadsDrawTL(&QuadItem, 1); } Graphics()->QuadsEnd(); - + return UI()->DoButtonLogic(pID, "", Checked, pRect); } @@ -138,7 +138,7 @@ int CMenus::DoButton_MenuTab(const void *pID, const char *pText, int Checked, co CUIRect Temp; pRect->HMargin(2.0f, &Temp); UI()->DoLabel(&Temp, pText, Temp.h*ms_FontmodHeight, 0); - + return UI()->DoButtonLogic(pID, pText, Checked, pRect); } @@ -162,7 +162,7 @@ int CMenus::DoButton_CheckBox_Common(const void *pID, const char *pText, const c t.x += c.w; t.w -= c.w; t.VSplitLeft(5.0f, 0, &t); - + c.Margin(2.0f, &c); RenderTools()->DrawUIRect(&c, vec4(1,1,1,0.25f)*ButtonColorMul(pID), CUI::CORNER_ALL, 3.0f); c.y += 2; @@ -186,7 +186,7 @@ int CMenus::DoButton_CheckBox_Number(const void *pID, const char *pText, int Che int CMenus::DoEditBox(void *pID, const CUIRect *pRect, char *pStr, unsigned StrSize, float FontSize, float *Offset, bool Hidden, int Corners) { - int Inside = UI()->MouseInside(pRect); + int Inside = UI()->MouseInside(pRect); bool ReturnValue = false; bool UpdateOffset = false; static int s_AtIndex = 0; @@ -200,7 +200,7 @@ int CMenus::DoEditBox(void *pID, const CUIRect *pRect, char *pStr, unsigned StrS int Len = str_length(pStr); if(Len == 0) s_AtIndex = 0; - + if(Inside && UI()->MouseButton(0)) { s_DoScroll = true; @@ -246,7 +246,7 @@ int CMenus::DoEditBox(void *pID, const CUIRect *pRect, char *pStr, unsigned StrS } bool JustGotActive = false; - + if(UI()->ActiveItem() == pID) { if(!UI()->MouseButton(0)) @@ -264,7 +264,7 @@ int CMenus::DoEditBox(void *pID, const CUIRect *pRect, char *pStr, unsigned StrS UI()->SetActiveItem(pID); } } - + if(Inside) UI()->SetHotItem(pID); @@ -272,10 +272,10 @@ int CMenus::DoEditBox(void *pID, const CUIRect *pRect, char *pStr, unsigned StrS RenderTools()->DrawUIRect(&Textbox, vec4(1, 1, 1, 0.5f), Corners, 3.0f); Textbox.VMargin(2.0f, &Textbox); Textbox.HMargin(2.0f, &Textbox); - + const char *pDisplayStr = pStr; char aStars[128]; - + if(Hidden) { unsigned s = str_length(pStr); @@ -315,7 +315,7 @@ int CMenus::DoEditBox(void *pID, const CUIRect *pRect, char *pStr, unsigned StrS Textbox.x -= *Offset; UI()->DoLabel(&Textbox, pDisplayStr, FontSize, -1); - + // render the cursor if(UI()->LastActiveItem() == pID && !JustGotActive) { @@ -341,14 +341,14 @@ float CMenus::DoScrollbarV(const void *pID, const CUIRect *pRect, float Current) Handle.y += (pRect->h-Handle.h)*Current; // logic - float ReturnValue = Current; - int Inside = UI()->MouseInside(&Handle); + float ReturnValue = Current; + int Inside = UI()->MouseInside(&Handle); if(UI()->ActiveItem() == pID) { if(!UI()->MouseButton(0)) UI()->SetActiveItem(0); - + float Min = pRect->y; float Max = pRect->h-Handle.h; float Cur = UI()->MouseY()-OffsetY; @@ -364,7 +364,7 @@ float CMenus::DoScrollbarV(const void *pID, const CUIRect *pRect, float Current) OffsetY = UI()->MouseY()-Handle.y; } } - + if(Inside) UI()->SetHotItem(pID); @@ -382,8 +382,8 @@ float CMenus::DoScrollbarV(const void *pID, const CUIRect *pRect, float Current) Slider = Handle; Slider.Margin(5.0f, &Slider); RenderTools()->DrawUIRect(&Slider, vec4(1,1,1,0.25f)*ButtonColorMul(pID), CUI::CORNER_ALL, 2.5f); - - return ReturnValue; + + return ReturnValue; } @@ -397,14 +397,14 @@ float CMenus::DoScrollbarH(const void *pID, const CUIRect *pRect, float Current) Handle.x += (pRect->w-Handle.w)*Current; // logic - float ReturnValue = Current; - int Inside = UI()->MouseInside(&Handle); + float ReturnValue = Current; + int Inside = UI()->MouseInside(&Handle); if(UI()->ActiveItem() == pID) { if(!UI()->MouseButton(0)) UI()->SetActiveItem(0); - + float Min = pRect->x; float Max = pRect->w-Handle.w; float Cur = UI()->MouseX()-OffsetX; @@ -420,7 +420,7 @@ float CMenus::DoScrollbarH(const void *pID, const CUIRect *pRect, float Current) OffsetX = UI()->MouseX()-Handle.x; } } - + if(Inside) UI()->SetHotItem(pID); @@ -438,8 +438,8 @@ float CMenus::DoScrollbarH(const void *pID, const CUIRect *pRect, float Current) Slider = Handle; Slider.Margin(5.0f, &Slider); RenderTools()->DrawUIRect(&Slider, vec4(1,1,1,0.25f)*ButtonColorMul(pID), CUI::CORNER_ALL, 2.5f); - - return ReturnValue; + + return ReturnValue; } int CMenus::DoKeyReader(void *pID, const CUIRect *pRect, int Key) @@ -450,7 +450,7 @@ int CMenus::DoKeyReader(void *pID, const CUIRect *pRect, int Key) static int ButtonUsed = 0; int Inside = UI()->MouseInside(pRect); int NewKey = Key; - + if(!UI()->MouseButton(0) && !UI()->MouseButton(1) && pGrabbedID == pID) MouseReleased = true; @@ -493,7 +493,7 @@ int CMenus::DoKeyReader(void *pID, const CUIRect *pRect, int Key) } } } - + if(Inside) UI()->SetHotItem(pID); @@ -515,13 +515,13 @@ int CMenus::RenderMenubar(CUIRect r) { CUIRect Box = r; CUIRect Button; - + m_ActivePage = g_Config.m_UiPage; int NewPage = -1; - + if(Client()->State() != IClient::STATE_OFFLINE) m_ActivePage = m_GamePage; - + if(Client()->State() == IClient::STATE_OFFLINE) { // offline menus @@ -531,7 +531,7 @@ int CMenus::RenderMenubar(CUIRect r) static int s_NewsButton=0; if (DoButton_MenuTab(&s_NewsButton, Localize("News"), m_ActivePage==PAGE_NEWS, &Button, 0)) NewPage = PAGE_NEWS; - Box.VSplitLeft(30.0f, 0, &Box); + Box.VSplitLeft(30.0f, 0, &Box); } Box.VSplitLeft(100.0f, &Button, &Box); @@ -557,17 +557,17 @@ int CMenus::RenderMenubar(CUIRect r) if(DoButton_MenuTab(&s_FavoritesButton, Localize("Favorites"), m_ActivePage==PAGE_FAVORITES, &Button, CUI::CORNER_TR)) { ServerBrowser()->Refresh(IServerBrowser::TYPE_FAVORITES); - NewPage = PAGE_FAVORITES; + NewPage = PAGE_FAVORITES; } - + Box.VSplitLeft(4.0f*5, 0, &Box); Box.VSplitLeft(100.0f, &Button, &Box); static int s_DemosButton=0; if(DoButton_MenuTab(&s_DemosButton, Localize("Demos"), m_ActivePage==PAGE_DEMOS, &Button, CUI::CORNER_T)) { DemolistPopulate(); - NewPage = PAGE_DEMOS; - } + NewPage = PAGE_DEMOS; + } } else { @@ -592,16 +592,16 @@ int CMenus::RenderMenubar(CUIRect r) if(DoButton_MenuTab(&s_CallVoteButton, Localize("Call vote"), m_ActivePage==PAGE_CALLVOTE, &Button, CUI::CORNER_TR)) NewPage = PAGE_CALLVOTE; } - + /* box.VSplitRight(110.0f, &box, &button); static int system_button=0; if (UI()->DoButton(&system_button, "System", g_Config.m_UiPage==PAGE_SYSTEM, &button)) g_Config.m_UiPage = PAGE_SYSTEM; - + box.VSplitRight(30.0f, &box, 0); */ - + Box.VSplitRight(90.0f, &Box, &Button); static int s_QuitButton=0; if(DoButton_MenuTab(&s_QuitButton, Localize("Quit"), 0, &Button, CUI::CORNER_T)) @@ -612,7 +612,7 @@ int CMenus::RenderMenubar(CUIRect r) static int s_SettingsButton=0; if(DoButton_MenuTab(&s_SettingsButton, Localize("Settings"), m_ActivePage==PAGE_SETTINGS, &Button, CUI::CORNER_T)) NewPage = PAGE_SETTINGS; - + if(NewPage != -1) { if(Client()->State() == IClient::STATE_OFFLINE) @@ -620,7 +620,7 @@ int CMenus::RenderMenubar(CUIRect r) else m_GamePage = NewPage; } - + return 0; } @@ -633,14 +633,14 @@ void CMenus::RenderLoading() // because that will slow down loading if we have vsync if(time_get()-LastLoadRender < time_freq()/60) return; - + LastLoadRender = time_get(); - + // need up date this here to get correct vec3 Rgb = HslToRgb(vec3(g_Config.m_UiColorHue/255.0f, g_Config.m_UiColorSat/255.0f, g_Config.m_UiColorLht/255.0f)); ms_GuiColor = vec4(Rgb.r, Rgb.g, Rgb.b, g_Config.m_UiColorAlpha/255.0f); - - CUIRect Screen = *UI()->Screen(); + + CUIRect Screen = *UI()->Screen(); Graphics()->MapScreen(Screen.x, Screen.y, Screen.w, Screen.h); RenderBackground(); @@ -701,14 +701,14 @@ void CMenus::OnInit() for(array<string>::range r = my_strings.all(); !r.empty(); r.pop_front()) dbg_msg("", "%s", r.front().cstr()); - + sort(my_strings.all()); - + dbg_msg("", "after:"); for(array<string>::range r = my_strings.all(); !r.empty(); r.pop_front()) dbg_msg("", "%s", r.front().cstr()); - - + + array<int> myarray; myarray.add(4); myarray.add(6); @@ -720,17 +720,17 @@ void CMenus::OnInit() for(array<int>::range r = myarray.all(); !r.empty(); r.pop_front()) dbg_msg("", "%d", r.front()); - + sort(myarray.all()); sort_verify(myarray.all()); - + dbg_msg("", "after:"); for(array<int>::range r = myarray.all(); !r.empty(); r.pop_front()) dbg_msg("", "%d", r.front()); - + exit(-1); // */ - + if(g_Config.m_ClShowWelcome) m_Popup = POPUP_LANGUAGE; g_Config.m_ClShowWelcome = 0; @@ -759,7 +759,7 @@ void CMenus::PopupMessage(const char *pTopic, const char *pBody, const char *pBu int CMenus::Render() { - CUIRect Screen = *UI()->Screen(); + CUIRect Screen = *UI()->Screen(); Graphics()->MapScreen(Screen.x, Screen.y, Screen.w, Screen.h); static bool s_First = true; @@ -774,7 +774,7 @@ int CMenus::Render() m_pClient->m_pSounds->Enqueue(CSounds::CHN_MUSIC, SOUND_MENU); s_First = false; } - + if(Client()->State() == IClient::STATE_ONLINE) { ms_ColorTabbarInactive = ms_ColorTabbarInactiveIngame; @@ -786,13 +786,13 @@ int CMenus::Render() ms_ColorTabbarInactive = ms_ColorTabbarInactiveOutgame; ms_ColorTabbarActive = ms_ColorTabbarActiveOutgame; } - + CUIRect TabBar; CUIRect MainView; // some margin around the screen Screen.Margin(10.0f, &Screen); - + static bool s_SoundCheck = false; if(!s_SoundCheck && m_Popup == POPUP_NONE) { @@ -807,14 +807,14 @@ int CMenus::Render() Screen.HSplitTop(24.0f, &TabBar, &MainView); TabBar.VMargin(20.0f, &TabBar); RenderMenubar(TabBar); - + // news is not implemented yet if(g_Config.m_UiPage <= PAGE_NEWS || g_Config.m_UiPage > PAGE_SETTINGS || (Client()->State() == IClient::STATE_OFFLINE && g_Config.m_UiPage >= PAGE_GAME && g_Config.m_UiPage <= PAGE_CALLVOTE)) { ServerBrowser()->Refresh(IServerBrowser::TYPE_INTERNET); g_Config.m_UiPage = PAGE_INTERNET; } - + // render current page if(Client()->State() != IClient::STATE_OFFLINE) { @@ -852,7 +852,7 @@ int CMenus::Render() const char *pExtraText = ""; const char *pButtonText = ""; int ExtraAlign = 0; - + if(m_Popup == POPUP_MESSAGE) { pTitle = m_aMessageTopic; @@ -862,7 +862,7 @@ int CMenus::Render() else if(m_Popup == POPUP_CONNECTING) { pTitle = Localize("Connecting to"); - pExtraText = g_Config.m_UiServerAddress; // TODO: query the client about the address + pExtraText = g_Config.m_UiServerAddress; // TODO: query the client about the address pButtonText = Localize("Abort"); if(Client()->MapDownloadTotalsize() > 0) { @@ -928,22 +928,22 @@ int CMenus::Render() pButtonText = Localize("Ok"); ExtraAlign = -1; } - + CUIRect Box, Part; Box = Screen; Box.VMargin(150.0f/UI()->Scale(), &Box); Box.HMargin(150.0f/UI()->Scale(), &Box); - + // render the box RenderTools()->DrawUIRect(&Box, vec4(0,0,0,0.5f), CUI::CORNER_ALL, 15.0f); - + Box.HSplitTop(20.f/UI()->Scale(), &Part, &Box); Box.HSplitTop(24.f/UI()->Scale(), &Part, &Box); UI()->DoLabelScaled(&Part, pTitle, 24.f, 0); Box.HSplitTop(20.f/UI()->Scale(), &Part, &Box); Box.HSplitTop(24.f/UI()->Scale(), &Part, &Box); Part.VMargin(20.f/UI()->Scale(), &Part); - + if(ExtraAlign == -1) UI()->DoLabelScaled(&Part, pExtraText, 20.f, -1, (int)Part.w); else @@ -982,16 +982,16 @@ int CMenus::Render() else if(m_Popup == POPUP_PASSWORD) { CUIRect Label, TextBox, TryAgain, Abort; - + Box.HSplitBottom(20.f, &Box, &Part); Box.HSplitBottom(24.f, &Box, &Part); Part.VMargin(80.0f, &Part); - + Part.VSplitMid(&Abort, &TryAgain); - + TryAgain.VMargin(20.0f, &TryAgain); Abort.VMargin(20.0f, &Abort); - + static int s_ButtonAbort = 0; if(DoButton_Menu(&s_ButtonAbort, Localize("Abort"), 0, &Abort) || m_EscapePressed) m_Popup = POPUP_NONE; @@ -1001,10 +1001,10 @@ int CMenus::Render() { Client()->Connect(g_Config.m_UiServerAddress); } - + Box.HSplitBottom(60.f, &Box, &Part); Box.HSplitBottom(24.f, &Box, &Part); - + Part.VSplitLeft(60.0f, 0, &Label); Label.VSplitLeft(100.0f, 0, &TextBox); TextBox.VSplitLeft(20.0f, 0, &TextBox); @@ -1055,7 +1055,7 @@ int CMenus::Render() Box.HSplitTop(24.f, &Part, &Box); str_format(aBuf, sizeof(aBuf), "%d/%d KiB (%.1f KiB/s)", Client()->MapDownloadAmount()/1024, Client()->MapDownloadTotalsize()/1024, m_DownloadSpeed/1024.0f); UI()->DoLabel(&Part, aBuf, 20.f, 0, -1); - + // time left const char *pTimeLeftString; int TimeLeft = m_DownloadSpeed > 0.0f ? (Client()->MapDownloadTotalsize()-Client()->MapDownloadAmount())/m_DownloadSpeed : 0.0f; @@ -1103,9 +1103,9 @@ int CMenus::Render() Box.HSplitBottom(20.f, &Box, &Part); Box.HSplitBottom(24.f, &Box, &Part); Part.VMargin(80.0f, &Part); - + Part.VSplitMid(&No, &Yes); - + Yes.VMargin(20.0f, &Yes); No.VMargin(20.0f, &No); @@ -1135,16 +1135,16 @@ int CMenus::Render() else if(m_Popup == POPUP_RENAME_DEMO) { CUIRect Label, TextBox, Ok, Abort; - + Box.HSplitBottom(20.f, &Box, &Part); Box.HSplitBottom(24.f, &Box, &Part); Part.VMargin(80.0f, &Part); - + Part.VSplitMid(&Abort, &Ok); - + Ok.VMargin(20.0f, &Ok); Abort.VMargin(20.0f, &Abort); - + static int s_ButtonAbort = 0; if(DoButton_Menu(&s_ButtonAbort, Localize("Abort"), 0, &Abort) || m_EscapePressed) m_Popup = POPUP_NONE; @@ -1173,10 +1173,10 @@ int CMenus::Render() PopupMessage(Localize("Error"), Localize("Unable to rename the demo"), Localize("Ok")); } } - + Box.HSplitBottom(60.f, &Box, &Part); Box.HSplitBottom(24.f, &Box, &Part); - + Part.VSplitLeft(60.0f, 0, &Label); Label.VSplitLeft(120.0f, 0, &TextBox); TextBox.VSplitLeft(20.0f, 0, &TextBox); @@ -1191,9 +1191,9 @@ int CMenus::Render() Box.HSplitBottom(20.f, &Box, &Part); Box.HSplitBottom(24.f, &Box, &Part); Part.VMargin(80.0f, &Part); - + Part.VSplitMid(&No, &Yes); - + Yes.VMargin(20.0f, &Yes); No.VMargin(20.0f, &No); @@ -1216,18 +1216,18 @@ int CMenus::Render() else if(m_Popup == POPUP_FIRST_LAUNCH) { CUIRect Label, TextBox; - + Box.HSplitBottom(20.f, &Box, &Part); Box.HSplitBottom(24.f, &Box, &Part); Part.VMargin(80.0f, &Part); - + static int s_EnterButton = 0; if(DoButton_Menu(&s_EnterButton, Localize("Enter"), 0, &Part) || m_EnterPressed) m_Popup = POPUP_NONE; - + Box.HSplitBottom(40.f, &Box, &Part); Box.HSplitBottom(24.f, &Box, &Part); - + Part.VSplitLeft(60.0f, 0, &Label); Label.VSplitLeft(100.0f, 0, &TextBox); TextBox.VSplitLeft(20.0f, 0, &TextBox); @@ -1247,7 +1247,7 @@ int CMenus::Render() m_Popup = POPUP_NONE; } } - + return 0; } @@ -1281,24 +1281,24 @@ void CMenus::OnReset() bool CMenus::OnMouseMove(float x, float y) { m_LastInput = time_get(); - + if(!m_MenuActive) return false; - + m_MousePos.x += x; m_MousePos.y += y; if(m_MousePos.x < 0) m_MousePos.x = 0; if(m_MousePos.y < 0) m_MousePos.y = 0; if(m_MousePos.x > Graphics()->ScreenWidth()) m_MousePos.x = Graphics()->ScreenWidth(); if(m_MousePos.y > Graphics()->ScreenHeight()) m_MousePos.y = Graphics()->ScreenHeight(); - + return true; } bool CMenus::OnInput(IInput::CEvent e) { m_LastInput = time_get(); - + // special handle esc and enter for popup purposes if(e.m_Flags&IInput::FLAG_PRESS) { @@ -1309,7 +1309,7 @@ bool CMenus::OnInput(IInput::CEvent e) return true; } } - + if(IsActive()) { if(e.m_Flags&IInput::FLAG_PRESS) @@ -1320,7 +1320,7 @@ bool CMenus::OnInput(IInput::CEvent e) else if(e.m_Key == KEY_DELETE) m_DeletePressed = true; } - + if(m_NumInputEvents < MAX_INPUTEVENTS) m_aInputEvents[m_NumInputEvents++] = e; return true; @@ -1380,13 +1380,13 @@ void CMenus::OnRender() TextRender()->SetCursor(&cursor, 10, 30, 15, TEXTFLAG_RENDER); TextRender()->TextEx(&cursor, "ようこそ - ガイド", -1); - + //Graphics()->TextureSet(-1); Graphics()->QuadsBegin(); Graphics()->QuadsDrawTL(60, 60, 5000, 5000); Graphics()->QuadsEnd(); return;*/ - + if(Client()->State() != IClient::STATE_ONLINE && Client()->State() != IClient::STATE_DEMOPLAYBACK) SetActive(true); @@ -1396,14 +1396,14 @@ void CMenus::OnRender() Graphics()->MapScreen(Screen.x, Screen.y, Screen.w, Screen.h); RenderDemoPlayer(Screen); } - + if(Client()->State() == IClient::STATE_ONLINE && m_pClient->m_ServerMode == m_pClient->SERVERMODE_PUREMOD) { Client()->Disconnect(); SetActive(true); m_Popup = POPUP_PURE; } - + if(!IsActive()) { m_EscapePressed = false; @@ -1412,7 +1412,7 @@ void CMenus::OnRender() m_NumInputEvents = 0; return; } - + // update colors vec3 Rgb = HslToRgb(vec3(g_Config.m_UiColorHue/255.0f, g_Config.m_UiColorSat/255.0f, g_Config.m_UiColorLht/255.0f)); ms_GuiColor = vec4(Rgb.r, Rgb.g, Rgb.b, g_Config.m_UiColorAlpha/255.0f); @@ -1427,18 +1427,18 @@ void CMenus::OnRender() ms_GuiColor.g*ColorIngameScaleI, ms_GuiColor.b*ColorIngameScaleI, ms_GuiColor.a*0.8f); - + ms_ColorTabbarActiveIngame = vec4( ms_GuiColor.r*ColorIngameAcaleA, ms_GuiColor.g*ColorIngameAcaleA, ms_GuiColor.b*ColorIngameAcaleA, ms_GuiColor.a); - + // update the ui CUIRect *pScreen = UI()->Screen(); float mx = (m_MousePos.x/(float)Graphics()->ScreenWidth())*pScreen->w; float my = (m_MousePos.y/(float)Graphics()->ScreenHeight())*pScreen->h; - + int Buttons = 0; if(m_UseMouseButtons) { @@ -1446,9 +1446,9 @@ void CMenus::OnRender() if(Input()->KeyPressed(KEY_MOUSE_2)) Buttons |= 2; if(Input()->KeyPressed(KEY_MOUSE_3)) Buttons |= 4; } - + UI()->Update(mx,my,mx*3.0f,my*3.0f,Buttons); - + // render if(Client()->State() != IClient::STATE_DEMOPLAYBACK) Render(); @@ -1510,7 +1510,7 @@ void CMenus::RenderBackground() IGraphics::CQuadItem QuadItem(0, 0, sw, sh); Graphics()->QuadsDrawTL(&QuadItem, 1); Graphics()->QuadsEnd(); - + // render the tiles Graphics()->TextureSet(-1); Graphics()->QuadsBegin(); @@ -1533,7 +1533,7 @@ void CMenus::RenderBackground() Graphics()->QuadsDrawTL(&QuadItem, 1); Graphics()->QuadsEnd(); - // restore screen - {CUIRect Screen = *UI()->Screen(); - Graphics()->MapScreen(Screen.x, Screen.y, Screen.w, Screen.h);} + // restore screen + {CUIRect Screen = *UI()->Screen(); + Graphics()->MapScreen(Screen.x, Screen.y, Screen.w, Screen.h);} } diff --git a/src/game/client/components/menus.h b/src/game/client/components/menus.h index 11047a0b..51b8a1f8 100644 --- a/src/game/client/components/menus.h +++ b/src/game/client/components/menus.h @@ -25,7 +25,7 @@ public: }; class CMenus : public CComponent -{ +{ static vec4 ms_GuiColor; static vec4 ms_ColorTabbarInactiveOutgame; static vec4 ms_ColorTabbarActiveOutgame; @@ -33,7 +33,7 @@ class CMenus : public CComponent static vec4 ms_ColorTabbarActiveIngame; static vec4 ms_ColorTabbarInactive; static vec4 ms_ColorTabbarActive; - + vec4 ButtonColorMul(const void *pID); @@ -58,7 +58,7 @@ class CMenus : public CComponent //static void ui_draw_browse_icon(int what, const CUIRect *r); //static void ui_draw_grid_header(const void *id, const char *text, int checked, const CUIRect *r, const void *extra); - + /*static void ui_draw_checkbox_common(const void *id, const char *text, const char *boxtext, const CUIRect *r, const void *extra); static void ui_draw_checkbox(const void *id, const char *text, int checked, const CUIRect *r, const void *extra); static void ui_draw_checkbox_number(const void *id, const char *text, int checked, const CUIRect *r, const void *extra); @@ -81,13 +81,13 @@ class CMenus : public CComponent CUIRect m_Rect; CUIRect m_HitRect; }; - + void UiDoListboxStart(const void *pID, const CUIRect *pRect, float RowHeight, const char *pTitle, const char *pBottomText, int NumItems, - int ItemsPerRow, int SelectedIndex, float ScrollValue); + int ItemsPerRow, int SelectedIndex, float ScrollValue); CListboxItem UiDoListboxNextItem(const void *pID, bool Selected = false); CListboxItem UiDoListboxNextRow(); int UiDoListboxEnd(float *pScrollValue, bool *pItemActivated); - + //static void demolist_listdir_callback(const char *name, int is_dir, void *user); //static void demolist_list_callback(const CUIRect *rect, int index, void *user); @@ -105,7 +105,7 @@ class CMenus : public CComponent POPUP_REMOVE_FRIEND, POPUP_SOUNDERROR, POPUP_PASSWORD, - POPUP_QUIT, + POPUP_QUIT, }; enum @@ -129,36 +129,36 @@ class CMenus : public CComponent bool m_MenuActive; bool m_UseMouseButtons; vec2 m_MousePos; - + int64 m_LastInput; // loading int m_LoadCurrent; int m_LoadTotal; - + // char m_aMessageTopic[512]; char m_aMessageBody[512]; char m_aMessageButton[512]; - + void PopupMessage(const char *pTopic, const char *pBody, const char *pButton); - // TODO: this is a bit ugly but.. well.. yeah + // TODO: this is a bit ugly but.. well.. yeah enum { MAX_INPUTEVENTS = 32 }; static IInput::CEvent m_aInputEvents[MAX_INPUTEVENTS]; static int m_NumInputEvents; - + // some settings static float ms_ButtonHeight; static float ms_ListheaderHeight; static float ms_FontmodHeight; - + // for settings bool m_NeedRestartGraphics; bool m_NeedRestartSound; bool m_NeedSendinfo; int m_SettingPlayerPage; - + // bool m_EscapePressed; bool m_EnterPressed; @@ -168,12 +168,12 @@ class CMenus : public CComponent int64 m_DownloadLastCheckTime; int m_DownloadLastCheckSize; float m_DownloadSpeed; - + // for call vote int m_CallvoteSelectedOption; int m_CallvoteSelectedPlayer; char m_aCallvoteReason[VOTE_REASON_LENGTH]; - + // demo struct CDemoItem { @@ -181,40 +181,40 @@ class CMenus : public CComponent char m_aName[128]; bool m_IsDir; int m_StorageType; - + bool m_InfosLoaded; bool m_Valid; CDemoHeader m_Info; - + bool operator<(const CDemoItem &Other) { return !str_comp(m_aFilename, "..") ? true : !str_comp(Other.m_aFilename, "..") ? false : m_IsDir && !Other.m_IsDir ? true : !m_IsDir && Other.m_IsDir ? false : str_comp_filenames(m_aFilename, Other.m_aFilename) < 0; } }; - + sorted_array<CDemoItem> m_lDemos; char m_aCurrentDemoFolder[256]; char m_aCurrentDemoFile[64]; int m_DemolistSelectedIndex; bool m_DemolistSelectedIsDir; int m_DemolistStorageType; - + void DemolistOnUpdate(bool Reset); void DemolistPopulate(); static int DemolistFetchCallback(const char *pName, int IsDir, int StorageType, void *pUser); int m_FriendlistSelectedIndex; - + // found in menus.cpp int Render(); //void render_background(); //void render_loading(float percent); int RenderMenubar(CUIRect r); void RenderNews(CUIRect MainView); - + // found in menus_demo.cpp void RenderDemoPlayer(CUIRect MainView); void RenderDemoList(CUIRect MainView); - + // found in menus_ingame.cpp void RenderGame(CUIRect MainView); void RenderPlayers(CUIRect MainView); @@ -222,7 +222,7 @@ class CMenus : public CComponent void RenderServerControl(CUIRect MainView); void RenderServerControlKick(CUIRect MainView, bool FilterSpectators); void RenderServerControlServer(CUIRect MainView); - + // found in menus_browser.cpp int m_SelectedIndex; void RenderServerbrowserServerList(CUIRect View); @@ -231,7 +231,7 @@ class CMenus : public CComponent void RenderServerbrowserFriends(CUIRect View); void RenderServerbrowser(CUIRect MainView); static void ConchainServerbrowserUpdate(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData); - + // found in menus_settings.cpp void RenderLanguageSelection(CUIRect MainView); void RenderSettingsGeneral(CUIRect MainView); @@ -241,7 +241,7 @@ class CMenus : public CComponent void RenderSettingsGraphics(CUIRect MainView); void RenderSettingsSound(CUIRect MainView); void RenderSettings(CUIRect MainView); - + void SetActive(bool Active); public: void RenderBackground(); @@ -249,7 +249,7 @@ public: void UseMouseButtons(bool Use) { m_UseMouseButtons = Use; } static CMenusKeyBinder m_Binder; - + CMenus(); void RenderLoading(); diff --git a/src/game/client/components/menus_browser.cpp b/src/game/client/components/menus_browser.cpp index b9e61401..3ab02db8 100644 --- a/src/game/client/components/menus_browser.cpp +++ b/src/game/client/components/menus_browser.cpp @@ -65,7 +65,7 @@ void CMenus::RenderServerbrowserServerList(CUIRect View) {COL_FLAG_LOCK, -1, " ", -1, 14.0f, 0, {0}, {0}}, {COL_FLAG_PURE, -1, " ", -1, 14.0f, 0, {0}, {0}}, {COL_FLAG_FAV, -1, " ", -1, 14.0f, 0, {0}, {0}}, - {COL_NAME, IServerBrowser::SORT_NAME, "Name", 0, 300.0f, 0, {0}, {0}}, // Localize - these strings are localized within CLocConstString + {COL_NAME, IServerBrowser::SORT_NAME, "Name", 0, 300.0f, 0, {0}, {0}}, // Localize - these strings are localized within CLocConstString {COL_GAMETYPE, IServerBrowser::SORT_GAMETYPE, "Type", 1, 50.0f, 0, {0}, {0}}, {COL_MAP, IServerBrowser::SORT_MAP, "Map", 1, 100.0f, 0, {0}, {0}}, {COL_PLAYERS, IServerBrowser::SORT_NUMPLAYERS, "Players", 1, 60.0f, 0, {0}, {0}}, @@ -161,8 +161,8 @@ void CMenus::RenderServerbrowserServerList(CUIRect View) } else ScrollNum = 0; - - if(m_SelectedIndex > -1) + + if(m_SelectedIndex > -1) { for(int i = 0; i < m_NumInputEvents; i++) { @@ -174,10 +174,10 @@ void CMenus::RenderServerbrowserServerList(CUIRect View) } if(NewIndex > -1 && NewIndex < NumServers) { - //scroll - float IndexY = View.y - s_ScrollValue*ScrollNum*s_aCols[0].m_Rect.h + NewIndex*s_aCols[0].m_Rect.h; + //scroll + float IndexY = View.y - s_ScrollValue*ScrollNum*s_aCols[0].m_Rect.h + NewIndex*s_aCols[0].m_Rect.h; int Scroll = View.y > IndexY ? -1 : View.y+View.h < IndexY+s_aCols[0].m_Rect.h ? 1 : 0; - if(Scroll) + if(Scroll) { if(Scroll < 0) { @@ -192,15 +192,15 @@ void CMenus::RenderServerbrowserServerList(CUIRect View) } m_SelectedIndex = NewIndex; - + const CServerInfo *pItem = ServerBrowser()->SortedGet(m_SelectedIndex); str_copy(g_Config.m_UiServerAddress, pItem->m_aAddress, sizeof(g_Config.m_UiServerAddress)); } } } - - if(s_ScrollValue < 0) s_ScrollValue = 0; - if(s_ScrollValue > 1) s_ScrollValue = 1; + + if(s_ScrollValue < 0) s_ScrollValue = 0; + if(s_ScrollValue > 1) s_ScrollValue = 1; // set clipping UI()->ClipEnable(&View); @@ -224,7 +224,7 @@ void CMenus::RenderServerbrowserServerList(CUIRect View) int ItemIndex = i; const CServerInfo *pItem = ServerBrowser()->SortedGet(ItemIndex); CUIRect Row; - CUIRect SelectHitBox; + CUIRect SelectHitBox; int Selected = str_comp(pItem->m_aAddress, g_Config.m_UiServerAddress) == 0; //selected_index==ItemIndex; @@ -422,7 +422,7 @@ void CMenus::RenderServerbrowserServerList(CUIRect View) Client()->ServerBrowserUpdate(); } } - + // render status char aBuf[128]; if(ServerBrowser()->IsRefreshing()) @@ -481,7 +481,7 @@ void CMenus::RenderServerbrowserFilters(CUIRect View) ServerFilter.HSplitTop(20.0f, &Button, &ServerFilter); if (DoButton_CheckBox((char *)&g_Config.m_BrFilterPureMap, Localize("Standard map"), g_Config.m_BrFilterPureMap, &Button)) g_Config.m_BrFilterPureMap ^= 1; - + ServerFilter.HSplitTop(5.0f, 0, &ServerFilter); ServerFilter.HSplitTop(19.0f, &Button, &ServerFilter); @@ -496,9 +496,9 @@ void CMenus::RenderServerbrowserFilters(CUIRect View) ServerFilter.HSplitTop(19.0f, &Button, &ServerFilter); CUIRect EditBox; Button.VSplitRight(60.0f, &Button, &EditBox); - + UI()->DoLabelScaled(&Button, Localize("Maximum ping:"), FontSize, -1); - + char aBuf[5]; str_format(aBuf, sizeof(aBuf), "%d", g_Config.m_BrFilterPing); static float Offset = 0.0f; @@ -510,7 +510,7 @@ void CMenus::RenderServerbrowserFilters(CUIRect View) ServerFilter.HSplitTop(3.0f, 0, &ServerFilter); ServerFilter.HSplitTop(19.0f, &Button, &ServerFilter); UI()->DoLabelScaled(&Button, Localize("Server address:"), FontSize, -1); - Button.VSplitRight(60.0f, 0, &Button); + Button.VSplitRight(60.0f, 0, &Button); static float OffsetAddr = 0.0f; if(DoEditBox(&g_Config.m_BrFilterServerAddress, &Button, g_Config.m_BrFilterServerAddress, sizeof(g_Config.m_BrFilterServerAddress), FontSize, &OffsetAddr)) Client()->ServerBrowserUpdate(); @@ -639,7 +639,7 @@ void CMenus::RenderServerbrowserServerDetail(CUIRect View) Cursor.m_LineWidth = Score.w; TextRender()->TextEx(&Cursor, aTemp, -1); } - + // name TextRender()->SetCursor(&Cursor, Name.x, Name.y, FontSize-2, TEXTFLAG_RENDER|TEXTFLAG_STOP_AT_END); Cursor.m_LineWidth = Name.w; @@ -716,12 +716,12 @@ void CMenus::RenderServerbrowserFriends(CUIRect View) static int s_FriendList = 0; static float s_ScrollValue = 0; UiDoListboxStart(&s_FriendList, &List, 40.0f, "", "", m_pClient->Friends()->NumFriends(), 1, m_FriendlistSelectedIndex, s_ScrollValue); - + for(int i = 0; i < m_pClient->Friends()->NumFriends(); ++i) { const CFriendInfo *pFriend = m_pClient->Friends()->GetFriend(i); CListboxItem Item = UiDoListboxNextItem(pFriend); - + if(Item.m_Visible) { Item.m_Rect.Margin(2.5f, &Item.m_Rect); @@ -732,7 +732,7 @@ void CMenus::RenderServerbrowserFriends(CUIRect View) UI()->DoLabelScaled(&Button, pFriend->m_aClan, FontSize, -1); } } - + m_FriendlistSelectedIndex = UiDoListboxEnd(&s_ScrollValue, 0); ServerFriends.HSplitTop(2.5f, 0, &ServerFriends); @@ -780,14 +780,14 @@ void CMenus::RenderServerbrowserFriends(CUIRect View) void CMenus::RenderServerbrowser(CUIRect MainView) { /* - +-----------------+ +------+ - | | | | - | | | tool | - | server list | | box | - | | | | - | | | | - +-----------------+ | | - status box tab +------+ + +-----------------+ +-------+ + | | | | + | | | tool | + | server list | | box | + | | | | + | | | | + +-----------------+ | | + status box tab +-------+ */ CUIRect ServerList, ToolBox, StatusBox, TabBar; @@ -843,7 +843,7 @@ void CMenus::RenderServerbrowser(CUIRect MainView) // tool box { RenderTools()->DrawUIRect(&ToolBox, vec4(0.0f, 0.0f, 0.0f, 0.15f), CUI::CORNER_T, 4.0f); - + if(ToolboxPage == 0) RenderServerbrowserFilters(ToolBox); @@ -877,7 +877,7 @@ void CMenus::RenderServerbrowser(CUIRect MainView) ButtonArea.VSplitRight(150.0f, 0, &ButtonArea); ButtonArea.HSplitTop(20.0f, &Button, &ButtonArea); Button.VMargin(2.0f, &Button); - + static int s_RefreshButton = 0; if(DoButton_Menu(&s_RefreshButton, Localize("Refresh"), 0, &Button)) { @@ -892,7 +892,7 @@ void CMenus::RenderServerbrowser(CUIRect MainView) ButtonArea.HSplitTop(5.0f, 0, &ButtonArea); ButtonArea.HSplitTop(20.0f, &Button, &ButtonArea); Button.VMargin(2.0f, &Button); - + static int s_JoinButton = 0; if(DoButton_Menu(&s_JoinButton, Localize("Connect"), 0, &Button) || m_EnterPressed) { diff --git a/src/game/client/components/menus_demo.cpp b/src/game/client/components/menus_demo.cpp index 7e73c3eb..7fcfab99 100644 --- a/src/game/client/components/menus_demo.cpp +++ b/src/game/client/components/menus_demo.cpp @@ -28,7 +28,7 @@ int CMenus::DoButton_DemoPlayer(const void *pID, const char *pText, int Checked, int CMenus::DoButton_Sprite(const void *pID, int ImageID, int SpriteID, int Checked, const CUIRect *pRect, int Corners) { - RenderTools()->DrawUIRect(pRect, Checked ? vec4(1.0f, 1.0f, 1.0f, 0.10f) : vec4(1.0f, 1.0f, 1.0f, 0.5f)*ButtonColorMul(pID), Corners, 5.0f); + RenderTools()->DrawUIRect(pRect, Checked ? vec4(1.0f, 1.0f, 1.0f, 0.10f) : vec4(1.0f, 1.0f, 1.0f, 0.5f)*ButtonColorMul(pID), Corners, 5.0f); Graphics()->TextureSet(g_pData->m_aImages[ImageID].m_Id); Graphics()->QuadsBegin(); if(!Checked) @@ -37,38 +37,38 @@ int CMenus::DoButton_Sprite(const void *pID, int ImageID, int SpriteID, int Chec IGraphics::CQuadItem QuadItem(pRect->x, pRect->y, pRect->w, pRect->h); Graphics()->QuadsDrawTL(&QuadItem, 1); Graphics()->QuadsEnd(); - + return UI()->DoButtonLogic(pID, "", Checked, pRect); } void CMenus::RenderDemoPlayer(CUIRect MainView) { const IDemoPlayer::CInfo *pInfo = DemoPlayer()->BaseInfo(); - + const float SeekBarHeight = 15.0f; const float ButtonbarHeight = 20.0f; const float NameBarHeight = 20.0f; const float Margins = 5.0f; float TotalHeight; - + if(m_MenuActive) TotalHeight = SeekBarHeight+ButtonbarHeight+NameBarHeight+Margins*3; else TotalHeight = SeekBarHeight+Margins*2; - + MainView.HSplitBottom(TotalHeight, 0, &MainView); MainView.VSplitLeft(50.0f, 0, &MainView); MainView.VSplitRight(450.0f, &MainView, 0); - + RenderTools()->DrawUIRect(&MainView, ms_ColorTabbarActive, CUI::CORNER_T, 10.0f); - + MainView.Margin(5.0f, &MainView); - + CUIRect SeekBar, ButtonBar, NameBar; - + int CurrentTick = pInfo->m_CurrentTick - pInfo->m_FirstTick; int TotalTicks = pInfo->m_LastTick - pInfo->m_FirstTick; - + if(m_MenuActive) { MainView.HSplitTop(SeekBarHeight, &SeekBar, &ButtonBar); @@ -84,24 +84,24 @@ void CMenus::RenderDemoPlayer(CUIRect MainView) static int s_SeekBarID = 0; void *id = &s_SeekBarID; char aBuffer[128]; - + RenderTools()->DrawUIRect(&SeekBar, vec4(0,0,0,0.5f), CUI::CORNER_ALL, 5.0f); - + float Amount = CurrentTick/(float)TotalTicks; - + CUIRect FilledBar = SeekBar; FilledBar.w = 10.0f + (FilledBar.w-10.0f)*Amount; - + RenderTools()->DrawUIRect(&FilledBar, vec4(1,1,1,0.5f), CUI::CORNER_ALL, 5.0f); - + str_format(aBuffer, sizeof(aBuffer), "%d:%02d / %d:%02d", CurrentTick/SERVER_TICK_SPEED/60, (CurrentTick/SERVER_TICK_SPEED)%60, TotalTicks/SERVER_TICK_SPEED/60, (TotalTicks/SERVER_TICK_SPEED)%60); UI()->DoLabel(&SeekBar, aBuffer, SeekBar.h*0.70f, 0); // do the logic - int Inside = UI()->MouseInside(&SeekBar); - + int Inside = UI()->MouseInside(&SeekBar); + if(UI()->ActiveItem() == id) { if(!UI()->MouseButton(0)) @@ -124,11 +124,11 @@ void CMenus::RenderDemoPlayer(CUIRect MainView) { if(UI()->MouseButton(0)) UI()->SetActiveItem(id); - } - + } + if(Inside) UI()->SetHotItem(id); - } + } if(CurrentTick == TotalTicks) { @@ -143,7 +143,7 @@ void CMenus::RenderDemoPlayer(CUIRect MainView) { // do buttons CUIRect Button; - + // combined play and pause button ButtonBar.VSplitLeft(ButtonbarHeight, &Button, &ButtonBar); static int s_PlayPauseButton = 0; @@ -157,16 +157,16 @@ void CMenus::RenderDemoPlayer(CUIRect MainView) if(DoButton_Sprite(&s_PlayPauseButton, IMAGE_DEMOBUTTONS, SPRITE_DEMOBUTTON_PLAY, false, &Button, CUI::CORNER_ALL)) DemoPlayer()->Unpause(); } - + // stop button - + ButtonBar.VSplitLeft(Margins, 0, &ButtonBar); ButtonBar.VSplitLeft(ButtonbarHeight, &Button, &ButtonBar); static int s_ResetButton = 0; if(DoButton_Sprite(&s_ResetButton, IMAGE_DEMOBUTTONS, SPRITE_DEMOBUTTON_STOP, false, &Button, CUI::CORNER_ALL)) { m_pClient->OnReset(); - DemoPlayer()->Pause(); + DemoPlayer()->Pause(); DemoPlayer()->SetPos(0); } @@ -176,7 +176,7 @@ void CMenus::RenderDemoPlayer(CUIRect MainView) static int s_SlowDownButton = 0; if(DoButton_Sprite(&s_SlowDownButton, IMAGE_DEMOBUTTONS, SPRITE_DEMOBUTTON_SLOWER, 0, &Button, CUI::CORNER_ALL) || Input()->KeyPresses(KEY_MOUSE_WHEEL_DOWN)) DecreaseDemoSpeed = true; - + // fastforward ButtonBar.VSplitLeft(Margins, 0, &ButtonBar); ButtonBar.VSplitLeft(ButtonbarHeight, &Button, &ButtonBar); @@ -250,15 +250,15 @@ void CMenus::UiDoListboxStart(const void *pID, const CUIRect *pRect, float RowHe CUIRect Scroll, Row; CUIRect View = *pRect; CUIRect Header, Footer; - + // draw header View.HSplitTop(ms_ListheaderHeight, &Header, &View); - RenderTools()->DrawUIRect(&Header, vec4(1,1,1,0.25f), CUI::CORNER_T, 5.0f); + RenderTools()->DrawUIRect(&Header, vec4(1,1,1,0.25f), CUI::CORNER_T, 5.0f); UI()->DoLabel(&Header, pTitle, Header.h*ms_FontmodHeight, 0); // draw footers View.HSplitBottom(ms_ListheaderHeight, &View, &Footer); - RenderTools()->DrawUIRect(&Footer, vec4(1,1,1,0.25f), CUI::CORNER_B, 5.0f); + RenderTools()->DrawUIRect(&Footer, vec4(1,1,1,0.25f), CUI::CORNER_B, 5.0f); Footer.VSplitLeft(10.0f, 0, &Footer); UI()->DoLabel(&Footer, pBottomText, Header.h*ms_FontmodHeight, 0); @@ -268,7 +268,7 @@ void CMenus::UiDoListboxStart(const void *pID, const CUIRect *pRect, float RowHe // prepare the scroll View.VSplitRight(15, &View, &Scroll); - // setup the variables + // setup the variables gs_ListBoxOriginalView = View; gs_ListBoxSelectedIndex = SelectedIndex; gs_ListBoxNewSelected = SelectedIndex; @@ -282,7 +282,7 @@ void CMenus::UiDoListboxStart(const void *pID, const CUIRect *pRect, float RowHe // do the scrollbar View.HSplitTop(gs_ListBoxRowHeight, &Row, 0); - + int NumViewable = (int)(gs_ListBoxOriginalView.h/Row.h) + 1; int Num = (NumItems+gs_ListBoxItemsPerRow-1)/gs_ListBoxItemsPerRow-NumViewable+1; if(Num < 0) @@ -293,14 +293,14 @@ void CMenus::UiDoListboxStart(const void *pID, const CUIRect *pRect, float RowHe gs_ListBoxScrollValue -= 3.0f/Num; if(Input()->KeyPresses(KEY_MOUSE_WHEEL_DOWN)) gs_ListBoxScrollValue += 3.0f/Num; - + if(gs_ListBoxScrollValue < 0.0f) gs_ListBoxScrollValue = 0.0f; if(gs_ListBoxScrollValue > 1.0f) gs_ListBoxScrollValue = 1.0f; } - + Scroll.HMargin(5.0f, &Scroll); gs_ListBoxScrollValue = DoScrollbarV(pID, &Scroll, gs_ListBoxScrollValue); - + // the list gs_ListBoxView = gs_ListBoxOriginalView; gs_ListBoxView.VMargin(5.0f, &gs_ListBoxView); @@ -319,24 +319,24 @@ CMenus::CListboxItem CMenus::UiDoListboxNextRow() Item.m_Visible = 1; //item.rect = row; - + Item.m_HitRect = Item.m_Rect; - + //CUIRect select_hit_box = item.rect; if(gs_ListBoxSelectedIndex == gs_ListBoxItemIndex) Item.m_Selected = 1; - + // make sure that only those in view can be selected if(Item.m_Rect.y+Item.m_Rect.h > gs_ListBoxOriginalView.y) { - + if(Item.m_HitRect.y < Item.m_HitRect.y) // clip the selection { Item.m_HitRect.h -= gs_ListBoxOriginalView.y-Item.m_HitRect.y; Item.m_HitRect.y = gs_ListBoxOriginalView.y; } - + } else Item.m_Visible = 0; @@ -344,7 +344,7 @@ CMenus::CListboxItem CMenus::UiDoListboxNextRow() // check if we need to do more if(Item.m_Rect.y > gs_ListBoxOriginalView.y+gs_ListBoxOriginalView.h) Item.m_Visible = 0; - + gs_ListBoxItemIndex++; return Item; } @@ -358,12 +358,12 @@ CMenus::CListboxItem CMenus::UiDoListboxNextItem(const void *pId, bool Selected) gs_ListBoxNewSelected = ThisItemIndex; gs_ListBoxSelectedIndex = ThisItemIndex; } - + CListboxItem Item = UiDoListboxNextRow(); if(Item.m_Visible && UI()->DoButtonLogic(pId, "", gs_ListBoxSelectedIndex == gs_ListBoxItemIndex, &Item.m_HitRect)) gs_ListBoxNewSelected = ThisItemIndex; - + // process input, regard selected index if(gs_ListBoxSelectedIndex == ThisItemIndex) { @@ -377,7 +377,7 @@ CMenus::CListboxItem CMenus::UiDoListboxNextItem(const void *pId, bool Selected) UI()->SetActiveItem(0); } else - { + { for(int i = 0; i < m_NumInputEvents; i++) { int NewIndex = -1; @@ -410,18 +410,18 @@ CMenus::CListboxItem CMenus::UiDoListboxNextItem(const void *pId, bool Selected) if(gs_ListBoxScrollValue < 0.0f) gs_ListBoxScrollValue = 0.0f; if(gs_ListBoxScrollValue > 1.0f) gs_ListBoxScrollValue = 1.0f; } - + gs_ListBoxNewSelected = NewIndex; } } } } - + //selected_index = i; CUIRect r = Item.m_Rect; r.Margin(1.5f, &r); RenderTools()->DrawUIRect(&r, vec4(1,1,1,0.5f), CUI::CORNER_ALL, 4.0f); - } + } return Item; } @@ -444,7 +444,7 @@ int CMenus::DemolistFetchCallback(const char *pName, int IsDir, int StorageType, (pName[1] == '.' && pName[2] == 0 && !str_comp(pSelf->m_aCurrentDemoFolder, "demos")))) || (!IsDir && (Length < 5 || str_comp(pName+Length-5, ".demo")))) return 0; - + CDemoItem Item; str_copy(Item.m_aFilename, pName, sizeof(Item.m_aFilename)); if(IsDir) @@ -513,11 +513,11 @@ void CMenus::RenderDemoList(CUIRect MainView) str_copy(aFooterLabel, Localize("Demo details"), sizeof(aFooterLabel)); } } - + // render background RenderTools()->DrawUIRect(&MainView, ms_ColorTabbarActive, CUI::CORNER_ALL, 10.0f); MainView.Margin(10.0f, &MainView); - + CUIRect ButtonBar, RefreshRect, PlayRect, DeleteRect, RenameRect, FileIcon, ListBox; MainView.HSplitBottom(ms_ButtonHeight+5.0f, &MainView, &ButtonBar); ButtonBar.HSplitTop(5.0f, 0, &ButtonBar); @@ -595,7 +595,7 @@ void CMenus::RenderDemoList(CUIRect MainView) UI()->DoLabelScaled(&Left, Localize("Netversion:"), 14.0f, -1); UI()->DoLabelScaled(&Right, m_lDemos[m_DemolistSelectedIndex].m_Info.m_aNetversion, 14.0f, -1); } - + static int s_DemoListId = 0; static float s_ScrollValue = 0; UiDoListboxStart(&s_DemoListId, &ListBox, 17.0f, Localize("Demos"), aFooterLabel, m_lDemos.size(), 1, m_DemolistSelectedIndex, s_ScrollValue); @@ -613,7 +613,7 @@ void CMenus::RenderDemoList(CUIRect MainView) bool Activated = false; m_DemolistSelectedIndex = UiDoListboxEnd(&s_ScrollValue, &Activated); DemolistOnUpdate(false); - + static int s_RefreshButton = 0; if(DoButton_Menu(&s_RefreshButton, Localize("Refresh"), 0, &RefreshRect)) { @@ -655,7 +655,7 @@ void CMenus::RenderDemoList(CUIRect MainView) } } } - + if(!m_DemolistSelectedIsDir) { static int s_DeleteButton = 0; diff --git a/src/game/client/components/menus_ingame.cpp b/src/game/client/components/menus_ingame.cpp index 4737f38d..33aaa14f 100644 --- a/src/game/client/components/menus_ingame.cpp +++ b/src/game/client/components/menus_ingame.cpp @@ -28,12 +28,12 @@ void CMenus::RenderGame(CUIRect MainView) CUIRect Button, ButtonBar; MainView.HSplitTop(45.0f, &ButtonBar, &MainView); RenderTools()->DrawUIRect(&ButtonBar, ms_ColorTabbarActive, CUI::CORNER_ALL, 10.0f); - + // button bar ButtonBar.HSplitTop(10.0f, 0, &ButtonBar); ButtonBar.HSplitTop(25.0f, &ButtonBar, 0); ButtonBar.VMargin(10.0f, &ButtonBar); - + ButtonBar.VSplitRight(120.0f, &ButtonBar, &Button); static int s_DisconnectButton = 0; if(DoButton_Menu(&s_DisconnectButton, Localize("Disconnect"), 0, &Button)) @@ -52,7 +52,7 @@ void CMenus::RenderGame(CUIRect MainView) SetActive(false); } } - + if(m_pClient->m_Snap.m_pGameInfoObj->m_GameFlags & GAMEFLAG_TEAMS) { if(m_pClient->m_Snap.m_pLocalInfo->m_Team != TEAM_RED) @@ -193,7 +193,7 @@ void CMenus::RenderPlayers(CUIRect MainView) else m_pClient->Friends()->AddFriend(m_pClient->m_aClients[i].m_aName, m_pClient->m_aClients[i].m_aClan); } - + /* CUIRect bars; votearea.HSplitTop(10.0f, 0, &votearea); @@ -220,7 +220,7 @@ void CMenus::RenderPlayers(CUIRect MainView) static int no_button = 0; if(UI()->DoButton(&no_button, "No", 0, &button, ui_draw_menu_button, 0)) gameclient.voting->vote(-1); - + // do time left votearea.VSplitRight(50.0f, &votearea, &button); char buf[256]; @@ -236,10 +236,10 @@ void CMenus::RenderPlayers(CUIRect MainView) // do bars bars.HSplitTop(10.0f, 0, &bars); bars.HMargin(5.0f, &bars); - + gameclient.voting->render_bars(bars, true); - } + } else { UI()->DoLabel(&votearea, "No vote in progress", 18.0f, -1); @@ -254,33 +254,33 @@ void CMenus::RenderServerInfo(CUIRect MainView) // fetch server info CServerInfo CurrentServerInfo; Client()->GetServerInfo(&CurrentServerInfo); - + // render background RenderTools()->DrawUIRect(&MainView, ms_ColorTabbarActive, CUI::CORNER_ALL, 10.0f); - + CUIRect View, ServerInfo, GameInfo, Motd; - + float x = 0.0f; float y = 0.0f; - + char aBuf[1024]; - + // set view to use for all sub-modules MainView.Margin(10.0f, &View); - + // serverinfo View.HSplitTop(View.h/2/UI()->Scale()-5.0f, &ServerInfo, &Motd); ServerInfo.VSplitLeft(View.w/2/UI()->Scale()-5.0f, &ServerInfo, &GameInfo); RenderTools()->DrawUIRect(&ServerInfo, vec4(1,1,1,0.25f), CUI::CORNER_ALL, 10.0f); - + ServerInfo.Margin(5.0f, &ServerInfo); - + x = 5.0f; y = 0.0f; - + TextRender()->Text(0, ServerInfo.x+x, ServerInfo.y+y, 32, Localize("Server info"), 250); y += 32.0f+5.0f; - + mem_zero(aBuf, sizeof(aBuf)); str_format( aBuf, @@ -296,9 +296,9 @@ void CMenus::RenderServerInfo(CUIRect MainView) Localize("Version"), CurrentServerInfo.m_aVersion, Localize("Password"), CurrentServerInfo.m_Flags &1 ? Localize("Yes") : Localize("No") ); - + TextRender()->Text(0, ServerInfo.x+x, ServerInfo.y+y, 20, aBuf, 250); - + { CUIRect Button; int IsFavorite = ServerBrowser()->IsFavorite(CurrentServerInfo.m_NetAddr); @@ -312,19 +312,19 @@ void CMenus::RenderServerInfo(CUIRect MainView) ServerBrowser()->AddFavorite(CurrentServerInfo.m_NetAddr); } } - + // gameinfo GameInfo.VSplitLeft(10.0f, 0x0, &GameInfo); RenderTools()->DrawUIRect(&GameInfo, vec4(1,1,1,0.25f), CUI::CORNER_ALL, 10.0f); - + GameInfo.Margin(5.0f, &GameInfo); - + x = 5.0f; y = 0.0f; - + TextRender()->Text(0, GameInfo.x+x, GameInfo.y+y, 32, Localize("Game info"), 250); y += 32.0f+5.0f; - + if(m_pClient->m_Snap.m_pGameInfoObj) { mem_zero(aBuf, sizeof(aBuf)); @@ -346,7 +346,7 @@ void CMenus::RenderServerInfo(CUIRect MainView) ); TextRender()->Text(0, GameInfo.x+x, GameInfo.y+y, 20, aBuf, 250); } - + // motd Motd.HSplitTop(10.0f, 0, &Motd); RenderTools()->DrawUIRect(&Motd, vec4(1,1,1,0.25f), CUI::CORNER_ALL, 10.0f); @@ -364,15 +364,15 @@ void CMenus::RenderServerControlServer(CUIRect MainView) static float s_ScrollValue = 0; CUIRect List = MainView; UiDoListboxStart(&s_VoteList, &List, 24.0f, "", "", m_pClient->m_pVoting->m_NumVoteOptions, 1, m_CallvoteSelectedOption, s_ScrollValue); - + for(CVoteOptionClient *pOption = m_pClient->m_pVoting->m_pFirst; pOption; pOption = pOption->m_pNext) { CListboxItem Item = UiDoListboxNextItem(pOption); - + if(Item.m_Visible) UI()->DoLabelScaled(&Item.m_Rect, pOption->m_aDescription, 16.0f, -1); } - + m_CallvoteSelectedOption = UiDoListboxEnd(&s_ScrollValue, 0); } @@ -396,11 +396,11 @@ void CMenus::RenderServerControlKick(CUIRect MainView, bool FilterSpectators) static float s_ScrollValue = 0; CUIRect List = MainView; UiDoListboxStart(&s_VoteList, &List, 24.0f, "", "", NumOptions, 1, Selected, s_ScrollValue); - + for(int i = 0; i < NumOptions; i++) { CListboxItem Item = UiDoListboxNextItem(&aPlayerIDs[i]); - + if(Item.m_Visible) { CTeeRenderInfo Info = m_pClient->m_aClients[aPlayerIDs[i]].m_RenderInfo; @@ -411,7 +411,7 @@ void CMenus::RenderServerControlKick(CUIRect MainView, bool FilterSpectators) UI()->DoLabelScaled(&Item.m_Rect, m_pClient->m_aClients[aPlayerIDs[i]].m_aName, 16.0f, -1); } } - + Selected = UiDoListboxEnd(&s_ScrollValue, 0); m_CallvoteSelectedPlayer = Selected != -1 ? aPlayerIDs[Selected] : -1; } @@ -419,7 +419,7 @@ void CMenus::RenderServerControlKick(CUIRect MainView, bool FilterSpectators) void CMenus::RenderServerControl(CUIRect MainView) { static int s_ControlPage = 0; - + // render background CUIRect Bottom, Extended, TabBar, Button; MainView.HSplitTop(20.0f, &Bottom, &MainView); @@ -461,7 +461,7 @@ void CMenus::RenderServerControl(CUIRect MainView) { CUIRect Button; Bottom.VSplitRight(120.0f, &Bottom, &Button); - + static int s_CallVoteButton = 0; if(DoButton_Menu(&s_CallVoteButton, Localize("Call vote"), 0, &Button)) { @@ -487,7 +487,7 @@ void CMenus::RenderServerControl(CUIRect MainView) } m_aCallvoteReason[0] = 0; } - + // render kick reason CUIRect Reason; Bottom.VSplitRight(40.0f, &Bottom, 0); @@ -499,7 +499,7 @@ void CMenus::RenderServerControl(CUIRect MainView) Reason.VSplitLeft(w+10.0f, 0, &Reason); static float s_Offset = 0.0f; DoEditBox(&m_aCallvoteReason, &Reason, m_aCallvoteReason, sizeof(m_aCallvoteReason), 14.0f, &s_Offset, false, CUI::CORNER_ALL); - + // extended features (only available when authed in rcon) if(Client()->RconAuthed()) { @@ -545,7 +545,7 @@ void CMenus::RenderServerControl(CUIRect MainView) static int s_RemoveVoteButton = 0; if(DoButton_Menu(&s_RemoveVoteButton, Localize("Remove"), 0, &Button)) m_pClient->m_pVoting->RemovevoteOption(m_CallvoteSelectedOption); - + // add vote Extended.HSplitTop(20.0f, &Bottom, &Extended); @@ -571,7 +571,7 @@ void CMenus::RenderServerControl(CUIRect MainView) static float s_OffsetDesc = 0.0f; DoEditBox(&s_aVoteDescription, &Button, s_aVoteDescription, sizeof(s_aVoteDescription), 14.0f, &s_OffsetDesc, false, CUI::CORNER_ALL); - Bottom.VMargin(20.0f, &Button); + Bottom.VMargin(20.0f, &Button); static float s_OffsetCmd = 0.0f; DoEditBox(&s_aVoteCommand, &Button, s_aVoteCommand, sizeof(s_aVoteCommand), 14.0f, &s_OffsetCmd, false, CUI::CORNER_ALL); } diff --git a/src/game/client/components/menus_settings.cpp b/src/game/client/components/menus_settings.cpp index 959af2f3..28f3559d 100644 --- a/src/game/client/components/menus_settings.cpp +++ b/src/game/client/components/menus_settings.cpp @@ -108,7 +108,7 @@ void CMenus::RenderSettingsGeneral(CUIRect MainView) Right.HSplitTop(20.0f, &Button, &Right); if(DoButton_CheckBox(&g_Config.m_ClNameplatesAlways, Localize("Always show name plates"), g_Config.m_ClNameplatesAlways, &Button)) g_Config.m_ClNameplatesAlways ^= 1; - + Right.HSplitTop(2.5f, 0, &Right); Right.HSplitTop(20.0f, &Label, &Right); Right.HSplitTop(20.0f, &Button, &Right); @@ -245,7 +245,7 @@ void CMenus::RenderSettingsTee(CUIRect MainView) MainView.HSplitTop(10.0f, 0, &MainView); // skin info - const CSkins::CSkin *pOwnSkin = m_pClient->m_pSkins->Get(m_pClient->m_pSkins->Find(g_Config.m_PlayerSkin)); + const CSkins::CSkin *pOwnSkin = m_pClient->m_pSkins->Get(m_pClient->m_pSkins->Find(g_Config.m_PlayerSkin)); CTeeRenderInfo OwnSkinInfo; if(g_Config.m_PlayerUseCustomColor) { @@ -273,7 +273,7 @@ void CMenus::RenderSettingsTee(CUIRect MainView) RenderTools()->RenderTee(CAnimState::GetIdle(), &OwnSkinInfo, 0, vec2(1, 0), vec2(Label.x+30.0f, Label.y+28.0f)); Label.HSplitTop(15.0f, 0, &Label);; Label.VSplitLeft(70.0f, 0, &Label); - UI()->DoLabelScaled(&Label, g_Config.m_PlayerSkin, 14.0f, -1, 150.0f); + UI()->DoLabelScaled(&Label, g_Config.m_PlayerSkin, 14.0f, -1, 150.0f); // custom colour selector MainView.HSplitTop(20.0f, 0, &MainView); @@ -322,7 +322,7 @@ void CMenus::RenderSettingsTee(CUIRect MainView) Label.VSplitLeft(100.0f, &Label, &Button); Button.HMargin(2.0f, &Button); - float k = ((PrevColor>>((2-s)*8))&0xff) / 255.0f; + float k = ((PrevColor>>((2-s)*8))&0xff) / 255.0f; k = DoScrollbarH(&s_aColorSlider[i][s], &Button, k); Color <<= 8; Color += clamp((int)(k*255), 0, 255); @@ -643,7 +643,7 @@ void CMenus::RenderSettingsGraphics(CUIRect MainView) CListboxItem Item = UiDoListboxNextItem(&s_aModes[i], OldSelected == i); if(Item.m_Visible) { - str_format(aBuf, sizeof(aBuf), " %dx%d %d bit", s_aModes[i].m_Width, s_aModes[i].m_Height, Depth); + str_format(aBuf, sizeof(aBuf), " %dx%d %d bit", s_aModes[i].m_Width, s_aModes[i].m_Height, Depth); UI()->DoLabelScaled(&Item.m_Rect, aBuf, 16.0f, -1); } } @@ -826,7 +826,7 @@ void LoadLanguageIndexfile(IStorage *pStorage, IConsole *pConsole, sorted_array< pConsole->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "localization", "couldn't open index file"); return; } - + char aOrigin[128]; CLineReader LineReader; LineReader.Init(File); @@ -835,7 +835,7 @@ void LoadLanguageIndexfile(IStorage *pStorage, IConsole *pConsole, sorted_array< { if(!str_length(pLine) || pLine[0] == '#') // skip empty lines and comments continue; - + str_copy(aOrigin, pLine, sizeof(aOrigin)); char *pReplacement = LineReader.Get(); if(!pReplacement) @@ -843,7 +843,7 @@ void LoadLanguageIndexfile(IStorage *pStorage, IConsole *pConsole, sorted_array< pConsole->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "localization", "unexpected end of index file"); break; } - + if(pReplacement[0] != '=' || pReplacement[1] != '=' || pReplacement[2] != ' ') { char aBuf[128]; @@ -851,7 +851,7 @@ void LoadLanguageIndexfile(IStorage *pStorage, IConsole *pConsole, sorted_array< pConsole->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "localization", aBuf); continue; } - + char aFileName[128]; str_format(aFileName, sizeof(aFileName), "languages/%s.txt", aOrigin); pLanguages->add(CLanguage(pReplacement+3, aFileName)); @@ -861,7 +861,7 @@ void LoadLanguageIndexfile(IStorage *pStorage, IConsole *pConsole, sorted_array< void CMenus::RenderLanguageSelection(CUIRect MainView) { - static int s_LanguageList = 0; + static int s_LanguageList = 0; static int s_SelectedLanguage = 0; static sorted_array<CLanguage> s_Languages; static float s_ScrollValue = 0; diff --git a/src/game/client/components/motd.cpp b/src/game/client/components/motd.cpp index 96347933..76203c47 100644 --- a/src/game/client/components/motd.cpp +++ b/src/game/client/components/motd.cpp @@ -18,7 +18,7 @@ void CMotd::Clear() bool CMotd::IsActive() { - return time_get() < m_ServerMotdTime; + return time_get() < m_ServerMotdTime; } void CMotd::OnStateChange(int NewState, int OldState) @@ -31,12 +31,12 @@ void CMotd::OnRender() { if(!IsActive()) return; - + float Width = 400*3.0f*Graphics()->ScreenAspect(); float Height = 400*3.0f; Graphics()->MapScreen(0, 0, Width, Height); - + float h = 800.0f; float w = 650.0f; float x = Width/2 - w/2; @@ -61,7 +61,7 @@ void CMotd::OnMessage(int MsgType, void *pRawMsg) { CNetMsg_Sv_Motd *pMsg = (CNetMsg_Sv_Motd *)pRawMsg; - // process escaping + // process escaping str_copy(m_aServerMotd, pMsg->m_pMessage, sizeof(m_aServerMotd)); for(int i = 0; m_aServerMotd[i]; i++) { diff --git a/src/game/client/components/motd.h b/src/game/client/components/motd.h index e2240fa2..f47adaff 100644 --- a/src/game/client/components/motd.h +++ b/src/game/client/components/motd.h @@ -13,7 +13,7 @@ public: void Clear(); bool IsActive(); - + virtual void OnRender(); virtual void OnStateChange(int NewState, int OldState); virtual void OnMessage(int MsgType, void *pRawMsg); diff --git a/src/game/client/components/nameplates.cpp b/src/game/client/components/nameplates.cpp index fecd6227..6699fe24 100644 --- a/src/game/client/components/nameplates.cpp +++ b/src/game/client/components/nameplates.cpp @@ -17,9 +17,9 @@ void CNamePlates::RenderNameplate( ) { float IntraTick = Client()->IntraGameTick(); - + vec2 Position = mix(vec2(pPrevChar->m_X, pPrevChar->m_Y), vec2(pPlayerChar->m_X, pPlayerChar->m_Y), IntraTick); - + float FontSize = 18.0f + 20.0f * g_Config.m_ClNameplatesSize / 100.0f; // render name plate @@ -28,10 +28,10 @@ void CNamePlates::RenderNameplate( float a = 1; if(g_Config.m_ClNameplatesAlways == 0) a = clamp(1-powf(distance(m_pClient->m_pControls->m_TargetPos, Position)/200.0f,16.0f), 0.0f, 1.0f); - + const char *pName = m_pClient->m_aClients[pPlayerInfo->m_ClientID].m_aName; float tw = TextRender()->TextWidth(0, FontSize, pName, -1); - + TextRender()->TextOutlineColor(0.0f, 0.0f, 0.0f, 0.5f*a); TextRender()->TextColor(1.0f, 1.0f, 1.0f, a); if(g_Config.m_ClNameplatesTeamcolors && m_pClient->m_Snap.m_pGameInfoObj && m_pClient->m_Snap.m_pGameInfoObj->m_GameFlags&GAMEFLAG_TEAMS) @@ -41,9 +41,9 @@ void CNamePlates::RenderNameplate( else if(pPlayerInfo->m_Team == TEAM_BLUE) TextRender()->TextColor(0.7f, 0.7f, 1.0f, a); } - + TextRender()->Text(0, Position.x-tw/2.0f, Position.y-FontSize-38.0f, FontSize, pName, -1); - + if(g_Config.m_Debug) // render client id when in debug aswell { char aBuf[128]; diff --git a/src/game/client/components/particles.cpp b/src/game/client/components/particles.cpp index 25c9dd36..c4583cb1 100644 --- a/src/game/client/components/particles.cpp +++ b/src/game/client/components/particles.cpp @@ -26,7 +26,7 @@ void CParticles::OnReset() m_aParticles[i].m_PrevPart = i-1; m_aParticles[i].m_NextPart = i+1; } - + m_aParticles[0].m_PrevPart = 0; m_aParticles[MAX_PARTICLES-1].m_NextPart = -1; m_FirstFree = 0; @@ -39,30 +39,30 @@ void CParticles::Add(int Group, CParticle *pPart) { if(Client()->State() == IClient::STATE_DEMOPLAYBACK) { - const IDemoPlayer::CInfo *pInfo = DemoPlayer()->BaseInfo(); + const IDemoPlayer::CInfo *pInfo = DemoPlayer()->BaseInfo(); if(pInfo->m_Paused) return; } if (m_FirstFree == -1) return; - + // remove from the free list int Id = m_FirstFree; m_FirstFree = m_aParticles[Id].m_NextPart; if(m_FirstFree != -1) m_aParticles[m_FirstFree].m_PrevPart = -1; - + // copy data m_aParticles[Id] = *pPart; - + // insert to the group list m_aParticles[Id].m_PrevPart = -1; m_aParticles[Id].m_NextPart = m_aFirstPart[Group]; if(m_aFirstPart[Group] != -1) m_aParticles[m_aFirstPart[Group]].m_PrevPart = Id; m_aFirstPart[Group] = Id; - + // set some parameters m_aParticles[Id].m_Life = 0; } @@ -74,14 +74,14 @@ void CParticles::Update(float TimePassed) if(FrictionFraction > 2.0f) // safty messure FrictionFraction = 0; - + int FrictionCount = 0; while(FrictionFraction > 0.05f) { FrictionCount++; FrictionFraction -= 0.05f; } - + for(int g = 0; g < NUM_GROUPS; g++) { int i = m_aFirstPart[g]; @@ -90,15 +90,15 @@ void CParticles::Update(float TimePassed) int Next = m_aParticles[i].m_NextPart; //m_aParticles[i].vel += flow_get(m_aParticles[i].pos)*time_passed * m_aParticles[i].flow_affected; m_aParticles[i].m_Vel.y += m_aParticles[i].m_Gravity*TimePassed; - + for(int f = 0; f < FrictionCount; f++) // apply friction m_aParticles[i].m_Vel *= m_aParticles[i].m_Friction; - + // move the point vec2 Vel = m_aParticles[i].m_Vel*TimePassed; Collision()->MovePoint(&m_aParticles[i].m_Pos, &Vel, 0.1f+0.9f*frandom(), NULL); m_aParticles[i].m_Vel = Vel* (1.0f/TimePassed); - + m_aParticles[i].m_Life += TimePassed; m_aParticles[i].m_Rot += TimePassed * m_aParticles[i].m_Rotspeed; @@ -110,10 +110,10 @@ void CParticles::Update(float TimePassed) m_aParticles[m_aParticles[i].m_PrevPart].m_NextPart = m_aParticles[i].m_NextPart; else m_aFirstPart[g] = m_aParticles[i].m_NextPart; - + if(m_aParticles[i].m_NextPart != -1) m_aParticles[m_aParticles[i].m_NextPart].m_PrevPart = m_aParticles[i].m_PrevPart; - + // insert to the free list if(m_FirstFree != -1) m_aParticles[m_FirstFree].m_PrevPart = i; @@ -121,7 +121,7 @@ void CParticles::Update(float TimePassed) m_aParticles[i].m_NextPart = m_FirstFree; m_FirstFree = i; } - + i = Next; } } @@ -134,16 +134,16 @@ void CParticles::OnRender() static int64 LastTime = 0; int64 t = time_get(); - + if(Client()->State() == IClient::STATE_DEMOPLAYBACK) { - const IDemoPlayer::CInfo *pInfo = DemoPlayer()->BaseInfo(); + const IDemoPlayer::CInfo *pInfo = DemoPlayer()->BaseInfo(); if(!pInfo->m_Paused) Update((float)((t-LastTime)/(double)time_freq())*pInfo->m_Speed); } else Update((float)((t-LastTime)/(double)time_freq())); - + LastTime = t; } @@ -168,11 +168,11 @@ void CParticles::RenderGroup(int Group) m_aParticles[i].m_Color.r, m_aParticles[i].m_Color.g, m_aParticles[i].m_Color.b, - m_aParticles[i].m_Color.a); // pow(a, 0.75f) * + m_aParticles[i].m_Color.a); // pow(a, 0.75f) * IGraphics::CQuadItem QuadItem(p.x, p.y, Size, Size); Graphics()->QuadsDraw(&QuadItem, 1); - + i = m_aParticles[i].m_NextPart; } Graphics()->QuadsEnd(); diff --git a/src/game/client/components/particles.h b/src/game/client/components/particles.h index 641ec261..176a2b05 100644 --- a/src/game/client/components/particles.h +++ b/src/game/client/components/particles.h @@ -21,7 +21,7 @@ struct CParticle m_FlowAffected = 1.0f; m_Color = vec4(1,1,1,1); } - + vec2 m_Pos; vec2 m_Vel; @@ -30,7 +30,7 @@ struct CParticle float m_FlowAffected; float m_LifeSpan; - + float m_StartSize; float m_EndSize; @@ -41,7 +41,7 @@ struct CParticle float m_Friction; vec4 m_Color; - + // set by the particle system float m_Life; int m_PrevPart; @@ -61,14 +61,14 @@ public: }; CParticles(); - + void Add(int Group, CParticle *pPart); - + virtual void OnReset(); virtual void OnRender(); private: - + enum { MAX_PARTICLES=1024*8, @@ -77,7 +77,7 @@ private: CParticle m_aParticles[MAX_PARTICLES]; int m_FirstFree; int m_aFirstPart[NUM_GROUPS]; - + void RenderGroup(int Group); void Update(float TimePassed); @@ -88,7 +88,7 @@ private: CParticles *m_pParts; virtual void OnRender() { m_pParts->RenderGroup(TGROUP); } }; - + CRenderGroup<GROUP_PROJECTILE_TRAIL> m_RenderTrail; CRenderGroup<GROUP_EXPLOSIONS> m_RenderExplosions; CRenderGroup<GROUP_GENERAL> m_RenderGeneral; diff --git a/src/game/client/components/players.cpp b/src/game/client/components/players.cpp index 74a48503..6811c2ad 100644 --- a/src/game/client/components/players.cpp +++ b/src/game/client/components/players.cpp @@ -25,7 +25,7 @@ void CPlayers::RenderHand(CTeeRenderInfo *pInfo, vec2 CenterPos, vec2 Dir, float { // for drawing hand //const skin *s = skin_get(skin_id); - + float BaseSize = 10.0f; //dir = normalize(hook_pos-pos); @@ -102,7 +102,7 @@ void CPlayers::RenderHook( if(m_pClient->m_Snap.m_pGameInfoObj) IsTeamplay = (m_pClient->m_Snap.m_pGameInfoObj->m_GameFlags&GAMEFLAG_TEAMS) != 0; - // check for ninja + // check for ninja if (Player.m_Weapon == WEAPON_NINJA) { // change the skin for the player to the ninja @@ -117,7 +117,7 @@ void CPlayers::RenderHook( RenderInfo.m_ColorBody = vec4(1,1,1,1); RenderInfo.m_ColorFeet = vec4(1,1,1,1); } - } + } } float IntraTick = Client()->IntraGameTick(); @@ -125,7 +125,7 @@ void CPlayers::RenderHook( // set size RenderInfo.m_Size = 64.0f; - + // use preditect players if needed if(pInfo.m_Local && g_Config.m_ClPredict && Client()->State() != IClient::STATE_DEMOPLAYBACK) { @@ -152,7 +152,7 @@ void CPlayers::RenderHook( vec2 Pos = Position; vec2 HookPos; - + if(pPlayerChar->m_HookedPlayer != -1) { if(m_pClient->m_Snap.m_pLocalInfo && pPlayerChar->m_HookedPlayer == m_pClient->m_Snap.m_pLocalInfo->m_ClientID) @@ -226,7 +226,7 @@ void CPlayers::RenderPlayer( if(m_pClient->m_Snap.m_pGameInfoObj) IsTeamplay = (m_pClient->m_Snap.m_pGameInfoObj->m_GameFlags&GAMEFLAG_TEAMS) != 0; - // check for ninja + // check for ninja if (Player.m_Weapon == WEAPON_NINJA) { // change the skin for the player to the ninja @@ -241,18 +241,18 @@ void CPlayers::RenderPlayer( RenderInfo.m_ColorBody = vec4(1,1,1,1); RenderInfo.m_ColorFeet = vec4(1,1,1,1); } - } + } } - + // set size RenderInfo.m_Size = 64.0f; float IntraTick = Client()->IntraGameTick(); - + float Angle = mix((float)Prev.m_Angle, (float)Player.m_Angle, IntraTick)/256.0f; - + //float angle = 0; - + if(pInfo.m_Local && Client()->State() != IClient::STATE_DEMOPLAYBACK) { // just use the direct input if it's local player we are rendering @@ -264,14 +264,14 @@ void CPlayers::RenderPlayer( float mixspeed = Client()->FrameTime()*2.5f; if(player.attacktick != prev.attacktick) // shooting boosts the mixing speed mixspeed *= 15.0f; - + // move the delta on a constant speed on a x^2 curve float current = g_GameClient.m_aClients[info.cid].angle; float target = player.angle/256.0f; float delta = angular_distance(current, target); float sign = delta < 0 ? -1 : 1; float new_delta = delta - 2*mixspeed*sqrt(delta*sign)*sign + mixspeed*mixspeed; - + // make sure that it doesn't vibrate when it's still if(fabs(delta) < 2/256.0f) angle = target; @@ -280,7 +280,7 @@ void CPlayers::RenderPlayer( g_GameClient.m_aClients[info.cid].angle = angle;*/ } - + // use preditect players if needed if(pInfo.m_Local && g_Config.m_ClPredict && Client()->State() != IClient::STATE_DEMOPLAYBACK) { @@ -296,16 +296,16 @@ void CPlayers::RenderPlayer( NewTick = m_pClient->m_NewPredictedTick; } } - + vec2 Direction = GetDirection((int)(Angle*256.0f)); vec2 Position = mix(vec2(Prev.m_X, Prev.m_Y), vec2(Player.m_X, Player.m_Y), IntraTick); vec2 Vel = mix(vec2(Prev.m_VelX/256.0f, Prev.m_VelY/256.0f), vec2(Player.m_VelX/256.0f, Player.m_VelY/256.0f), IntraTick); - + m_pClient->m_pFlow->Add(Position, Vel*100.0f, 10.0f); - + RenderInfo.m_GotAirJump = Player.m_Jumped&2?0:1; - - + + // detect events if(NewTick) { @@ -340,7 +340,7 @@ void CPlayers::RenderPlayer( float ct = (Client()->PrevGameTick()-Player.m_AttackTick)/(float)SERVER_TICK_SPEED + Client()->GameTickTime(); State.Add(&g_pData->m_aAnimations[ANIM_NINJA_SWING], clamp(ct*2.0f,0.0f,1.0f), 1.0f); } - + // do skidding if(!InAir && WantOtherDir && length(Vel*50) > 500.0f) { @@ -350,7 +350,7 @@ void CPlayers::RenderPlayer( m_pClient->m_pSounds->Play(CSounds::CHN_WORLD, SOUND_PLAYER_SKID, 0.25f, Position); SkidSoundTime = time_get(); } - + m_pClient->m_pEffects->SkidTrail( Position+vec2(-Player.m_Direction*6,12), vec2(-Player.m_Direction*100*length(Vel),-50) @@ -422,7 +422,7 @@ void CPlayers::RenderPlayer( { vec2 Dir = vec2(pPlayerChar->m_X,pPlayerChar->m_Y) - vec2(pPrevChar->m_X, pPrevChar->m_Y); Dir = normalize(Dir); - float HadOkenAngle = GetAngle(Dir); + float HadOkenAngle = GetAngle(Dir); Graphics()->QuadsSetRotation(HadOkenAngle ); //float offsety = -data->weapons[iw].muzzleoffsety; RenderTools()->SelectSprite(g_pData->m_Weapons.m_aId[iw].m_aSpriteMuzzles[IteX], 0); @@ -564,7 +564,7 @@ void CPlayers::OnRender() bool Local = ((const CNetObj_PlayerInfo *)pInfo)->m_Local !=0; if((p % 2) == 0 && Local) continue; if((p % 2) == 1 && !Local) continue; - + CNetObj_Character PrevChar = m_pClient->m_Snap.m_aCharacters[i].m_Prev; CNetObj_Character CurChar = m_pClient->m_Snap.m_aCharacters[i].m_Cur; @@ -582,7 +582,7 @@ void CPlayers::OnRender() (const CNetObj_PlayerInfo *)pPrevInfo, (const CNetObj_PlayerInfo *)pInfo ); - } + } } } } diff --git a/src/game/client/components/players.h b/src/game/client/components/players.h index 34cebd90..cedad0ff 100644 --- a/src/game/client/components/players.h +++ b/src/game/client/components/players.h @@ -5,21 +5,21 @@ #include <game/client/component.h> class CPlayers : public CComponent -{ +{ void RenderHand(class CTeeRenderInfo *pInfo, vec2 CenterPos, vec2 Dir, float AngleOffset, vec2 PostRotOffset); void RenderPlayer( const CNetObj_Character *pPrevChar, const CNetObj_Character *pPlayerChar, const CNetObj_PlayerInfo *pPrevInfo, const CNetObj_PlayerInfo *pPlayerInfo - ); + ); void RenderHook( const CNetObj_Character *pPrevChar, const CNetObj_Character *pPlayerChar, const CNetObj_PlayerInfo *pPrevInfo, const CNetObj_PlayerInfo *pPlayerInfo ); - + public: virtual void OnRender(); }; diff --git a/src/game/client/components/scoreboard.cpp b/src/game/client/components/scoreboard.cpp index 47603255..2cec5e62 100644 --- a/src/game/client/components/scoreboard.cpp +++ b/src/game/client/components/scoreboard.cpp @@ -82,7 +82,7 @@ void CScoreboard::RenderGoals(float x, float y, float w) void CScoreboard::RenderSpectators(float x, float y, float w) { - float h = 140.0f; + float h = 140.0f; // background Graphics()->BlendNormal(); @@ -194,19 +194,19 @@ void CScoreboard::RenderScoreboard(float x, float y, float w, int Team, const ch float NameOffset = TeeOffset+TeeLength, NameLength = 300.0f-TeeLength; float PingOffset = x+610.0f, PingLength = 65.0f; float CountryOffset = PingOffset-(LineHeight-Spacing-TeeSizeMod*5.0f)*2.0f, CountryLength = (LineHeight-Spacing-TeeSizeMod*5.0f)*2.0f; - float ClanOffset = x+370.0f, ClanLength = 230.0f-CountryLength; + float ClanOffset = x+370.0f, ClanLength = 230.0f-CountryLength; // render headlines y += 50.0f; float HeadlineFontsize = 22.0f; tw = TextRender()->TextWidth(0, HeadlineFontsize, Localize("Score"), -1); TextRender()->Text(0, ScoreOffset+ScoreLength-tw, y, HeadlineFontsize, Localize("Score"), -1); - + TextRender()->Text(0, NameOffset, y, HeadlineFontsize, Localize("Name"), -1); - + tw = TextRender()->TextWidth(0, HeadlineFontsize, Localize("Clan"), -1); TextRender()->Text(0, ClanOffset+ClanLength/2-tw/2, y, HeadlineFontsize, Localize("Clan"), -1); - + tw = TextRender()->TextWidth(0, HeadlineFontsize, Localize("Ping"), -1); TextRender()->Text(0, PingOffset+PingLength-tw, y, HeadlineFontsize, Localize("Ping"), -1); @@ -214,7 +214,7 @@ void CScoreboard::RenderScoreboard(float x, float y, float w, int Team, const ch y += HeadlineFontsize*2.0f; float FontSize = 24.0f; CTextCursor Cursor; - + for(int i = 0; i < MAX_CLIENTS; i++) { // make sure that we render the correct team @@ -249,13 +249,13 @@ void CScoreboard::RenderScoreboard(float x, float y, float w, int Team, const ch Graphics()->QuadsBegin(); RenderTools()->SelectSprite(pInfo->m_Team==TEAM_RED ? SPRITE_FLAG_BLUE : SPRITE_FLAG_RED, SPRITE_FLAG_FLIP_X); - + float Size = LineHeight; IGraphics::CQuadItem QuadItem(TeeOffset+0.0f, y-5.0f-Spacing/2.0f, Size/2.0f, Size); Graphics()->QuadsDrawTL(&QuadItem, 1); Graphics()->QuadsEnd(); } - + // avatar CTeeRenderInfo TeeInfo = m_pClient->m_aClients[pInfo->m_ClientID].m_RenderInfo; TeeInfo.m_Size *= TeeSizeMod; @@ -279,7 +279,7 @@ void CScoreboard::RenderScoreboard(float x, float y, float w, int Team, const ch IGraphics::CQuadItem QuadItem(CountryOffset, y+(Spacing+TeeSizeMod*5.0f)/2.0f, CountryLength, LineHeight-Spacing-TeeSizeMod*5.0f); Graphics()->QuadsDrawTL(&QuadItem, 1); Graphics()->QuadsEnd(); - + // ping str_format(aBuf, sizeof(aBuf), "%d", clamp(pInfo->m_Latency, 0, 1000)); tw = TextRender()->TextWidth(0, FontSize, aBuf, -1); @@ -321,15 +321,15 @@ void CScoreboard::OnRender() { if(!Active()) return; - + // if the score board is active, then we should clear the motd message aswell if(m_pClient->m_pMotd->IsActive()) m_pClient->m_pMotd->Clear(); - + float Width = 400*3.0f*Graphics()->ScreenAspect(); float Height = 400*3.0f; - + Graphics()->MapScreen(0, 0, Width, Height); float w = 700.0f; @@ -342,12 +342,12 @@ void CScoreboard::OnRender() { const char *pRedClanName = GetClanName(TEAM_RED); const char *pBlueClanName = GetClanName(TEAM_BLUE); - + if(m_pClient->m_Snap.m_pGameInfoObj->m_GameStateFlags&GAMESTATEFLAG_GAMEOVER && m_pClient->m_Snap.m_pGameDataObj) { char aText[256]; str_copy(aText, Localize("Draw!"), sizeof(aText)); - + if(m_pClient->m_Snap.m_pGameDataObj->m_TeamscoreRed > m_pClient->m_Snap.m_pGameDataObj->m_TeamscoreBlue) { if(pRedClanName) @@ -362,11 +362,11 @@ void CScoreboard::OnRender() else str_copy(aText, Localize("Blue team wins!"), sizeof(aText)); } - + float w = TextRender()->TextWidth(0, 86.0f, aText, -1); TextRender()->Text(0, Width/2-w/2, 39, 86.0f, aText, -1); } - + RenderScoreboard(Width/2-w-5.0f, 150.0f, w, TEAM_RED, pRedClanName ? pRedClanName : Localize("Red team")); RenderScoreboard(Width/2+5.0f, 150.0f, w, TEAM_BLUE, pBlueClanName ? pBlueClanName : Localize("Blue team")); } @@ -379,10 +379,10 @@ void CScoreboard::OnRender() bool CScoreboard::Active() { - // if we activly wanna look on the scoreboard + // if we activly wanna look on the scoreboard if(m_Active) return true; - + if(m_pClient->m_Snap.m_pLocalInfo && m_pClient->m_Snap.m_pLocalInfo->m_Team != TEAM_SPECTATORS) { // we are not a spectator, check if we are dead @@ -406,7 +406,7 @@ const char *CScoreboard::GetClanName(int Team) const CNetObj_PlayerInfo *pInfo = m_pClient->m_Snap.m_paInfoByScore[i]; if(!pInfo || pInfo->m_Team != Team) continue; - + if(!pClanName) { pClanName = m_pClient->m_aClients[pInfo->m_ClientID].m_aClan; @@ -420,7 +420,7 @@ const char *CScoreboard::GetClanName(int Team) return 0; } } - + if(ClanPlayers > 1 && pClanName[0]) return pClanName; else diff --git a/src/game/client/components/scoreboard.h b/src/game/client/components/scoreboard.h index 5ac43a49..ea920d35 100644 --- a/src/game/client/components/scoreboard.h +++ b/src/game/client/components/scoreboard.h @@ -12,11 +12,11 @@ class CScoreboard : public CComponent void RenderRecordingNotification(float x); static void ConKeyScoreboard(IConsole::IResult *pResult, void *pUserData); - + const char *GetClanName(int Team); - + bool m_Active; - + public: CScoreboard(); virtual void OnReset(); diff --git a/src/game/client/components/skins.cpp b/src/game/client/components/skins.cpp index d8550da4..dd38e9ea 100644 --- a/src/game/client/components/skins.cpp +++ b/src/game/client/components/skins.cpp @@ -10,13 +10,13 @@ #include "skins.h" -int CSkins::SkinScan(const char *pName, int IsDir, int DirType, void *pUser) +int CSkins::SkinScan(const char *pName, int IsDir, int DirType, void *pUser) { CSkins *pSelf = (CSkins *)pUser; int l = str_length(pName); if(l < 4 || IsDir || str_comp(pName+l-4, ".png") != 0) return 0; - + char aBuf[512]; str_format(aBuf, sizeof(aBuf), "skins/%s", pName); CImageInfo Info; @@ -26,10 +26,10 @@ int CSkins::SkinScan(const char *pName, int IsDir, int DirType, void *pUser) pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "game", aBuf); return 0; } - + CSkin Skin; Skin.m_OrgTexture = pSelf->Graphics()->LoadTextureRaw(Info.m_Width, Info.m_Height, Info.m_Format, Info.m_pData, Info.m_Format, 0); - + int BodySize = 96; // body size unsigned char *d = (unsigned char *)Info.m_pData; int Pitch = Info.m_Width*4; @@ -47,10 +47,10 @@ int CSkins::SkinScan(const char *pName, int IsDir, int DirType, void *pUser) aColors[2] += d[y*Pitch+x*4+2]; } } - + Skin.m_BloodColor = normalize(vec3(aColors[0], aColors[1], aColors[2])); } - + // create colorless version int Step = Info.m_Format == CImageInfo::FORMAT_RGBA ? 4 : 3; @@ -63,11 +63,11 @@ int CSkins::SkinScan(const char *pName, int IsDir, int DirType, void *pUser) d[i*Step+2] = v; } - + int Freq[256] = {0}; int OrgWeight = 0; int NewWeight = 192; - + // find most common frequence for(int y = 0; y < BodySize; y++) for(int x = 0; x < BodySize; x++) @@ -75,7 +75,7 @@ int CSkins::SkinScan(const char *pName, int IsDir, int DirType, void *pUser) if(d[y*Pitch+x*4+3] > 128) Freq[d[y*Pitch+x*4]]++; } - + for(int i = 1; i < 256; i++) { if(Freq[OrgWeight] < Freq[i]) @@ -97,11 +97,11 @@ int CSkins::SkinScan(const char *pName, int IsDir, int DirType, void *pUser) d[y*Pitch+x*4+1] = v; d[y*Pitch+x*4+2] = v; } - + Skin.m_ColorTexture = pSelf->Graphics()->LoadTextureRaw(Info.m_Width, Info.m_Height, Info.m_Format, Info.m_pData, Info.m_Format, 0); mem_free(Info.m_pData); - // set skin data + // set skin data str_copy(Skin.m_aName, pName, min((int)sizeof(Skin.m_aName),l-3)); str_format(aBuf, sizeof(aBuf), "load skin %s", Skin.m_aName); pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "game", aBuf); @@ -130,7 +130,7 @@ void CSkins::OnInit() int CSkins::Num() { - return m_aSkins.size(); + return m_aSkins.size(); } const CSkins::CSkin *CSkins::Get(int Index) diff --git a/src/game/client/components/skins.h b/src/game/client/components/skins.h index d76ad85b..519f4521 100644 --- a/src/game/client/components/skins.h +++ b/src/game/client/components/skins.h @@ -19,15 +19,15 @@ public: bool operator<(const CSkin &Other) { return str_comp(m_aName, Other.m_aName) < 0; } }; - + void OnInit(); - + vec3 GetColorV3(int v); vec4 GetColorV4(int v); int Num(); const CSkin *Get(int Index); int Find(const char *pName); - + private: sorted_array<CSkin> m_aSkins; diff --git a/src/game/client/components/sounds.cpp b/src/game/client/components/sounds.cpp index 24bd0ebf..ffafa128 100644 --- a/src/game/client/components/sounds.cpp +++ b/src/game/client/components/sounds.cpp @@ -19,7 +19,7 @@ struct CUserData static int LoadSoundsThread(void *pUser) { CUserData *pData = static_cast<CUserData *>(pUser); - + for(int s = 0; s < g_pData->m_NumSounds; s++) { for(int i = 0; i < g_pData->m_aSounds[s].m_NumSounds; i++) @@ -86,7 +86,7 @@ void CSounds::OnRender() // play sound from queue if(m_QueuePos > 0) { - int64 Now = time_get(); + int64 Now = time_get(); if(m_QueueWaitTime <= Now) { Play(m_aQueue[0].m_Channel, m_aQueue[0].m_SetId, 1.0f, vec2(0,0)); @@ -122,7 +122,7 @@ void CSounds::PlayAndRecord(int Chn, int SetId, float Vol, vec2 Pos) CNetMsg_Sv_SoundGlobal Msg; Msg.m_SoundID = SetId; Client()->SendPackMsg(&Msg, MSGFLAG_NOSEND|MSGFLAG_RECORD); - + Play(Chn, SetId, Vol, Pos); } diff --git a/src/game/client/components/sounds.h b/src/game/client/components/sounds.h index ca8cfd77..2670f793 100644 --- a/src/game/client/components/sounds.h +++ b/src/game/client/components/sounds.h @@ -33,7 +33,7 @@ public: virtual void OnInit(); virtual void OnReset(); virtual void OnRender(); - + void ClearQueue(); void Enqueue(int Channel, int SetId); void Play(int Channel, int SetId, float Vol, vec2 Pos); diff --git a/src/game/client/components/spectator.cpp b/src/game/client/components/spectator.cpp index 94889de7..41c7b48f 100644 --- a/src/game/client/components/spectator.cpp +++ b/src/game/client/components/spectator.cpp @@ -32,7 +32,7 @@ void CSpectator::ConSpectateNext(IConsole::IResult *pResult, void *pUserData) CSpectator *pSelf = (CSpectator *)pUserData; int NewSpectatorID; bool GotNewSpectatorID = false; - + if(pSelf->m_pClient->m_Snap.m_SpecInfo.m_SpectatorID == SPEC_FREEVIEW) { for(int i = 0; i < MAX_CLIENTS; i++) @@ -56,7 +56,7 @@ void CSpectator::ConSpectateNext(IConsole::IResult *pResult, void *pUserData) GotNewSpectatorID = true; break; } - + if(!GotNewSpectatorID) { for(int i = 0; i < pSelf->m_pClient->m_Snap.m_SpecInfo.m_SpectatorID; i++) @@ -79,7 +79,7 @@ void CSpectator::ConSpectatePrevious(IConsole::IResult *pResult, void *pUserData CSpectator *pSelf = (CSpectator *)pUserData; int NewSpectatorID; bool GotNewSpectatorID = false; - + if(pSelf->m_pClient->m_Snap.m_SpecInfo.m_SpectatorID == SPEC_FREEVIEW) { for(int i = MAX_CLIENTS -1; i > -1; i--) @@ -103,7 +103,7 @@ void CSpectator::ConSpectatePrevious(IConsole::IResult *pResult, void *pUserData GotNewSpectatorID = true; break; } - + if(!GotNewSpectatorID) { for(int i = MAX_CLIENTS - 1; i > pSelf->m_pClient->m_Snap.m_SpecInfo.m_SpectatorID; i--) @@ -138,7 +138,7 @@ bool CSpectator::OnMouseMove(float x, float y) { if(!m_Active) return false; - + m_SelectorMouse += vec2(x,y); return true; } @@ -147,7 +147,7 @@ void CSpectator::OnRelease() { OnReset(); } - + void CSpectator::OnRender() { if(!m_Active) @@ -160,14 +160,14 @@ void CSpectator::OnRender() } return; } - + m_WasActive = true; m_SelectedSpectatorID = NO_SELECTION; // draw background float Width = 400*3.0f*Graphics()->ScreenAspect(); float Height = 400*3.0f; - + Graphics()->MapScreen(0, 0, Width, Height); Graphics()->BlendNormal(); @@ -185,7 +185,7 @@ void CSpectator::OnRender() float FontSize = 20.0f; float StartY = -190.0f; float LineHeight = 60.0f; - bool Selected = false; + bool Selected = false; if(m_pClient->m_Snap.m_SpecInfo.m_SpectatorID == SPEC_FREEVIEW) { @@ -238,7 +238,7 @@ void CSpectator::OnRender() CTeeRenderInfo TeeInfo = m_pClient->m_aClients[i].m_RenderInfo; RenderTools()->RenderTee(CAnimState::GetIdle(), &TeeInfo, EMOTE_NORMAL, vec2(1.0f, 0.0f), vec2(Width/2.0f+x+20.0f, Height/2.0f+y+20.0f)); - + y += LineHeight; } TextRender()->TextColor(1.0f, 1.0f, 1.0f, 1.0f); diff --git a/src/game/client/components/spectator.h b/src/game/client/components/spectator.h index 7dfbf856..8e775cff 100644 --- a/src/game/client/components/spectator.h +++ b/src/game/client/components/spectator.h @@ -15,7 +15,7 @@ class CSpectator : public CComponent bool m_Active; bool m_WasActive; - + int m_SelectedSpectatorID; vec2 m_SelectorMouse; @@ -23,10 +23,10 @@ class CSpectator : public CComponent static void ConSpectate(IConsole::IResult *pResult, void *pUserData); static void ConSpectateNext(IConsole::IResult *pResult, void *pUserData); static void ConSpectatePrevious(IConsole::IResult *pResult, void *pUserData); - + public: CSpectator(); - + virtual void OnConsoleInit(); virtual bool OnMouseMove(float x, float y); virtual void OnRender(); diff --git a/src/game/client/components/voting.cpp b/src/game/client/components/voting.cpp index feeb96f7..675d6770 100644 --- a/src/game/client/components/voting.cpp +++ b/src/game/client/components/voting.cpp @@ -80,7 +80,7 @@ void CVoting::CallvoteOption(int OptionID, const char *pReason, bool ForceVote) Callvote("option", pOption->m_aDescription, pReason); break; } - + OptionID--; pOption = pOption->m_pNext; } @@ -98,7 +98,7 @@ void CVoting::RemovevoteOption(int OptionID) Client()->Rcon(aBuf); break; } - + OptionID--; pOption = pOption->m_pNext; } @@ -145,7 +145,7 @@ void CVoting::AddOption(const char *pDescription) m_pLast = pOption; if(!m_pFirst) m_pFirst = pOption; - + str_copy(pOption->m_aDescription, pDescription, sizeof(pOption->m_aDescription)); ++m_NumVoteOptions; } @@ -154,7 +154,7 @@ void CVoting::ClearOptions() { m_Heap.Reset(); - m_NumVoteOptions = 0; + m_NumVoteOptions = 0; m_pFirst = 0; m_pLast = 0; @@ -199,7 +199,7 @@ void CVoting::OnMessage(int MsgType, void *pRawMsg) m_No = pMsg->m_No; m_Pass = pMsg->m_Pass; m_Total = pMsg->m_Total; - } + } else if(MsgType == NETMSGTYPE_SV_VOTECLEAROPTIONS) { ClearOptions(); @@ -238,7 +238,7 @@ void CVoting::OnMessage(int MsgType, void *pRawMsg) else if(MsgType == NETMSGTYPE_SV_VOTEOPTIONREMOVE) { CNetMsg_Sv_VoteOptionRemove *pMsg = (CNetMsg_Sv_VoteOptionRemove *)pRawMsg; - + for(CVoteOptionClient *pOption = m_pFirst; pOption; pOption = pOption->m_pNext) { if(str_comp(pOption->m_aDescription, pMsg->m_pDescription) == 0) @@ -277,13 +277,13 @@ void CVoting::OnRender() void CVoting::RenderBars(CUIRect Bars, bool Text) { RenderTools()->DrawUIRect(&Bars, vec4(0.8f,0.8f,0.8f,0.5f), CUI::CORNER_ALL, Bars.h/3); - + CUIRect Splitter = Bars; Splitter.x = Splitter.x+Splitter.w/2; Splitter.w = Splitter.h/2.0f; Splitter.x -= Splitter.w/2; RenderTools()->DrawUIRect(&Splitter, vec4(0.4f,0.4f,0.4f,0.5f), CUI::CORNER_ALL, Splitter.h/4); - + if(m_Total) { CUIRect PassArea = Bars; @@ -292,25 +292,25 @@ void CVoting::RenderBars(CUIRect Bars, bool Text) CUIRect YesArea = Bars; YesArea.w *= m_Yes/(float)m_Total; RenderTools()->DrawUIRect(&YesArea, vec4(0.2f,0.9f,0.2f,0.85f), CUI::CORNER_ALL, Bars.h/3); - + if(Text) { char Buf[256]; str_format(Buf, sizeof(Buf), "%d", m_Yes); UI()->DoLabel(&YesArea, Buf, Bars.h*0.75f, 0); } - + PassArea.x += YesArea.w; PassArea.w -= YesArea.w; } - + if(m_No) { CUIRect NoArea = Bars; NoArea.w *= m_No/(float)m_Total; NoArea.x = (Bars.x + Bars.w)-NoArea.w; RenderTools()->DrawUIRect(&NoArea, vec4(0.9f,0.2f,0.2f,0.85f), CUI::CORNER_ALL, Bars.h/3); - + if(Text) { char Buf[256]; @@ -327,7 +327,7 @@ void CVoting::RenderBars(CUIRect Bars, bool Text) str_format(Buf, sizeof(Buf), "%d", m_Pass); UI()->DoLabel(&PassArea, Buf, Bars.h*0.75f, 0); } - } + } } diff --git a/src/game/client/components/voting.h b/src/game/client/components/voting.h index 1f8fb8cf..8a3d824f 100644 --- a/src/game/client/components/voting.h +++ b/src/game/client/components/voting.h @@ -15,19 +15,19 @@ class CVoting : public CComponent static void ConCallvote(IConsole::IResult *pResult, void *pUserData); static void ConVote(IConsole::IResult *pResult, void *pUserData); - + int64 m_Closetime; char m_aDescription[VOTE_DESC_LENGTH]; char m_aReason[VOTE_REASON_LENGTH]; int m_Voted; int m_Yes, m_No, m_Pass, m_Total; - + void AddOption(const char *pDescription); void ClearOptions(); void Callvote(const char *pType, const char *pValue, const char *pReason); - + public: - int m_NumVoteOptions; + int m_NumVoteOptions; CVoteOptionClient *m_pFirst; CVoteOptionClient *m_pLast; @@ -39,17 +39,17 @@ public: virtual void OnConsoleInit(); virtual void OnMessage(int Msgtype, void *pRawMsg); virtual void OnRender(); - + void RenderBars(CUIRect Bars, bool Text); - + void CallvoteSpectate(int ClientID, const char *pReason, bool ForceVote = false); void CallvoteKick(int ClientID, const char *pReason, bool ForceVote = false); void CallvoteOption(int OptionID, const char *pReason, bool ForceVote = false); void RemovevoteOption(int OptionID); void AddvoteOption(const char *pDescription, const char *pCommand); - + void Vote(int v); // -1 = no, 1 = yes - + int SecondsLeft() { return (m_Closetime - time_get())/time_freq(); } bool IsVoting() { return m_Closetime != 0; } int TakenChoice() const { return m_Voted; } diff --git a/src/game/client/gameclient.cpp b/src/game/client/gameclient.cpp index 1a35895e..511cf894 100644 --- a/src/game/client/gameclient.cpp +++ b/src/game/client/gameclient.cpp @@ -98,7 +98,7 @@ int CGameClient::GetCountryIndex(int Code) Index = g_GameClient.m_pCountryFlags->Find(-1); if(Index < 0) Index = 0; - } + } return Index; } @@ -117,7 +117,7 @@ void CGameClient::OnConsoleInit() m_pServerBrowser = Kernel()->RequestInterface<IServerBrowser>(); m_pEditor = Kernel()->RequestInterface<IEditor>(); m_pFriends = Kernel()->RequestInterface<IFriends>(); - + // setup pointers m_pBinds = &::gs_Binds; m_pGameConsole = &::gs_GameConsole; @@ -137,7 +137,7 @@ void CGameClient::OnConsoleInit() m_pVoting = &::gs_Voting; m_pScoreboard = &::gs_Scoreboard; m_pItems = &::gs_Items; - + // make a list of all the systems, make sure to add them in the corrent render order m_All.Add(m_pSkins); m_All.Add(m_pCountryFlags); @@ -150,7 +150,7 @@ void CGameClient::OnConsoleInit() m_All.Add(m_pSounds); m_All.Add(m_pVoting); m_All.Add(m_pParticles); // doesn't render anything, just updates all the particles - + m_All.Add(&gs_MapLayersBackGround); // first to render m_All.Add(&m_pParticles->m_RenderTrail); m_All.Add(m_pItems); @@ -171,7 +171,7 @@ void CGameClient::OnConsoleInit() m_All.Add(m_pMotd); m_All.Add(m_pMenus); m_All.Add(m_pGameConsole); - + // build the input stack m_Input.Add(&m_pMenus->m_Binder); // this will take over all input when we want to bind a key m_Input.Add(&m_pBinds->m_SpecialBinds); @@ -183,11 +183,11 @@ void CGameClient::OnConsoleInit() m_Input.Add(&gs_Emoticon); m_Input.Add(m_pControls); m_Input.Add(m_pBinds); - + // add the some console commands Console()->Register("team", "i", CFGFLAG_CLIENT, ConTeam, this, "Switch team"); Console()->Register("kill", "", CFGFLAG_CLIENT, ConKill, this, "Kill yourself"); - + // register server dummy commands for tab completion Console()->Register("tune", "si", CFGFLAG_SERVER, 0, 0, "Tune variable to value"); Console()->Register("tune_reset", "", CFGFLAG_SERVER, 0, 0, "Reset tuning"); @@ -211,12 +211,12 @@ void CGameClient::OnConsoleInit() m_RenderTools.m_pUI = UI(); for(int i = 0; i < m_All.m_Num; i++) m_All.m_paComponents[i]->m_pClient = this; - + // let all the other components register their console commands for(int i = 0; i < m_All.m_Num; i++) m_All.m_paComponents[i]->OnConsoleInit(); - - + + // Console()->Chain("player_name", ConchainSpecialInfoupdate, this); Console()->Chain("player_clan", ConchainSpecialInfoupdate, this); @@ -225,7 +225,7 @@ void CGameClient::OnConsoleInit() Console()->Chain("player_color_body", ConchainSpecialInfoupdate, this); Console()->Chain("player_color_feet", ConchainSpecialInfoupdate, this); Console()->Chain("player_skin", ConchainSpecialInfoupdate, this); - + // m_SuppressEvents = false; } @@ -242,7 +242,7 @@ void CGameClient::OnInit() for(int i = 0; i < NUM_NETOBJTYPES; i++) Client()->SnapSetStaticsize(i, m_NetObjHandler.GetObjSize(i)); - // load default font + // load default font static CFont *pDefaultFont = 0; char aFilename[512]; IOHANDLE File = Storage()->OpenFile("fonts/DejaVuSans.ttf", IOFLAG_READ, IStorage::TYPE_ALL, aFilename, sizeof(aFilename)); @@ -254,7 +254,7 @@ void CGameClient::OnInit() } if(!pDefaultFont) Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "gameclient", "failed to load font. filename='fonts/DejaVuSans.ttf'"); - + // init all components for(int i = m_All.m_Num-1; i >= 0; --i) m_All.m_paComponents[i]->OnInit(); @@ -268,12 +268,12 @@ void CGameClient::OnInit() for(int i = 0; i < m_All.m_Num; i++) m_All.m_paComponents[i]->OnReset(); - + int64 End = time_get(); char aBuf[256]; str_format(aBuf, sizeof(aBuf), "initialisation finished after %.2fms", ((End-Start)*1000)/(float)time_freq()); Console()->Print(IConsole::OUTPUT_LEVEL_DEBUG, "gameclient", aBuf); - + m_ServerMode = SERVERMODE_PURE; } @@ -290,12 +290,12 @@ void CGameClient::DispatchInput() break; } } - + // handle key presses for(int i = 0; i < Input()->NumEvents(); i++) { IInput::CEvent e = Input()->GetEvent(i); - + for(int h = 0; h < m_Input.m_Num; h++) { if(m_Input.m_paComponents[h]->OnInput(e)) @@ -305,9 +305,9 @@ void CGameClient::DispatchInput() } } } - + // clear all events for this frame - Input()->ClearEvents(); + Input()->ClearEvents(); } @@ -320,7 +320,7 @@ void CGameClient::OnConnected() { m_Layers.Init(Kernel()); m_Collision.Init(Layers()); - + RenderTools()->RenderTilemapGenerateSkip(Layers()); for(int i = 0; i < m_All.m_Num; i++) @@ -328,13 +328,13 @@ void CGameClient::OnConnected() m_All.m_paComponents[i]->OnMapLoad(); m_All.m_paComponents[i]->OnReset(); } - + CServerInfo CurrentServerInfo; Client()->GetServerInfo(&CurrentServerInfo); - + m_ServerMode = SERVERMODE_PURE; m_LastSendInfo = 0; - + // send the inital info SendInfo(true); } @@ -347,7 +347,7 @@ void CGameClient::OnReset() for(int i = 0; i < MAX_CLIENTS; i++) m_aClients[i].Reset(); - + for(int i = 0; i < m_All.m_Num; i++) m_All.m_paComponents[i]->OnReset(); @@ -406,7 +406,7 @@ static void Evolve(CNetObj_Character *pCharacter, int Tick) mem_zero(&TempCore, sizeof(TempCore)); TempCore.Init(&TempWorld, g_GameClient.Collision()); TempCore.Read(pCharacter); - + while(pCharacter->m_Tick < Tick) { pCharacter->m_Tick++; @@ -422,30 +422,30 @@ static void Evolve(CNetObj_Character *pCharacter, int Tick) void CGameClient::OnRender() { /*Graphics()->Clear(1,0,0); - + menus->render_background(); return;*/ /* Graphics()->Clear(1,0,0); Graphics()->MapScreen(0,0,100,100); - + Graphics()->QuadsBegin(); Graphics()->SetColor(1,1,1,1); Graphics()->QuadsDraw(50, 50, 30, 30); Graphics()->QuadsEnd(); - + return;*/ - + // update the local character and spectate position UpdatePositions(); - + // dispatch all input to systems DispatchInput(); - + // render all systems for(int i = 0; i < m_All.m_Num; i++) m_All.m_paComponents[i]->OnRender(); - + // clear new tick flags m_NewTick = false; m_NewPredictedTick = false; @@ -482,19 +482,19 @@ void CGameClient::OnMessage(int MsgId, CUnpacker *pUnpacker) if(MsgId == NETMSGTYPE_SV_EXTRAPROJECTILE) { int Num = pUnpacker->GetInt(); - + for(int k = 0; k < Num; k++) { CNetObj_Projectile Proj; for(unsigned i = 0; i < sizeof(CNetObj_Projectile)/sizeof(int); i++) ((int *)&Proj)[i] = pUnpacker->GetInt(); - + if(pUnpacker->Error()) return; - + g_GameClient.m_pItems->AddExtraProjectile(&Proj); } - + return; } else if(MsgId == NETMSGTYPE_SV_TUNEPARAMS) @@ -508,14 +508,14 @@ void CGameClient::OnMessage(int MsgId, CUnpacker *pUnpacker) // check for unpacking errors if(pUnpacker->Error()) return; - + m_ServerMode = SERVERMODE_PURE; - + // apply new tuning m_Tuning = NewTuning; return; } - + void *pRawMsg = m_NetObjHandler.SecureUnpackMsg(MsgId, pUnpacker); if(!pRawMsg) { @@ -528,7 +528,7 @@ void CGameClient::OnMessage(int MsgId, CUnpacker *pUnpacker) // TODO: this should be done smarter for(int i = 0; i < m_All.m_Num; i++) m_All.m_paComponents[i]->OnMessage(MsgId, pRawMsg); - + if(MsgId == NETMSGTYPE_SV_READYTOENTER) { Client()->EnterGame(); @@ -545,7 +545,7 @@ void CGameClient::OnMessage(int MsgId, CUnpacker *pUnpacker) { if(m_SuppressEvents) return; - + // don't enqueue pseudo-global sounds from demos (created by PlayAndRecord) CNetMsg_Sv_SoundGlobal *pMsg = (CNetMsg_Sv_SoundGlobal *)pRawMsg; if(pMsg->m_SoundID == SOUND_CTF_DROP || pMsg->m_SoundID == SOUND_CTF_RETURN || @@ -554,7 +554,7 @@ void CGameClient::OnMessage(int MsgId, CUnpacker *pUnpacker) g_GameClient.m_pSounds->Enqueue(CSounds::CHN_GLOBAL, pMsg->m_SoundID); else g_GameClient.m_pSounds->Play(CSounds::CHN_GLOBAL, pMsg->m_SoundID, 1.0f, vec2(0,0)); - } + } } void CGameClient::OnStateChange(int NewState, int OldState) @@ -562,7 +562,7 @@ void CGameClient::OnStateChange(int NewState, int OldState) // reset everything when not already connected (to keep gathered stuff) if(NewState < IClient::STATE_ONLINE) OnReset(); - + // then change the state for(int i = 0; i < m_All.m_Num; i++) m_All.m_paComponents[i]->OnStateChange(NewState, OldState); @@ -592,7 +592,7 @@ void CGameClient::ProcessEvents() { if(m_SuppressEvents) return; - + int SnapType = IClient::SNAP_CURRENT; int Num = Client()->SnapNumItems(SnapType); for(int Index = 0; Index < Num; Index++) @@ -636,7 +636,7 @@ void CGameClient::ProcessEvents() void CGameClient::OnNewSnapshot() { m_NewTick = true; - + // clear out the invalid pointers mem_zero(&g_GameClient.m_Snap, sizeof(g_GameClient.m_Snap)); m_Snap.m_LocalClientID = -1; @@ -660,7 +660,7 @@ void CGameClient::OnNewSnapshot() } } } - + ProcessEvents(); if(g_Config.m_DbgStress) @@ -672,7 +672,7 @@ void CGameClient::OnNewSnapshot() for(int i = 0; i < MsgLen; i++) aMessage[i] = 'a'+(rand()%('z'-'a')); aMessage[MsgLen] = 0; - + CNetMsg_Cl_Say Msg; Msg.m_Team = rand()&1; Msg.m_pMessage = aMessage; @@ -683,7 +683,7 @@ void CGameClient::OnNewSnapshot() // go trough all the items in the snapshot and gather the info we want { m_Snap.m_aTeamSize[TEAM_RED] = m_Snap.m_aTeamSize[TEAM_BLUE] = 0; - + int Num = Client()->SnapNumItems(IClient::SNAP_CURRENT); for(int i = 0; i < Num; i++) { @@ -698,19 +698,19 @@ void CGameClient::OnNewSnapshot() IntsToStr(&pInfo->m_Clan0, 3, m_aClients[ClientID].m_aClan); m_aClients[ClientID].m_Country = GetCountryIndex(pInfo->m_Country); IntsToStr(&pInfo->m_Skin0, 6, m_aClients[ClientID].m_aSkinName); - + m_aClients[ClientID].m_UseCustomColor = pInfo->m_UseCustomColor; m_aClients[ClientID].m_ColorBody = pInfo->m_ColorBody; m_aClients[ClientID].m_ColorFeet = pInfo->m_ColorFeet; - + // prepare the info if(m_aClients[ClientID].m_aSkinName[0] == 'x' || m_aClients[ClientID].m_aSkinName[1] == '_') str_copy(m_aClients[ClientID].m_aSkinName, "default", 64); - + m_aClients[ClientID].m_SkinInfo.m_ColorBody = m_pSkins->GetColorV4(m_aClients[ClientID].m_ColorBody); m_aClients[ClientID].m_SkinInfo.m_ColorFeet = m_pSkins->GetColorV4(m_aClients[ClientID].m_ColorFeet); m_aClients[ClientID].m_SkinInfo.m_Size = 64; - + // find new skin m_aClients[ClientID].m_SkinID = g_GameClient.m_pSkins->Find(m_aClients[ClientID].m_aSkinName); if(m_aClients[ClientID].m_SkinID < 0) @@ -719,7 +719,7 @@ void CGameClient::OnNewSnapshot() if(m_aClients[ClientID].m_SkinID < 0) m_aClients[ClientID].m_SkinID = 0; } - + if(m_aClients[ClientID].m_UseCustomColor) m_aClients[ClientID].m_SkinInfo.m_Texture = g_GameClient.m_pSkins->Get(m_aClients[ClientID].m_SkinID)->m_ColorTexture; else @@ -730,33 +730,33 @@ void CGameClient::OnNewSnapshot() } m_aClients[ClientID].UpdateRenderInfo(); - + } else if(Item.m_Type == NETOBJTYPE_PLAYERINFO) { const CNetObj_PlayerInfo *pInfo = (const CNetObj_PlayerInfo *)pData; - + m_aClients[pInfo->m_ClientID].m_Team = pInfo->m_Team; m_aClients[pInfo->m_ClientID].m_Active = true; m_Snap.m_paPlayerInfos[pInfo->m_ClientID] = pInfo; m_Snap.m_NumPlayers++; - + if(pInfo->m_Local) { m_Snap.m_LocalClientID = Item.m_ID; m_Snap.m_pLocalInfo = pInfo; - + if(pInfo->m_Team == TEAM_SPECTATORS) { m_Snap.m_SpecInfo.m_Active = true; m_Snap.m_SpecInfo.m_SpectatorID = SPEC_FREEVIEW; } } - + // calculate team-balance if(pInfo->m_Team != TEAM_SPECTATORS) m_Snap.m_aTeamSize[pInfo->m_Team]++; - + } else if(Item.m_Type == NETOBJTYPE_CHARACTER) { @@ -799,7 +799,7 @@ void CGameClient::OnNewSnapshot() m_Snap.m_paFlags[Item.m_ID%2] = (const CNetObj_Flag *)pData; } } - + // setup local pointers if(m_Snap.m_LocalClientID >= 0) { @@ -856,7 +856,7 @@ void CGameClient::OnNewSnapshot() } } } - + CTuningParams StandardTuning; CServerInfo CurrentServerInfo; Client()->GetServerInfo(&CurrentServerInfo); @@ -881,7 +881,7 @@ void CGameClient::OnPredict() // we can't predict without our own id or own character if(m_Snap.m_LocalClientID == -1 || !m_Snap.m_aCharacters[m_Snap.m_LocalClientID].m_Active) return; - + // don't predict anything if we are paused if(m_Snap.m_pGameInfoObj && m_Snap.m_pGameInfoObj->m_GameStateFlags&GAMESTATEFLAG_PAUSED) { @@ -901,19 +901,19 @@ void CGameClient::OnPredict() { if(!m_Snap.m_aCharacters[i].m_Active) continue; - + g_GameClient.m_aClients[i].m_Predicted.Init(&World, Collision()); World.m_apCharacters[i] = &g_GameClient.m_aClients[i].m_Predicted; g_GameClient.m_aClients[i].m_Predicted.Read(&m_Snap.m_aCharacters[i].m_Cur); } - + // predict for(int Tick = Client()->GameTick()+1; Tick <= Client()->PredGameTick(); Tick++) { // fetch the local if(Tick == Client()->PredGameTick() && World.m_apCharacters[m_Snap.m_LocalClientID]) m_PredictedPrevChar = *World.m_apCharacters[m_Snap.m_LocalClientID]; - + // first calculate where everyone should move for(int c = 0; c < MAX_CLIENTS; c++) { @@ -943,25 +943,25 @@ void CGameClient::OnPredict() World.m_apCharacters[c]->Move(); World.m_apCharacters[c]->Quantize(); } - + // check if we want to trigger effects if(Tick > m_LastNewPredictedTick) { m_LastNewPredictedTick = Tick; m_NewPredictedTick = true; - + if(m_Snap.m_LocalClientID != -1 && World.m_apCharacters[m_Snap.m_LocalClientID]) { vec2 Pos = World.m_apCharacters[m_Snap.m_LocalClientID]->m_Pos; int Events = World.m_apCharacters[m_Snap.m_LocalClientID]->m_TriggeredEvents; if(Events&COREEVENT_GROUND_JUMP) g_GameClient.m_pSounds->PlayAndRecord(CSounds::CHN_WORLD, SOUND_PLAYER_JUMP, 1.0f, Pos); - + /*if(events&COREEVENT_AIR_JUMP) { GameClient.effects->air_jump(pos); GameClient.sounds->play_and_record(SOUNDS::CHN_WORLD, SOUND_PLAYER_AIRJUMP, 1.0f, pos); }*/ - + //if(events&COREEVENT_HOOK_LAUNCH) snd_play_random(CHN_WORLD, SOUND_HOOK_LOOP, 1.0f, pos); //if(events&COREEVENT_HOOK_ATTACH_PLAYER) snd_play_random(CHN_WORLD, SOUND_HOOK_ATTACH_PLAYER, 1.0f, pos); if(Events&COREEVENT_HOOK_ATTACH_GROUND) g_GameClient.m_pSounds->PlayAndRecord(CSounds::CHN_WORLD, SOUND_HOOK_ATTACH_GROUND, 1.0f, Pos); @@ -969,11 +969,11 @@ void CGameClient::OnPredict() //if(events&COREEVENT_HOOK_RETRACT) snd_play_random(CHN_WORLD, SOUND_PLAYER_JUMP, 1.0f, pos); } } - + if(Tick == Client()->PredGameTick() && World.m_apCharacters[m_Snap.m_LocalClientID]) m_PredictedChar = *World.m_apCharacters[m_Snap.m_LocalClientID]; } - + if(g_Config.m_Debug && g_Config.m_ClPredict && m_PredictedTick == Client()->PredGameTick()) { CNetObj_CharacterCore Before = {0}, Now = {0}, BeforePrev = {0}, NowPrev = {0}; @@ -989,12 +989,12 @@ void CGameClient::OnPredict() if(((int *)&Before)[i] != ((int *)&Now)[i]) { char aBuf[256]; - str_format(aBuf, sizeof(aBuf), " %d %d %d (%d %d)", i, ((int *)&Before)[i], ((int *)&Now)[i], ((int *)&BeforePrev)[i], ((int *)&NowPrev)[i]); + str_format(aBuf, sizeof(aBuf), " %d %d %d (%d %d)", i, ((int *)&Before)[i], ((int *)&Now)[i], ((int *)&BeforePrev)[i], ((int *)&NowPrev)[i]); Console()->Print(IConsole::OUTPUT_LEVEL_DEBUG, "client", aBuf); } } } - + m_PredictedTick = Client()->PredGameTick(); } @@ -1022,7 +1022,7 @@ void CGameClient::CClientData::UpdateRenderInfo() m_RenderInfo.m_ColorBody = g_GameClient.m_pSkins->GetColorV4(12895054); m_RenderInfo.m_ColorFeet = g_GameClient.m_pSkins->GetColorV4(12895054); } - } + } } void CGameClient::CClientData::Reset() @@ -1047,7 +1047,7 @@ void CGameClient::SendSwitchTeam(int Team) { CNetMsg_Cl_SetTeam Msg; Msg.m_Team = Team; - Client()->SendPackMsg(&Msg, MSGFLAG_VITAL); + Client()->SendPackMsg(&Msg, MSGFLAG_VITAL); } void CGameClient::SendInfo(bool Start) @@ -1062,7 +1062,7 @@ void CGameClient::SendInfo(bool Start) Msg.m_UseCustomColor = g_Config.m_PlayerUseCustomColor; Msg.m_ColorBody = g_Config.m_PlayerColorBody; Msg.m_ColorFeet = g_Config.m_PlayerColorFeet; - Client()->SendPackMsg(&Msg, MSGFLAG_VITAL); + Client()->SendPackMsg(&Msg, MSGFLAG_VITAL); } else { @@ -1085,7 +1085,7 @@ void CGameClient::SendInfo(bool Start) void CGameClient::SendKill(int ClientID) { CNetMsg_Cl_Kill Msg; - Client()->SendPackMsg(&Msg, MSGFLAG_VITAL); + Client()->SendPackMsg(&Msg, MSGFLAG_VITAL); } void CGameClient::ConTeam(IConsole::IResult *pResult, void *pUserData) diff --git a/src/game/client/gameclient.h b/src/game/client/gameclient.h index 7aa02ace..a89f4e86 100644 --- a/src/game/client/gameclient.h +++ b/src/game/client/gameclient.h @@ -19,18 +19,18 @@ class CGameClient : public IGameClient { MAX_COMPONENTS = 64, }; - + CStack(); void Add(class CComponent *pComponent); - + class CComponent *m_paComponents[MAX_COMPONENTS]; int m_Num; }; - + CStack m_All; CStack m_Input; CNetObjHandler m_NetObjHandler; - + class IEngine *m_pEngine; class IInput *m_pInput; class IGraphics *m_pGraphics; @@ -44,11 +44,11 @@ class CGameClient : public IGameClient class IServerBrowser *m_pServerBrowser; class IEditor *m_pEditor; class IFriends *m_pFriends; - + CLayers m_Layers; class CCollision m_Collision; CUI m_UI; - + void DispatchInput(); void ProcessEvents(); void UpdatePositions(); @@ -60,9 +60,9 @@ class CGameClient : public IGameClient static void ConTeam(IConsole::IResult *pResult, void *pUserData); static void ConKill(IConsole::IResult *pResult, void *pUserData); - + static void ConchainSpecialInfoupdate(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData); - + public: IKernel *Kernel() { return IInterface::Kernel(); } IEngine *Engine() const { return m_pEngine; } @@ -82,7 +82,7 @@ public: class CCollision *Collision() { return &m_Collision; }; class IEditor *Editor() { return m_pEditor; } class IFriends *Friends() { return m_pFriends; } - + int NetobjNumCorrections() { return m_NetObjHandler.NumObjCorrections(); } const char *NetobjCorrectedOn() { return m_NetObjHandler.CorrectedObjOn(); } @@ -92,7 +92,7 @@ public: // TODO: move this CTuningParams m_Tuning; - + enum { SERVERMODE_PURE=0, @@ -124,11 +124,11 @@ public: const CNetObj_PlayerInfo *m_paPlayerInfos[MAX_CLIENTS]; const CNetObj_PlayerInfo *m_paInfoByScore[MAX_CLIENTS]; - + int m_LocalClientID; int m_NumPlayers; int m_aTeamSize[2]; - + // spectate data struct CSpectateInfo { @@ -137,32 +137,32 @@ public: bool m_UsePosition; vec2 m_Position; } m_SpecInfo; - + // struct CCharacterInfo { bool m_Active; - + // snapshots CNetObj_Character m_Prev; CNetObj_Character m_Cur; - + // interpolated position vec2 m_Position; }; - + CCharacterInfo m_aCharacters[MAX_CLIENTS]; }; CSnapState m_Snap; - + // client data struct CClientData { int m_UseCustomColor; int m_ColorBody; int m_ColorFeet; - + char m_aName[MAX_NAME_LENGTH]; char m_aClan[MAX_CLAN_LENGTH]; int m_Country; @@ -173,23 +173,23 @@ public: int m_Emoticon; int m_EmoticonStart; CCharacterCore m_Predicted; - + CTeeRenderInfo m_SkinInfo; // this is what the server reports CTeeRenderInfo m_RenderInfo; // this is what we use - + float m_Angle; bool m_Active; bool m_ChatIgnore; bool m_Friend; - + void UpdateRenderInfo(); void Reset(); }; CClientData m_aClients[MAX_CLIENTS]; - + CRenderTools m_RenderTools; - + void OnReset(); // hooks @@ -209,19 +209,19 @@ public: virtual void OnRconLine(const char *pLine); virtual void OnGameOver(); virtual void OnStartGame(); - + virtual const char *GetItemName(int Type); virtual int GetCountryIndex(int Code); virtual const char *Version(); virtual const char *NetVersion(); - - + + // actions // TODO: move these void SendSwitchTeam(int Team); void SendInfo(bool Start); void SendKill(int ClientID); - + // pointers to all systems class CGameConsole *m_pGameConsole; class CBinds *m_pBinds; @@ -246,12 +246,12 @@ public: inline float HueToRgb(float v1, float v2, float h) { - if(h < 0.0f) h += 1; - if(h > 1.0f) h -= 1; - if((6.0f * h) < 1.0f) return v1 + (v2 - v1) * 6.0f * h; - if((2.0f * h) < 1.0f) return v2; - if((3.0f * h) < 2.0f) return v1 + (v2 - v1) * ((2.0f/3.0f) - h) * 6.0f; - return v1; + if(h < 0.0f) h += 1; + if(h > 1.0f) h -= 1; + if((6.0f * h) < 1.0f) return v1 + (v2 - v1) * 6.0f * h; + if((2.0f * h) < 1.0f) return v2; + if((3.0f * h) < 2.0f) return v1 + (v2 - v1) * ((2.0f/3.0f) - h) * 6.0f; + return v1; } inline vec3 HslToRgb(vec3 HSL) diff --git a/src/game/client/lineinput.cpp b/src/game/client/lineinput.cpp index b5d35ef8..29b891c2 100644 --- a/src/game/client/lineinput.cpp +++ b/src/game/client/lineinput.cpp @@ -27,19 +27,19 @@ bool CLineInput::Manipulate(IInput::CEvent e, char *pStr, int StrMaxSize, int *p int CursorPos = *pCursorPosPtr; int Len = *pStrLenPtr; bool Changes = false; - + if(CursorPos > Len) CursorPos = Len; - + int Code = e.m_Unicode; int k = e.m_Key; - + // 127 is produced on Mac OS X and corresponds to the delete key if (!(Code >= 0 && Code < 32) && Code != 127) { char Tmp[8]; int CharSize = str_utf8_encode(Tmp, Code); - + if (Len < StrMaxSize - CharSize && CursorPos < StrMaxSize - CharSize) { mem_move(pStr + CursorPos + CharSize, pStr + CursorPos, Len - CursorPos + CharSize); @@ -50,7 +50,7 @@ bool CLineInput::Manipulate(IInput::CEvent e, char *pStr, int StrMaxSize, int *p Changes = true; } } - + if(e.m_Flags&IInput::FLAG_PRESS) { if (k == KEY_BACKSPACE && CursorPos > 0) @@ -79,7 +79,7 @@ bool CLineInput::Manipulate(IInput::CEvent e, char *pStr, int StrMaxSize, int *p else if (k == KEY_END) CursorPos = Len; } - + *pCursorPosPtr = CursorPos; *pStrLenPtr = Len; diff --git a/src/game/client/render.cpp b/src/game/client/render.cpp index 2a15326d..5dbc3842 100644 --- a/src/game/client/render.cpp +++ b/src/game/client/render.cpp @@ -30,7 +30,7 @@ static void layershot_end() { if(!config.cl_layershot) return; - + char buf[256]; str_format(buf, sizeof(buf), "screenshots/layers_%04d.png", config.cl_layershot); gfx_screenshot_direct(buf); @@ -49,7 +49,7 @@ void CRenderTools::SelectSprite(SPRITE *pSpr, int Flags, int sx, int sy) float f = sqrtf(h*h + w*w); gs_SpriteWScale = w/f; gs_SpriteHScale = h/f; - + float x1 = x/(float)cx; float x2 = (x+w)/(float)cx; float y1 = y/(float)cy; @@ -69,7 +69,7 @@ void CRenderTools::SelectSprite(SPRITE *pSpr, int Flags, int sx, int sy) x1 = x2; x2 = Temp; } - + Graphics()->QuadsSetSubset(x1, y1, x2, y2); } @@ -140,7 +140,7 @@ void CRenderTools::DrawRoundRectExt(float x, float y, float w, float h, float r, ArrayQ[NumItems++] = IGraphics::CQuadItem(x+r, y+h-r, w-r*2, r); // bottom ArrayQ[NumItems++] = IGraphics::CQuadItem(x, y+r, r, h-r*2); // left ArrayQ[NumItems++] = IGraphics::CQuadItem(x+w-r, y+r, r, h-r*2); // right - + if(!(Corners&1)) ArrayQ[NumItems++] = IGraphics::CQuadItem(x, y, r, r); // TL if(!(Corners&2)) ArrayQ[NumItems++] = IGraphics::CQuadItem(x+w, y, -r, r); // TR if(!(Corners&4)) ArrayQ[NumItems++] = IGraphics::CQuadItem(x, y+h, r, -r); // BL @@ -157,7 +157,7 @@ void CRenderTools::DrawRoundRect(float x, float y, float w, float h, float r) void CRenderTools::DrawUIRect(const CUIRect *r, vec4 Color, int Corners, float Rounding) { Graphics()->TextureSet(-1); - + // TODO: FIX US Graphics()->QuadsBegin(); Graphics()->SetColor(Color.r, Color.g, Color.b, Color.a); @@ -172,7 +172,7 @@ void CRenderTools::RenderTee(CAnimState *pAnim, CTeeRenderInfo *pInfo, int Emote //Graphics()->TextureSet(data->images[IMAGE_CHAR_DEFAULT].id); Graphics()->TextureSet(pInfo->m_Texture); - + // TODO: FIX ME Graphics()->QuadsBegin(); //Graphics()->QuadsDraw(pos.x, pos.y-128, 128, 128); @@ -219,7 +219,7 @@ void CRenderTools::RenderTee(CAnimState *pAnim, CTeeRenderInfo *pInfo, int Emote SelectSprite(SPRITE_TEE_EYE_NORMAL, 0, 0, 0); break; } - + float EyeScale = BaseSize*0.40f; float h = Emote == EMOTE_BLINK ? BaseSize*0.15f : EyeScale; float EyeSeparation = (0.075f - 0.010f*absolute(Direction.x))*BaseSize; @@ -238,10 +238,10 @@ void CRenderTools::RenderTee(CAnimState *pAnim, CTeeRenderInfo *pInfo, int Emote float h = BaseSize/2; Graphics()->QuadsSetRotation(pFoot->m_Angle*pi*2); - + bool Indicate = !pInfo->m_GotAirJump && g_Config.m_ClAirjumpindicator; float cs = 1.0f; // color scale - + if(OutLine) SelectSprite(SPRITE_TEE_FOOT_OUTLINE, 0, 0, 0); else @@ -250,7 +250,7 @@ void CRenderTools::RenderTee(CAnimState *pAnim, CTeeRenderInfo *pInfo, int Emote if(Indicate) cs = 0.5f; } - + Graphics()->SetColor(pInfo->m_ColorFeet.r*cs, pInfo->m_ColorFeet.g*cs, pInfo->m_ColorFeet.b*cs, pInfo->m_ColorFeet.a); IGraphics::CQuadItem QuadItem(Position.x+pFoot->m_X*AnimScale, Position.y+pFoot->m_Y*AnimScale, w, h); Graphics()->QuadsDraw(&QuadItem, 1); @@ -258,8 +258,8 @@ void CRenderTools::RenderTee(CAnimState *pAnim, CTeeRenderInfo *pInfo, int Emote } Graphics()->QuadsEnd(); - - + + } static void CalcScreenParams(float Amount, float WMax, float HMax, float Aspect, float *w, float *h) @@ -267,14 +267,14 @@ static void CalcScreenParams(float Amount, float WMax, float HMax, float Aspect, float f = sqrtf(Amount) / sqrtf(Aspect); *w = f*Aspect; *h = f; - + // limit the view if(*w > WMax) { *w = WMax; *h = *w/Aspect; } - + if(*h > HMax) { *h = HMax; @@ -299,11 +299,11 @@ void CRenderTools::MapscreenToWorld(float CenterX, float CenterY, float Parallax void CRenderTools::RenderTilemapGenerateSkip(class CLayers *pLayers) { - + for(int g = 0; g < pLayers->NumGroups(); g++) { CMapItemGroup *pGroup = pLayers->GetGroup(g); - + for(int l = 0; l < pGroup->m_NumLayers; l++) { CMapItemLayer *pLayer = pLayers->GetLayer(pGroup->m_StartLayer+l); @@ -322,7 +322,7 @@ void CRenderTools::RenderTilemapGenerateSkip(class CLayers *pLayers) if(pTiles[y*pTmap->m_Width+x+sx].m_Index) break; } - + pTiles[y*pTmap->m_Width+x].m_Skip = sx-1; } } diff --git a/src/game/client/render.h b/src/game/client/render.h index fe8d2dd6..10705e56 100644 --- a/src/game/client/render.h +++ b/src/game/client/render.h @@ -19,7 +19,7 @@ public: m_Size = 1.0f; m_GotAirJump = 1; }; - + int m_Texture; vec4 m_ColorBody; vec4 m_ColorFeet; @@ -32,10 +32,10 @@ enum { SPRITE_FLAG_FLIP_Y=1, SPRITE_FLAG_FLIP_X=2, - + LAYERRENDERFLAG_OPAQUE=1, LAYERRENDERFLAG_TRANSPARENT=2, - + TILERENDERFLAG_EXTEND=4, }; @@ -45,7 +45,7 @@ class CRenderTools public: class IGraphics *m_pGraphics; class CUI *m_pUI; - + class IGraphics *Graphics() const { return m_pGraphics; } class CUI *UI() const { return m_pUI; } @@ -59,7 +59,7 @@ public: // rects void DrawRoundRect(float x, float y, float w, float h, float r); void DrawRoundRectExt(float x, float y, float w, float h, float r, int Corners); - + void DrawUIRect(const CUIRect *pRect, vec4 Color, int Corners, float Rounding); // larger rendering methods @@ -75,8 +75,8 @@ public: // helpers void MapscreenToWorld(float CenterX, float CenterY, float ParallaxX, float ParallaxY, - float OffsetX, float OffsetY, float Aspect, float Zoom, float *pPoints); - + float OffsetX, float OffsetY, float Aspect, float Zoom, float *pPoints); + }; #endif diff --git a/src/game/client/render_map.cpp b/src/game/client/render_map.cpp index bffc4c2d..33cc1c7d 100644 --- a/src/game/client/render_map.cpp +++ b/src/game/client/render_map.cpp @@ -16,7 +16,7 @@ void CRenderTools::RenderEvalEnvelope(CEnvPoint *pPoints, int NumPoints, int Cha pResult[3] = 0; return; } - + if(NumPoints == 1) { pResult[0] = fx2f(pPoints[0].m_aValues[0]); @@ -25,7 +25,7 @@ void CRenderTools::RenderEvalEnvelope(CEnvPoint *pPoints, int NumPoints, int Cha pResult[3] = fx2f(pPoints[0].m_aValues[3]); return; } - + Time = fmod(Time, pPoints[NumPoints-1].m_Time/1000.0f)*1000.0f; for(int i = 0; i < NumPoints-1; i++) { @@ -50,18 +50,18 @@ void CRenderTools::RenderEvalEnvelope(CEnvPoint *pPoints, int NumPoints, int Cha { // linear } - + for(int c = 0; c < Channels; c++) { float v0 = fx2f(pPoints[i].m_aValues[c]); float v1 = fx2f(pPoints[i+1].m_aValues[c]); pResult[c] = v0 + (v1-v0) * a; } - + return; } } - + pResult[0] = fx2f(pPoints[NumPoints-1].m_aValues[0]); pResult[1] = fx2f(pPoints[NumPoints-1].m_aValues[1]); pResult[2] = fx2f(pPoints[NumPoints-1].m_aValues[2]); @@ -85,7 +85,7 @@ void CRenderTools::RenderQuads(CQuad *pQuads, int NumQuads, int RenderFlags, voi for(int i = 0; i < NumQuads; i++) { CQuad *q = &pQuads[i]; - + float r=1, g=1, b=1, a=1; if(q->m_ColorEnv >= 0) @@ -96,17 +96,17 @@ void CRenderTools::RenderQuads(CQuad *pQuads, int NumQuads, int RenderFlags, voi g = aChannels[1]; b = aChannels[2]; a = aChannels[3]; - } - + } + bool Opaque = false; if(a < 0.01f || (q->m_aColors[0].a < 0.01f && q->m_aColors[1].a < 0.01f && q->m_aColors[2].a < 0.01f && q->m_aColors[3].a < 0.01f)) Opaque = true; - + if(Opaque && !(RenderFlags&LAYERRENDERFLAG_OPAQUE)) continue; if(!Opaque && !(RenderFlags&LAYERRENDERFLAG_TRANSPARENT)) continue; - + Graphics()->QuadsSetSubsetFree( fx2f(q->m_aTexcoords[0].x), fx2f(q->m_aTexcoords[0].y), fx2f(q->m_aTexcoords[1].x), fx2f(q->m_aTexcoords[1].y), @@ -117,7 +117,7 @@ void CRenderTools::RenderQuads(CQuad *pQuads, int NumQuads, int RenderFlags, voi float OffsetX = 0; float OffsetY = 0; float Rot = 0; - + // TODO: fix this if(q->m_PosEnv >= 0) { @@ -127,7 +127,7 @@ void CRenderTools::RenderQuads(CQuad *pQuads, int NumQuads, int RenderFlags, voi OffsetY = aChannels[1]; Rot = aChannels[2]/360.0f*pi*2; } - + IGraphics::CColorVertex Array[4] = { IGraphics::CColorVertex(0, q->m_aColors[0].r*Conv*r, q->m_aColors[0].g*Conv*g, q->m_aColors[0].b*Conv*b, q->m_aColors[0].a*Conv*a), IGraphics::CColorVertex(1, q->m_aColors[1].r*Conv*r, q->m_aColors[1].g*Conv*g, q->m_aColors[1].b*Conv*b, q->m_aColors[1].a*Conv*a), @@ -136,7 +136,7 @@ void CRenderTools::RenderQuads(CQuad *pQuads, int NumQuads, int RenderFlags, voi Graphics()->SetColorVertex(Array, 4); CPoint *pPoints = q->m_aPoints; - + if(Rot != 0) { static CPoint aRotated[4]; @@ -145,13 +145,13 @@ void CRenderTools::RenderQuads(CQuad *pQuads, int NumQuads, int RenderFlags, voi aRotated[2] = q->m_aPoints[2]; aRotated[3] = q->m_aPoints[3]; pPoints = aRotated; - + Rotate(&q->m_aPoints[4], &aRotated[0], Rot); Rotate(&q->m_aPoints[4], &aRotated[1], Rot); Rotate(&q->m_aPoints[4], &aRotated[2], Rot); Rotate(&q->m_aPoints[4], &aRotated[3], Rot); } - + IGraphics::CFreeformItem Freeform( fx2f(pPoints[0].x)+OffsetX, fx2f(pPoints[0].y)+OffsetY, fx2f(pPoints[1].x)+OffsetX, fx2f(pPoints[1].y)+OffsetY, @@ -159,7 +159,7 @@ void CRenderTools::RenderQuads(CQuad *pQuads, int NumQuads, int RenderFlags, voi fx2f(pPoints[3].x)+OffsetX, fx2f(pPoints[3].y)+OffsetY); Graphics()->QuadsDrawFreeform(&Freeform, 1); } - Graphics()->QuadsEnd(); + Graphics()->QuadsEnd(); } void CRenderTools::RenderTilemap(CTile *pTiles, int w, int h, float Scale, vec4 Color, int RenderFlags) @@ -169,19 +169,19 @@ void CRenderTools::RenderTilemap(CTile *pTiles, int w, int h, float Scale, vec4 Graphics()->GetScreen(&ScreenX0, &ScreenY0, &ScreenX1, &ScreenY1); //Graphics()->MapScreen(screen_x0-50, screen_y0-50, screen_x1+50, screen_y1+50); - // calculate the final pixelsize for the tiles + // calculate the final pixelsize for the tiles float TilePixelSize = 1024/32.0f; float FinalTileSize = Scale/(ScreenX1-ScreenX0) * Graphics()->ScreenWidth(); float FinalTilesetScale = FinalTileSize/TilePixelSize; - + Graphics()->QuadsBegin(); Graphics()->SetColor(Color.r, Color.g, Color.b, Color.a); - + int StartY = (int)(ScreenY0/Scale)-1; int StartX = (int)(ScreenX0/Scale)-1; int EndY = (int)(ScreenY1/Scale)+1; int EndX = (int)(ScreenX1/Scale)+1; - + // adjust the texture shift according to mipmap level float TexSize = 1024.0f; float Frac = (1.25f/TexSize) * (1/FinalTilesetScale); @@ -192,7 +192,7 @@ void CRenderTools::RenderTilemap(CTile *pTiles, int w, int h, float Scale, vec4 { int mx = x; int my = y; - + if(RenderFlags&TILERENDERFLAG_EXTEND) { if(mx<0) @@ -215,14 +215,14 @@ void CRenderTools::RenderTilemap(CTile *pTiles, int w, int h, float Scale, vec4 if(my>=h) continue; // my = h-1; } - + int c = mx + my*w; - + unsigned char Index = pTiles[c].m_Index; if(Index) { unsigned char Flags = pTiles[c].m_Flags; - + bool Render = false; if(Flags&TILEFLAG_OPAQUE) { @@ -234,17 +234,17 @@ void CRenderTools::RenderTilemap(CTile *pTiles, int w, int h, float Scale, vec4 if(RenderFlags&LAYERRENDERFLAG_TRANSPARENT) Render = true; } - + if(Render) { - + int tx = Index%16; int ty = Index/16; int Px0 = tx*(1024/16); int Py0 = ty*(1024/16); int Px1 = Px0+(1024/16)-1; int Py1 = Py0+(1024/16)-1; - + float x0 = Nudge + Px0/TexSize+Frac; float y0 = Nudge + Py0/TexSize+Frac; float x1 = Nudge + Px1/TexSize-Frac; @@ -253,7 +253,7 @@ void CRenderTools::RenderTilemap(CTile *pTiles, int w, int h, float Scale, vec4 float y2 = Nudge + Py1/TexSize-Frac; float x3 = Nudge + Px0/TexSize+Frac; float y3 = Nudge + Py1/TexSize-Frac; - + if(Flags&TILEFLAG_VFLIP) { x0 = x2; @@ -269,14 +269,14 @@ void CRenderTools::RenderTilemap(CTile *pTiles, int w, int h, float Scale, vec4 y3 = y1; y1 = y0; } - + if(Flags&TILEFLAG_ROTATE) { float Tmp = x0; x0 = x3; x3 = x2; x2 = x1; - x1 = Tmp; + x1 = Tmp; Tmp = y0; y0 = y3; y3 = y2; @@ -291,7 +291,7 @@ void CRenderTools::RenderTilemap(CTile *pTiles, int w, int h, float Scale, vec4 } x += pTiles[c].m_Skip; } - + Graphics()->QuadsEnd(); Graphics()->MapScreen(ScreenX0, ScreenY0, ScreenX1, ScreenY1); } diff --git a/src/game/client/ui.cpp b/src/game/client/ui.cpp index 23643e2a..2161bc77 100644 --- a/src/game/client/ui.cpp +++ b/src/game/client/ui.cpp @@ -8,7 +8,7 @@ #include "ui.h" /******************************************************** - UI + UI *********************************************************/ CUI::CUI() @@ -17,14 +17,14 @@ CUI::CUI() m_pActiveItem = 0; m_pLastActiveItem = 0; m_pBecommingHotItem = 0; - + m_MouseX = 0; m_MouseY = 0; m_MouseWorldX = 0; m_MouseWorldY = 0; m_MouseButtons = 0; - m_LastMouseButtons = 0; - + m_LastMouseButtons = 0; + m_Screen.x = 0; m_Screen.y = 0; m_Screen.w = 848.0f; @@ -33,53 +33,53 @@ CUI::CUI() int CUI::Update(float Mx, float My, float Mwx, float Mwy, int Buttons) { - m_MouseX = Mx; - m_MouseY = My; - m_MouseWorldX = Mwx; - m_MouseWorldY = Mwy; - m_LastMouseButtons = m_MouseButtons; - m_MouseButtons = Buttons; - m_pHotItem = m_pBecommingHotItem; - if(m_pActiveItem) - m_pHotItem = m_pActiveItem; - m_pBecommingHotItem = 0; - return 0; + m_MouseX = Mx; + m_MouseY = My; + m_MouseWorldX = Mwx; + m_MouseWorldY = Mwy; + m_LastMouseButtons = m_MouseButtons; + m_MouseButtons = Buttons; + m_pHotItem = m_pBecommingHotItem; + if(m_pActiveItem) + m_pHotItem = m_pActiveItem; + m_pBecommingHotItem = 0; + return 0; } int CUI::MouseInside(const CUIRect *r) { - if(m_MouseX >= r->x && m_MouseX <= r->x+r->w && m_MouseY >= r->y && m_MouseY <= r->y+r->h) - return 1; - return 0; + if(m_MouseX >= r->x && m_MouseX <= r->x+r->w && m_MouseY >= r->y && m_MouseY <= r->y+r->h) + return 1; + return 0; } CUIRect *CUI::Screen() { - float Aspect = Graphics()->ScreenAspect(); - float w, h; + float Aspect = Graphics()->ScreenAspect(); + float w, h; - h = 600; - w = Aspect*h; + h = 600; + w = Aspect*h; - m_Screen.w = w; - m_Screen.h = h; + m_Screen.w = w; + m_Screen.h = h; - return &m_Screen; + return &m_Screen; } void CUI::SetScale(float s) { - g_Config.m_UiScale = (int)(s*100.0f); + g_Config.m_UiScale = (int)(s*100.0f); } float CUI::Scale() { - return g_Config.m_UiScale/100.0f; + return g_Config.m_UiScale/100.0f; } float CUIRect::Scale() const { - return g_Config.m_UiScale/100.0f; + return g_Config.m_UiScale/100.0f; } void CUI::ClipEnable(const CUIRect *r) @@ -97,175 +97,175 @@ void CUI::ClipDisable() void CUIRect::HSplitMid(CUIRect *pTop, CUIRect *pBottom) const { CUIRect r = *this; - float Cut = r.h/2; - - if(pTop) - { - pTop->x = r.x; - pTop->y = r.y; - pTop->w = r.w; - pTop->h = Cut; - } - - if(pBottom) - { - pBottom->x = r.x; - pBottom->y = r.y + Cut; - pBottom->w = r.w; - pBottom->h = r.h - Cut; - } + float Cut = r.h/2; + + if(pTop) + { + pTop->x = r.x; + pTop->y = r.y; + pTop->w = r.w; + pTop->h = Cut; + } + + if(pBottom) + { + pBottom->x = r.x; + pBottom->y = r.y + Cut; + pBottom->w = r.w; + pBottom->h = r.h - Cut; + } } void CUIRect::HSplitTop(float Cut, CUIRect *pTop, CUIRect *pBottom) const { - CUIRect r = *this; - Cut *= Scale(); - - if (pTop) - { - pTop->x = r.x; - pTop->y = r.y; - pTop->w = r.w; - pTop->h = Cut; - } - - if (pBottom) - { - pBottom->x = r.x; - pBottom->y = r.y + Cut; - pBottom->w = r.w; - pBottom->h = r.h - Cut; - } + CUIRect r = *this; + Cut *= Scale(); + + if (pTop) + { + pTop->x = r.x; + pTop->y = r.y; + pTop->w = r.w; + pTop->h = Cut; + } + + if (pBottom) + { + pBottom->x = r.x; + pBottom->y = r.y + Cut; + pBottom->w = r.w; + pBottom->h = r.h - Cut; + } } void CUIRect::HSplitBottom(float Cut, CUIRect *pTop, CUIRect *pBottom) const { - CUIRect r = *this; - Cut *= Scale(); - - if (pTop) - { - pTop->x = r.x; - pTop->y = r.y; - pTop->w = r.w; - pTop->h = r.h - Cut; - } - - if (pBottom) - { - pBottom->x = r.x; - pBottom->y = r.y + r.h - Cut; - pBottom->w = r.w; - pBottom->h = Cut; - } + CUIRect r = *this; + Cut *= Scale(); + + if (pTop) + { + pTop->x = r.x; + pTop->y = r.y; + pTop->w = r.w; + pTop->h = r.h - Cut; + } + + if (pBottom) + { + pBottom->x = r.x; + pBottom->y = r.y + r.h - Cut; + pBottom->w = r.w; + pBottom->h = Cut; + } } void CUIRect::VSplitMid(CUIRect *pLeft, CUIRect *pRight) const { - CUIRect r = *this; - float Cut = r.w/2; -// Cut *= Scale(); - - if (pLeft) - { - pLeft->x = r.x; - pLeft->y = r.y; - pLeft->w = Cut; - pLeft->h = r.h; - } - - if (pRight) - { - pRight->x = r.x + Cut; - pRight->y = r.y; - pRight->w = r.w - Cut; - pRight->h = r.h; - } + CUIRect r = *this; + float Cut = r.w/2; +// Cut *= Scale(); + + if (pLeft) + { + pLeft->x = r.x; + pLeft->y = r.y; + pLeft->w = Cut; + pLeft->h = r.h; + } + + if (pRight) + { + pRight->x = r.x + Cut; + pRight->y = r.y; + pRight->w = r.w - Cut; + pRight->h = r.h; + } } void CUIRect::VSplitLeft(float Cut, CUIRect *pLeft, CUIRect *pRight) const { - CUIRect r = *this; - Cut *= Scale(); - - if (pLeft) - { - pLeft->x = r.x; - pLeft->y = r.y; - pLeft->w = Cut; - pLeft->h = r.h; - } - - if (pRight) - { - pRight->x = r.x + Cut; - pRight->y = r.y; - pRight->w = r.w - Cut; - pRight->h = r.h; - } + CUIRect r = *this; + Cut *= Scale(); + + if (pLeft) + { + pLeft->x = r.x; + pLeft->y = r.y; + pLeft->w = Cut; + pLeft->h = r.h; + } + + if (pRight) + { + pRight->x = r.x + Cut; + pRight->y = r.y; + pRight->w = r.w - Cut; + pRight->h = r.h; + } } void CUIRect::VSplitRight(float Cut, CUIRect *pLeft, CUIRect *pRight) const { - CUIRect r = *this; - Cut *= Scale(); - - if (pLeft) - { - pLeft->x = r.x; - pLeft->y = r.y; - pLeft->w = r.w - Cut; - pLeft->h = r.h; - } - - if (pRight) - { - pRight->x = r.x + r.w - Cut; - pRight->y = r.y; - pRight->w = Cut; - pRight->h = r.h; - } + CUIRect r = *this; + Cut *= Scale(); + + if (pLeft) + { + pLeft->x = r.x; + pLeft->y = r.y; + pLeft->w = r.w - Cut; + pLeft->h = r.h; + } + + if (pRight) + { + pRight->x = r.x + r.w - Cut; + pRight->y = r.y; + pRight->w = Cut; + pRight->h = r.h; + } } void CUIRect::Margin(float Cut, CUIRect *pOtherRect) const { - CUIRect r = *this; + CUIRect r = *this; Cut *= Scale(); - pOtherRect->x = r.x + Cut; - pOtherRect->y = r.y + Cut; - pOtherRect->w = r.w - 2*Cut; - pOtherRect->h = r.h - 2*Cut; + pOtherRect->x = r.x + Cut; + pOtherRect->y = r.y + Cut; + pOtherRect->w = r.w - 2*Cut; + pOtherRect->h = r.h - 2*Cut; } void CUIRect::VMargin(float Cut, CUIRect *pOtherRect) const { - CUIRect r = *this; + CUIRect r = *this; Cut *= Scale(); - pOtherRect->x = r.x + Cut; - pOtherRect->y = r.y; - pOtherRect->w = r.w - 2*Cut; - pOtherRect->h = r.h; + pOtherRect->x = r.x + Cut; + pOtherRect->y = r.y; + pOtherRect->w = r.w - 2*Cut; + pOtherRect->h = r.h; } void CUIRect::HMargin(float Cut, CUIRect *pOtherRect) const { - CUIRect r = *this; + CUIRect r = *this; Cut *= Scale(); - pOtherRect->x = r.x; - pOtherRect->y = r.y + Cut; - pOtherRect->w = r.w; - pOtherRect->h = r.h - 2*Cut; + pOtherRect->x = r.x; + pOtherRect->y = r.y + Cut; + pOtherRect->w = r.w; + pOtherRect->h = r.h - 2*Cut; } int CUI::DoButtonLogic(const void *pID, const char *pText, int Checked, const CUIRect *pRect) { - // logic - int ReturnValue = 0; - int Inside = MouseInside(pRect); + // logic + int ReturnValue = 0; + int Inside = MouseInside(pRect); static int ButtonUsed = 0; if(ActiveItem() == pID) @@ -284,25 +284,25 @@ int CUI::DoButtonLogic(const void *pID, const char *pText, int Checked, const CU SetActiveItem(pID); ButtonUsed = 0; } - + if(MouseButton(1)) { SetActiveItem(pID); ButtonUsed = 1; } } - + if(Inside) SetHotItem(pID); - return ReturnValue; + return ReturnValue; } /* int CUI::DoButton(const void *id, const char *text, int checked, const CUIRect *r, ui_draw_button_func draw_func, const void *extra) { - // logic - int ret = 0; - int inside = ui_MouseInside(r); + // logic + int ret = 0; + int inside = ui_MouseInside(r); static int button_used = 0; if(ui_ActiveItem() == id) @@ -321,41 +321,41 @@ int CUI::DoButton(const void *id, const char *text, int checked, const CUIRect * ui_SetActiveItem(id); button_used = 0; } - + if(ui_MouseButton(1)) { ui_SetActiveItem(id); button_used = 1; } } - + if(inside) ui_SetHotItem(id); if(draw_func) - draw_func(id, text, checked, r, extra); - return ret; + draw_func(id, text, checked, r, extra); + return ret; }*/ void CUI::DoLabel(const CUIRect *r, const char *pText, float Size, int Align, int MaxWidth) { // TODO: FIX ME!!!! - //Graphics()->BlendNormal(); - if(Align == 0) - { - float tw = TextRender()->TextWidth(0, Size, pText, MaxWidth); - TextRender()->Text(0, r->x + r->w/2-tw/2, r->y - Size/10, Size, pText, MaxWidth); + //Graphics()->BlendNormal(); + if(Align == 0) + { + float tw = TextRender()->TextWidth(0, Size, pText, MaxWidth); + TextRender()->Text(0, r->x + r->w/2-tw/2, r->y - Size/10, Size, pText, MaxWidth); } else if(Align < 0) - TextRender()->Text(0, r->x, r->y - Size/10, Size, pText, MaxWidth); + TextRender()->Text(0, r->x, r->y - Size/10, Size, pText, MaxWidth); else if(Align > 0) { - float tw = TextRender()->TextWidth(0, Size, pText, MaxWidth); - TextRender()->Text(0, r->x + r->w-tw, r->y - Size/10, Size, pText, MaxWidth); + float tw = TextRender()->TextWidth(0, Size, pText, MaxWidth); + TextRender()->Text(0, r->x + r->w-tw, r->y - Size/10, Size, pText, MaxWidth); } } void CUI::DoLabelScaled(const CUIRect *r, const char *pText, float Size, int Align, int MaxWidth) { - DoLabel(r, pText, Size*Scale(), Align, MaxWidth); + DoLabel(r, pText, Size*Scale(), Align, MaxWidth); } \ No newline at end of file diff --git a/src/game/client/ui.h b/src/game/client/ui.h index c339de73..017abf7c 100644 --- a/src/game/client/ui.h +++ b/src/game/client/ui.h @@ -8,8 +8,8 @@ class CUIRect // TODO: Refactor: Redo UI scaling float Scale() const; public: - float x, y, w, h; - + float x, y, w, h; + void HSplitMid(CUIRect *pTop, CUIRect *pBottom) const; void HSplitTop(float Cut, CUIRect *pTop, CUIRect *pBottom) const; void HSplitBottom(float Cut, CUIRect *pTop, CUIRect *pBottom) const; @@ -20,7 +20,7 @@ public: void Margin(float Cut, CUIRect *pOtherRect) const; void VMargin(float Cut, CUIRect *pOtherRect) const; void HMargin(float Cut, CUIRect *pOtherRect) const; - + }; class CUI @@ -33,11 +33,11 @@ class CUI float m_MouseWorldX, m_MouseWorldY; // in world space unsigned m_MouseButtons; unsigned m_LastMouseButtons; - + CUIRect m_Screen; class IGraphics *m_pGraphics; class ITextRender *m_pTextRender; - + public: // TODO: Refactor: Fill this in void SetGraphics(class IGraphics *pGraphics, class ITextRender *pTextRender) { m_pGraphics = pGraphics; m_pTextRender = pTextRender;} @@ -52,12 +52,12 @@ public: CORNER_TR=2, CORNER_BL=4, CORNER_BR=8, - + CORNER_T=CORNER_TL|CORNER_TR, CORNER_B=CORNER_BL|CORNER_BR, CORNER_R=CORNER_TR|CORNER_BR, CORNER_L=CORNER_TL|CORNER_BL, - + CORNER_ALL=CORNER_T|CORNER_B }; @@ -83,13 +83,13 @@ public: CUIRect *Screen(); void ClipEnable(const CUIRect *pRect); void ClipDisable(); - + // TODO: Refactor: Redo UI scaling void SetScale(float s); float Scale(); int DoButtonLogic(const void *pID, const char *pText /* TODO: Refactor: Remove */, int Checked, const CUIRect *pRect); - + // TODO: Refactor: Remove this? void DoLabel(const CUIRect *pRect, const char *pText, float Size, int Align, int MaxWidth = -1); void DoLabelScaled(const CUIRect *pRect, const char *pText, float Size, int Align, int MaxWidth = -1); diff --git a/src/game/collision.cpp b/src/game/collision.cpp index 8acddc6e..ca932d9b 100644 --- a/src/game/collision.cpp +++ b/src/game/collision.cpp @@ -26,14 +26,14 @@ void CCollision::Init(class CLayers *pLayers) m_Width = m_pLayers->GameLayer()->m_Width; m_Height = m_pLayers->GameLayer()->m_Height; m_pTiles = static_cast<CTile *>(m_pLayers->Map()->GetData(m_pLayers->GameLayer()->m_Data)); - + for(int i = 0; i < m_Width*m_Height; i++) { int Index = m_pTiles[i].m_Index; - + if(Index > 128) continue; - + switch(Index) { case TILE_DEATH: @@ -55,7 +55,7 @@ int CCollision::GetTile(int x, int y) { int Nx = clamp(x/32, 0, m_Width-1); int Ny = clamp(y/32, 0, m_Height-1); - + return m_pTiles[Ny*m_Width+Nx].m_Index > 128 ? 0 : m_pTiles[Ny*m_Width+Nx].m_Index; } @@ -70,7 +70,7 @@ int CCollision::IntersectLine(vec2 Pos0, vec2 Pos1, vec2 *pOutCollision, vec2 *p float Distance = distance(Pos0, Pos1); int End(Distance+1); vec2 Last = Pos0; - + for(int i = 0; i < End; i++) { float a = i/Distance; @@ -97,7 +97,7 @@ void CCollision::MovePoint(vec2 *pInoutPos, vec2 *pInoutVel, float Elasticity, i { if(pBounces) *pBounces = 0; - + vec2 Pos = *pInoutPos; vec2 Vel = *pInoutVel; if(CheckPoint(Pos + Vel)) @@ -107,7 +107,7 @@ void CCollision::MovePoint(vec2 *pInoutPos, vec2 *pInoutVel, float Elasticity, i { pInoutVel->x *= -Elasticity; if(pBounces) - (*pBounces)++; + (*pBounces)++; Affected++; } @@ -115,10 +115,10 @@ void CCollision::MovePoint(vec2 *pInoutPos, vec2 *pInoutVel, float Elasticity, i { pInoutVel->y *= -Elasticity; if(pBounces) - (*pBounces)++; + (*pBounces)++; Affected++; } - + if(Affected == 0) { pInoutVel->x *= -Elasticity; @@ -150,10 +150,10 @@ void CCollision::MoveBox(vec2 *pInoutPos, vec2 *pInoutVel, vec2 Size, float Elas // do the move vec2 Pos = *pInoutPos; vec2 Vel = *pInoutVel; - + float Distance = length(Vel); int Max = (int)Distance; - + if(Distance > 0.00001f) { //vec2 old_pos = pos; @@ -163,27 +163,27 @@ void CCollision::MoveBox(vec2 *pInoutPos, vec2 *pInoutVel, vec2 Size, float Elas //float amount = i/(float)max; //if(max == 0) //amount = 0; - + vec2 NewPos = Pos + Vel*Fraction; // TODO: this row is not nice - + if(TestBox(vec2(NewPos.x, NewPos.y), Size)) { int Hits = 0; - + if(TestBox(vec2(Pos.x, NewPos.y), Size)) { NewPos.y = Pos.y; Vel.y *= -Elasticity; Hits++; } - + if(TestBox(vec2(NewPos.x, Pos.y), Size)) { NewPos.x = Pos.x; Vel.x *= -Elasticity; Hits++; } - + // neither of the tests got a collision. // this is a real _corner case_! if(Hits == 0) @@ -194,11 +194,11 @@ void CCollision::MoveBox(vec2 *pInoutPos, vec2 *pInoutVel, vec2 Size, float Elas Vel.x *= -Elasticity; } } - + Pos = NewPos; } } - + *pInoutPos = Pos; *pInoutVel = Vel; } diff --git a/src/game/editor/ed_editor.h b/src/game/editor/ed_editor.h index 9d220bd6..aab757e1 100644 --- a/src/game/editor/ed_editor.h +++ b/src/game/editor/ed_editor.h @@ -30,7 +30,7 @@ enum { MODE_LAYERS=0, MODE_IMAGES, - + DIALOG_NONE=0, DIALOG_FILE, }; @@ -48,7 +48,7 @@ public: array<CEnvPoint> m_lPoints; char m_aName[32]; float m_Bottom, m_Top; - + CEnvelope(int Chan) { m_Channels = Chan; @@ -56,7 +56,7 @@ public: m_Bottom = 0; m_Top = 0; } - + void Resort() { sort(m_lPoints.all()); @@ -80,13 +80,13 @@ public: } } } - + int Eval(float Time, float *pResult) { CRenderTools::RenderEvalEnvelope(m_lPoints.base_ptr(), m_lPoints.size(), m_Channels, Time, pResult); return m_Channels; } - + void AddPoint(int Time, int v0, int v1=0, int v2=0, int v3=0) { CEnvPoint p; @@ -99,7 +99,7 @@ public: m_lPoints.add(p); Resort(); } - + float EndTime() { if(m_lPoints.size()) @@ -130,12 +130,12 @@ public: m_Flags = 0; m_pEditor = 0; } - + virtual ~CLayer() { } - - + + virtual void BrushSelecting(CUIRect Rect) {} virtual int BrushGrab(CLayerGroup *pBrush, CUIRect Rect) { return 0; } virtual void FillSelection(bool Empty, CLayer *pBrush, CUIRect Rect) {} @@ -144,15 +144,15 @@ public: virtual void BrushFlipX() {} virtual void BrushFlipY() {} virtual void BrushRotate(float Amount) {} - + virtual void Render() {} virtual int RenderProperties(CUIRect *pToolbox) { return 0; } - + virtual void ModifyImageIndex(INDEX_MODIFY_FUNC pfnFunc) {} virtual void ModifyEnvelopeIndex(INDEX_MODIFY_FUNC pfnFunc) {} - + virtual void GetSize(float *w, float *h) { *w = 0; *h = 0;} - + const char *m_pTypeName; int m_Type; int m_Flags; @@ -166,49 +166,49 @@ class CLayerGroup { public: class CEditorMap *m_pMap; - + array<CLayer*> m_lLayers; - + int m_OffsetX; int m_OffsetY; int m_ParallaxX; int m_ParallaxY; - + int m_UseClipping; int m_ClipX; int m_ClipY; int m_ClipW; int m_ClipH; - + const char *m_pName; bool m_GameGroup; bool m_Visible; bool m_SaveToMap; - + CLayerGroup(); ~CLayerGroup(); - + void Convert(CUIRect *pRect); void Render(); void MapScreen(); void Mapping(float *pPoints); void GetSize(float *w, float *h); - + void DeleteLayer(int Index); int SwapLayers(int Index0, int Index1); - - bool IsEmpty() const + + bool IsEmpty() const { return m_lLayers.size() == 0; } - - void Clear() - { + + void Clear() + { m_lLayers.delete_all(); } - + void AddLayer(CLayer *l); void ModifyImageIndex(INDEX_MODIFY_FUNC Func) @@ -216,7 +216,7 @@ public: for(int i = 0; i < m_lLayers.size(); i++) m_lLayers[i]->ModifyImageIndex(Func); } - + void ModifyEnvelopeIndex(INDEX_MODIFY_FUNC Func) { for(int i = 0; i < m_lLayers.size(); i++) @@ -228,7 +228,7 @@ class CEditorImage : public CImageInfo { public: CEditor *m_pEditor; - + CEditorImage(CEditor *pEditor) { m_pEditor = pEditor; @@ -240,11 +240,11 @@ public: m_pData = 0; m_Format = 0; } - + ~CEditorImage(); - + void AnalyseTileFlags(); - + int m_TexID; int m_External; char m_aName[128]; @@ -267,10 +267,10 @@ public: array<CLayerGroup*> m_lGroups; array<CEditorImage*> m_lImages; array<CEnvelope*> m_lEnvelopes; - + class CLayerGame *m_pGameLayer; CLayerGroup *m_pGameGroup; - + CEnvelope *NewEnvelope(int Channels) { m_Modified = true; @@ -280,7 +280,7 @@ public: } void DeleteEnvelope(int Index); - + CLayerGroup *NewGroup() { m_Modified = true; @@ -289,7 +289,7 @@ public: m_lGroups.add(g); return g; } - + int SwapGroups(int Index0, int Index1) { if(Index0 < 0 || Index0 >= m_lGroups.size()) return Index0; @@ -299,7 +299,7 @@ public: swap(m_lGroups[Index0], m_lGroups[Index1]); return Index1; } - + void DeleteGroup(int Index) { if(Index < 0 || Index >= m_lGroups.size()) return; @@ -307,25 +307,25 @@ public: delete m_lGroups[Index]; m_lGroups.remove_index(Index); } - + void ModifyImageIndex(INDEX_MODIFY_FUNC pfnFunc) { m_Modified = true; for(int i = 0; i < m_lGroups.size(); i++) m_lGroups[i]->ModifyImageIndex(pfnFunc); } - + void ModifyEnvelopeIndex(INDEX_MODIFY_FUNC pfnFunc) { m_Modified = true; for(int i = 0; i < m_lGroups.size(); i++) m_lGroups[i]->ModifyEnvelopeIndex(pfnFunc); } - + void Clean(); void CreateDefault(int EntitiesTexture); - // io + // io int Save(class IStorage *pStorage, const char *pFilename); int Load(class IStorage *pStorage, const char *pFilename, int StorageType); }; @@ -383,17 +383,17 @@ public: virtual void BrushFlipX(); virtual void BrushFlipY(); virtual void BrushRotate(float Amount); - + virtual void ShowInfo(); virtual int RenderProperties(CUIRect *pToolbox); virtual void ModifyImageIndex(INDEX_MODIFY_FUNC pfnFunc); virtual void ModifyEnvelopeIndex(INDEX_MODIFY_FUNC pfnFunc); - + void PrepareForSave(); - void GetSize(float *w, float *h) { *w = m_Width*32.0f; *h = m_Height*32.0f; } - + void GetSize(float *w, float *h) { *w = m_Width*32.0f; *h = m_Height*32.0f; } + int m_TexID; int m_Game; int m_Image; @@ -418,14 +418,14 @@ public: virtual void BrushFlipX(); virtual void BrushFlipY(); virtual void BrushRotate(float Amount); - + virtual int RenderProperties(CUIRect *pToolbox); virtual void ModifyImageIndex(INDEX_MODIFY_FUNC pfnFunc); virtual void ModifyEnvelopeIndex(INDEX_MODIFY_FUNC pfnFunc); - + void GetSize(float *w, float *h); - + int m_Image; array<CQuad> m_lQuads; }; @@ -475,7 +475,7 @@ public: m_ValidSaveFilename = false; m_PopupEventActivated = false; - + m_FileDialogStorageType = 0; m_pFileDialogTitle = 0; m_pFileDialogButtonText = 0; @@ -495,7 +495,7 @@ public: m_WorldOffsetY = 0; m_EditorOffsetX = 0.0f; m_EditorOffsetY = 0.0f; - + m_WorldZoom = 1.0f; m_ZoomLevel = 200; m_LockMouse = false; @@ -504,36 +504,36 @@ public: m_MouseDeltaY = 0; m_MouseDeltaWx = 0; m_MouseDeltaWy = 0; - + m_GuiActive = true; m_ProofBorders = false; - + m_ShowTileInfo = false; m_ShowDetail = true; m_Animate = false; m_AnimateStart = 0; m_AnimateTime = 0; m_AnimateSpeed = 1; - + m_ShowEnvelopeEditor = 0; - + ms_CheckerTexture = 0; ms_BackgroundTexture = 0; ms_CursorTexture = 0; ms_EntitiesTexture = 0; - + ms_pUiGotContext = 0; } - + virtual void Init(); virtual void UpdateAndRender(); virtual bool HasUnsavedData() { return m_Map.m_Modified; } - + void FilelistPopulate(int StorageType); void InvokeFileDialog(int StorageType, int FileType, const char *pTitle, const char *pButtonText, const char *pBasepath, const char *pDefaultName, void (*pfnFunc)(const char *pFilename, int StorageType, void *pUser), void *pUser); - + void Reset(bool CreateDefault=true); int Save(const char *pFilename); int Load(const char *pFilename, int StorageType); @@ -544,9 +544,9 @@ public: CLayer *GetSelectedLayerType(int Index, int Type); CLayer *GetSelectedLayer(int Index); CLayerGroup *GetSelectedGroup(); - + int DoProperties(CUIRect *pToolbox, CProperty *pProps, int *pIDs, int *pNewVal); - + int m_Mode; int m_Dialog; const char *m_pTooltip; @@ -573,7 +573,7 @@ public: MAX_PATH_LENGTH = 512 }; - + int m_FileDialogStorageType; const char *m_pFileDialogTitle; const char *m_pFileDialogButtonText; @@ -597,7 +597,7 @@ public: bool m_IsDir; bool m_IsLink; int m_StorageType; - + bool operator<(const CFilelistItem &Other) { return !str_comp(m_aFilename, "..") ? true : !str_comp(Other.m_aFilename, "..") ? false : m_IsDir && !Other.m_IsDir ? true : !m_IsDir && Other.m_IsDir ? false : str_comp_filenames(m_aFilename, Other.m_aFilename) < 0; } @@ -621,36 +621,36 @@ public: float m_MouseDeltaY; float m_MouseDeltaWx; float m_MouseDeltaWy; - + bool m_ShowTileInfo; bool m_ShowDetail; bool m_Animate; int64 m_AnimateStart; float m_AnimateTime; float m_AnimateSpeed; - + int m_ShowEnvelopeEditor; - + int m_SelectedLayer; int m_SelectedGroup; int m_SelectedQuad; int m_SelectedPoints; int m_SelectedEnvelope; int m_SelectedImage; - + static int ms_CheckerTexture; static int ms_BackgroundTexture; static int ms_CursorTexture; static int ms_EntitiesTexture; - + CLayerGroup m_Brush; CLayerTiles m_TilesetPicker; - + static const void *ms_pUiGotContext; - + CEditorMap m_Map; - - void DoMapBorder(); + + void DoMapBorder(); int DoButton_Editor_Common(const void *pID, const char *pText, int Checked, const CUIRect *pRect, int Flags, const char *pToolTip); int DoButton_Editor(const void *pID, const char *pText, int Checked, const CUIRect *pRect, int Flags, const char *pToolTip); @@ -660,17 +660,17 @@ public: int DoButton_ButtonInc(const void *pID, const char *pText, int Checked, const CUIRect *pRect, int Flags, const char *pToolTip); int DoButton_File(const void *pID, const char *pText, int Checked, const CUIRect *pRect, int Flags, const char *pToolTip); - + int DoButton_Menu(const void *pID, const char *pText, int Checked, const CUIRect *pRect, int Flags, const char *pToolTip); int DoButton_MenuItem(const void *pID, const char *pText, int Checked, const CUIRect *pRect, int Flags=0, const char *pToolTip=0); - + int DoEditBox(void *pID, const CUIRect *pRect, char *pStr, unsigned StrSize, float FontSize, bool Hidden=false); void RenderBackground(CUIRect View, int Texture, float Size, float Brightness); void UiInvokePopupMenu(void *pID, int Flags, float X, float Y, float W, float H, int (*pfnFunc)(CEditor *pEditor, CUIRect Rect), void *pExtra=0); void UiDoPopupMenu(); - + int UiDoValueSelector(void *pID, CUIRect *pRect, const char *pLabel, int Current, int Min, int Max, int Step, float Scale, const char *pToolTip); static int PopupGroup(CEditor *pEditor, CUIRect View); @@ -693,7 +693,7 @@ public: void PopupSelectGametileOpInvoke(float x, float y); int PopupSelectGameTileOpResult(); - + vec4 ButtonColorMul(const void *pID); void DoQuadPoint(CQuad *pQuad, int QuadIndex, int v); @@ -702,16 +702,16 @@ public: void DoQuad(CQuad *pQuad, int Index); float UiDoScrollbarV(const void *pID, const CUIRect *pRect, float Current); vec4 GetButtonColor(const void *pID, int Checked); - + static void ReplaceImage(const char *pFilename, int StorageType, void *pUser); static void AddImage(const char *pFilename, int StorageType, void *pUser); - + void RenderImages(CUIRect Toolbox, CUIRect Toolbar, CUIRect View); void RenderLayers(CUIRect Toolbox, CUIRect Toolbar, CUIRect View); void RenderModebar(CUIRect View); void RenderStatusbar(CUIRect View); void RenderEnvelopeEditor(CUIRect View); - + void RenderMenubar(CUIRect Menubar); void RenderFileDialog(); diff --git a/src/game/editor/ed_io.cpp b/src/game/editor/ed_io.cpp index 4dd71245..a5ead97a 100644 --- a/src/game/editor/ed_io.cpp +++ b/src/game/editor/ed_io.cpp @@ -67,7 +67,7 @@ void editor_load_old(DATAFILE *df, MAP *map) MAPRES_FLAGSTAND_RED=5, MAPRES_FLAGSTAND_BLUE=6, MAPRES_ENTS_END, - + ITEM_NULL=0, ITEM_WEAPON_GUN=0x00010001, ITEM_WEAPON_SHOTGUN=0x00010002, @@ -78,7 +78,7 @@ void editor_load_old(DATAFILE *df, MAP *map) ITEM_ARMOR=0x00030001, ITEM_NINJA=0x00040001, }; - + enum { MAPRES_REGISTERED=0x8000, @@ -97,9 +97,9 @@ void editor_load_old(DATAFILE *df, MAP *map) for(int t = 0; t < num; t++) { mapres_tilemap *tmap = (mapres_tilemap *)datafile_get_item(df, start+t,0,0); - + CLayerTiles *l = new CLayerTiles(tmap->width, tmap->height); - + if(tmap->main) { // move game layer to correct position @@ -108,7 +108,7 @@ void editor_load_old(DATAFILE *df, MAP *map) if(map->groups[0]->layers[i] == pEditor->map.game_layer) map->groups[0]->swap_layers(i, i+1); } - + game_width = tmap->width; game_height = tmap->height; } @@ -119,18 +119,18 @@ void editor_load_old(DATAFILE *df, MAP *map) // process the data unsigned char *src_data = (unsigned char *)datafile_get_data(df, tmap->data); CTile *dst_data = l->tiles; - + for(int y = 0; y < tmap->height; y++) for(int x = 0; x < tmap->width; x++, dst_data++, src_data+=2) { dst_data->index = src_data[0]; dst_data->flags = src_data[1]; } - + l->image = tmap->image; } } - + // load images { int start, count; @@ -144,18 +144,18 @@ void editor_load_old(DATAFILE *df, MAP *map) img->width = imgres->width; img->height = imgres->height; img->format = CImageInfo::FORMAT_RGBA; - + // copy image data img->data = mem_alloc(img->width*img->height*4, 1); mem_copy(img->data, data, img->width*img->height*4); img->tex_id = Graphics()->LoadTextureRaw(img->width, img->height, img->format, img->data, CImageInfo::FORMAT_AUTO, 0); map->images.add(img); - + // unload image datafile_unload_data(df, imgres->image_data); } } - + // load entities { CLayerGame *g = map->game_layer; @@ -173,7 +173,7 @@ void editor_load_old(DATAFILE *df, MAP *map) int x = e->x/32; int y = e->y/32; int id = -1; - + if(t == MAPRES_SPAWNPOINT) id = ENTITY_SPAWN; else if(t == MAPRES_SPAWNPOINT_RED) id = ENTITY_SPAWN_RED; else if(t == MAPRES_SPAWNPOINT_BLUE) id = ENTITY_SPAWN_BLUE; @@ -187,7 +187,7 @@ void editor_load_old(DATAFILE *df, MAP *map) else if(e->data[0] == ITEM_ARMOR) id = ENTITY_ARMOR_1; else if(e->data[0] == ITEM_HEALTH) id = ENTITY_HEALTH_1; } - + if(id > 0 && x >= 0 && x < g->width && y >= 0 && y < g->height) g->tiles[y*g->width+x].index = id+ENTITY_OFFSET; } @@ -212,7 +212,7 @@ int CEditorMap::Save(class IStorage *pStorage, const char *pFileName) m_pEditor->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "editor", aBuf); return 0; } - + // save version { CMapItemVersion Item; @@ -224,14 +224,14 @@ int CEditorMap::Save(class IStorage *pStorage, const char *pFileName) for(int i = 0; i < m_lImages.size(); i++) { CEditorImage *pImg = m_lImages[i]; - + // analyse the image for when saving (should be done when we load the image) // TODO! pImg->AnalyseTileFlags(); - + CMapItemImage Item; Item.m_Version = 1; - + Item.m_Width = pImg->m_Width; Item.m_Height = pImg->m_Height; Item.m_External = pImg->m_External; @@ -242,7 +242,7 @@ int CEditorMap::Save(class IStorage *pStorage, const char *pFileName) Item.m_ImageData = df.AddData(Item.m_Width*Item.m_Height*4, pImg->m_pData); df.AddItem(MAPITEMTYPE_IMAGE, i, sizeof(Item), &Item); } - + // save layers int LayerCount = 0, GroupCount = 0; for(int g = 0; g < m_lGroups.size(); g++) @@ -253,7 +253,7 @@ int CEditorMap::Save(class IStorage *pStorage, const char *pFileName) CMapItemGroup GItem; GItem.m_Version = CMapItemGroup::CURRENT_VERSION; - + GItem.m_ParallaxX = pGroup->m_ParallaxX; GItem.m_ParallaxY = pGroup->m_ParallaxY; GItem.m_OffsetX = pGroup->m_OffsetX; @@ -265,7 +265,7 @@ int CEditorMap::Save(class IStorage *pStorage, const char *pFileName) GItem.m_ClipH = pGroup->m_ClipH; GItem.m_StartLayer = LayerCount; GItem.m_NumLayers = 0; - + for(int l = 0; l < pGroup->m_lLayers.size(); l++) { if(!pGroup->m_lLayers[l]->m_SaveToMap) @@ -276,27 +276,27 @@ int CEditorMap::Save(class IStorage *pStorage, const char *pFileName) m_pEditor->Console()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "editor", "saving tiles layer"); CLayerTiles *pLayer = (CLayerTiles *)pGroup->m_lLayers[l]; pLayer->PrepareForSave(); - + CMapItemLayerTilemap Item; Item.m_Version = 2; - + Item.m_Layer.m_Flags = pLayer->m_Flags; Item.m_Layer.m_Type = pLayer->m_Type; - + Item.m_Color.r = pLayer->m_Color.r; Item.m_Color.g = pLayer->m_Color.g; Item.m_Color.b = pLayer->m_Color.b; Item.m_Color.a = pLayer->m_Color.a; Item.m_ColorEnv = -1; // not in use right now Item.m_ColorEnvOffset = 0; - + Item.m_Width = pLayer->m_Width; Item.m_Height = pLayer->m_Height; Item.m_Flags = pLayer->m_Game; Item.m_Image = pLayer->m_Image; Item.m_Data = df.AddData(pLayer->m_Width*pLayer->m_Height*sizeof(CTile), pLayer->m_pTiles); df.AddItem(MAPITEMTYPE_LAYER, LayerCount, sizeof(Item), &Item); - + GItem.m_NumLayers++; LayerCount++; } @@ -308,15 +308,15 @@ int CEditorMap::Save(class IStorage *pStorage, const char *pFileName) { CMapItemLayerQuads Item; Item.m_Version = 1; - Item.m_Layer.m_Flags = pLayer->m_Flags; + Item.m_Layer.m_Flags = pLayer->m_Flags; Item.m_Layer.m_Type = pLayer->m_Type; Item.m_Image = pLayer->m_Image; - + // add the data Item.m_NumQuads = pLayer->m_lQuads.size(); Item.m_Data = df.AddDataSwapped(pLayer->m_lQuads.size()*sizeof(CQuad), pLayer->m_lQuads.base_ptr()); df.AddItem(MAPITEMTYPE_LAYER, LayerCount, sizeof(Item), &Item); - + // clean up //mem_free(quads); @@ -325,10 +325,10 @@ int CEditorMap::Save(class IStorage *pStorage, const char *pFileName) } } } - + df.AddItem(MAPITEMTYPE_GROUP, GroupCount++, sizeof(GItem), &GItem); } - + // save envelopes int PointCount = 0; for(int e = 0; e < m_lEnvelopes.size(); e++) @@ -339,16 +339,16 @@ int CEditorMap::Save(class IStorage *pStorage, const char *pFileName) Item.m_StartPoint = PointCount; Item.m_NumPoints = m_lEnvelopes[e]->m_lPoints.size(); StrToInts(Item.m_aName, sizeof(Item.m_aName)/sizeof(int), m_lEnvelopes[e]->m_aName); - + df.AddItem(MAPITEMTYPE_ENVELOPE, e, sizeof(Item), &Item); PointCount += Item.m_NumPoints; } - + // save points int TotalSize = sizeof(CEnvPoint) * PointCount; CEnvPoint *pPoints = (CEnvPoint *)mem_alloc(TotalSize, 1); PointCount = 0; - + for(int e = 0; e < m_lEnvelopes.size(); e++) { int Count = m_lEnvelopes[e]->m_lPoints.size(); @@ -357,11 +357,11 @@ int CEditorMap::Save(class IStorage *pStorage, const char *pFileName) } df.AddItem(MAPITEMTYPE_ENVPOINTS, 0, TotalSize, pPoints); - + // finish the data file df.Finish(); m_pEditor->Console()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "editor", "saving done"); - + // send rcon.. if we can if(m_pEditor->Client()->RconAuthed()) { @@ -372,7 +372,7 @@ int CEditorMap::Save(class IStorage *pStorage, const char *pFileName) if(!str_comp(aMapName, CurrentServerInfo.m_aMap)) m_pEditor->Client()->Rcon("reload"); } - + return 1; } @@ -388,7 +388,7 @@ int CEditorMap::Load(class IStorage *pStorage, const char *pFileName, int Storag //DATAFILE *df = datafile_load(filename); if(!DataFile.Open(pStorage, pFileName, StorageType)) return 0; - + Clean(); // check version @@ -404,7 +404,7 @@ int CEditorMap::Load(class IStorage *pStorage, const char *pFileName, int Storag else if(pItem->m_Version == 1) { //editor.reset(false); - + // load images { int Start, Num; @@ -414,7 +414,7 @@ int CEditorMap::Load(class IStorage *pStorage, const char *pFileName, int Storag CMapItemImage *pItem = (CMapItemImage *)DataFile.GetItem(Start+i, 0, 0); char *pName = (char *)DataFile.GetData(pItem->m_ImageName); - // copy base info + // copy base info CEditorImage *pImg = new CEditorImage(m_pEditor); pImg->m_External = pItem->m_External; @@ -422,7 +422,7 @@ int CEditorMap::Load(class IStorage *pStorage, const char *pFileName, int Storag { char aBuf[256]; str_format(aBuf, sizeof(aBuf),"mapres/%s.png", pName); - + // load external CEditorImage ImgInfo(m_pEditor); if(m_pEditor->Graphics()->LoadPNG(&ImgInfo, aBuf, IStorage::TYPE_ALL)) @@ -437,7 +437,7 @@ int CEditorMap::Load(class IStorage *pStorage, const char *pFileName, int Storag pImg->m_Width = pItem->m_Width; pImg->m_Height = pItem->m_Height; pImg->m_Format = CImageInfo::FORMAT_RGBA; - + // copy image data void *pData = DataFile.GetData(pItem->m_ImageData); pImg->m_pData = mem_alloc(pImg->m_Width*pImg->m_Height*4, 1); @@ -450,33 +450,33 @@ int CEditorMap::Load(class IStorage *pStorage, const char *pFileName, int Storag str_copy(pImg->m_aName, pName, 128); m_lImages.add(pImg); - + // unload image DataFile.UnloadData(pItem->m_ImageData); DataFile.UnloadData(pItem->m_ImageName); } } - + // load groups { int LayersStart, LayersNum; DataFile.GetType(MAPITEMTYPE_LAYER, &LayersStart, &LayersNum); - + int Start, Num; DataFile.GetType(MAPITEMTYPE_GROUP, &Start, &Num); for(int g = 0; g < Num; g++) { CMapItemGroup *pGItem = (CMapItemGroup *)DataFile.GetItem(Start+g, 0, 0); - + if(pGItem->m_Version < 1 || pGItem->m_Version > CMapItemGroup::CURRENT_VERSION) continue; - + CLayerGroup *pGroup = NewGroup(); pGroup->m_ParallaxX = pGItem->m_ParallaxX; pGroup->m_ParallaxY = pGItem->m_ParallaxY; pGroup->m_OffsetX = pGItem->m_OffsetX; pGroup->m_OffsetY = pGItem->m_OffsetY; - + if(pGItem->m_Version >= 2) { pGroup->m_UseClipping = pGItem->m_UseClipping; @@ -485,19 +485,19 @@ int CEditorMap::Load(class IStorage *pStorage, const char *pFileName, int Storag pGroup->m_ClipW = pGItem->m_ClipW; pGroup->m_ClipH = pGItem->m_ClipH; } - + for(int l = 0; l < pGItem->m_NumLayers; l++) { CLayer *pLayer = 0; CMapItemLayer *pLayerItem = (CMapItemLayer *)DataFile.GetItem(LayersStart+pGItem->m_StartLayer+l, 0, 0); if(!pLayerItem) continue; - + if(pLayerItem->m_Type == LAYERTYPE_TILES) { CMapItemLayerTilemap *pTilemapItem = (CMapItemLayerTilemap *)pLayerItem; CLayerTiles *pTiles = 0; - + if(pTilemapItem->m_Flags&1) { pTiles = new CLayerGame(pTilemapItem->m_Width, pTilemapItem->m_Height); @@ -515,14 +515,14 @@ int CEditorMap::Load(class IStorage *pStorage, const char *pFileName, int Storag } pLayer = pTiles; - + pGroup->AddLayer(pTiles); void *pData = DataFile.GetData(pTilemapItem->m_Data); pTiles->m_Image = pTilemapItem->m_Image; pTiles->m_Game = pTilemapItem->m_Flags&1; - + mem_copy(pTiles->m_pTiles, pData, pTiles->m_Width*pTiles->m_Height*sizeof(CTile)); - + if(pTiles->m_Game && pTilemapItem->m_Version == MakeVersion(1, *pTilemapItem)) { for(int i = 0; i < pTiles->m_Width*pTiles->m_Height; i++) @@ -531,7 +531,7 @@ int CEditorMap::Load(class IStorage *pStorage, const char *pFileName, int Storag pTiles->m_pTiles[i].m_Index += ENTITY_OFFSET; } } - + DataFile.UnloadData(pTilemapItem->m_Data); } else if(pLayerItem->m_Type == LAYERTYPE_QUADS) @@ -549,24 +549,24 @@ int CEditorMap::Load(class IStorage *pStorage, const char *pFileName, int Storag mem_copy(pQuads->m_lQuads.base_ptr(), pData, sizeof(CQuad)*pQuadsItem->m_NumQuads); DataFile.UnloadData(pQuadsItem->m_Data); } - + if(pLayer) pLayer->m_Flags = pLayerItem->m_Flags; } } } - + // load envelopes { CEnvPoint *pPoints = 0; - + { int Start, Num; DataFile.GetType(MAPITEMTYPE_ENVPOINTS, &Start, &Num); if(Num) pPoints = (CEnvPoint *)DataFile.GetItem(Start, 0, 0); } - + int Start, Num; DataFile.GetType(MAPITEMTYPE_ENVELOPE, &Start, &Num); for(int e = 0; e < Num; e++) @@ -581,7 +581,7 @@ int CEditorMap::Load(class IStorage *pStorage, const char *pFileName, int Storag } } } - + return 1; } @@ -602,25 +602,25 @@ int CEditor::Append(const char *pFileName, int StorageType) if(!Err) return Err; - // modify indecies + // modify indecies gs_ModifyAddAmount = m_Map.m_lImages.size(); NewMap.ModifyImageIndex(ModifyAdd); - + gs_ModifyAddAmount = m_Map.m_lEnvelopes.size(); NewMap.ModifyEnvelopeIndex(ModifyAdd); - + // transfer images for(int i = 0; i < NewMap.m_lImages.size(); i++) m_Map.m_lImages.add(NewMap.m_lImages[i]); NewMap.m_lImages.clear(); - + // transfer envelopes for(int i = 0; i < NewMap.m_lEnvelopes.size(); i++) m_Map.m_lEnvelopes.add(NewMap.m_lEnvelopes[i]); NewMap.m_lEnvelopes.clear(); // transfer groups - + for(int i = 0; i < NewMap.m_lGroups.size(); i++) { if(NewMap.m_lGroups[i] == NewMap.m_pGameGroup) @@ -632,7 +632,7 @@ int CEditor::Append(const char *pFileName, int StorageType) } } NewMap.m_lGroups.clear(); - + // all done \o/ return 0; } diff --git a/src/game/editor/ed_layer_quads.cpp b/src/game/editor/ed_layer_quads.cpp index 4f2e468c..680a54cd 100644 --- a/src/game/editor/ed_layer_quads.cpp +++ b/src/game/editor/ed_layer_quads.cpp @@ -32,7 +32,7 @@ static void EnvelopeEval(float TimeOffset, int Env, float *pChannels, void *pUse pChannels[3] = 0; return; } - + CEnvelope *e = pEditor->m_Map.m_lEnvelopes[Env]; float t = pEditor->m_AnimateTime+TimeOffset; t *= pEditor->m_AnimateSpeed; @@ -44,7 +44,7 @@ void CLayerQuads::Render() Graphics()->TextureSet(-1); if(m_Image >= 0 && m_Image < m_pEditor->m_Map.m_lImages.size()) Graphics()->TextureSet(m_pEditor->m_Map.m_lImages[m_Image]->m_TexID); - + m_pEditor->RenderTools()->RenderQuads(m_lQuads.base_ptr(), m_lQuads.size(), LAYERRENDERFLAG_OPAQUE|LAYERRENDERFLAG_TRANSPARENT, EnvelopeEval, m_pEditor); } @@ -70,26 +70,26 @@ CQuad *CLayerQuads::NewQuad() q->m_aPoints[4].x = x+32; // pivot q->m_aPoints[4].y = y+32; - + for(int i = 0; i < 5; i++) { q->m_aPoints[i].x <<= 10; q->m_aPoints[i].y <<= 10; } - + q->m_aTexcoords[0].x = 0; q->m_aTexcoords[0].y = 0; - + q->m_aTexcoords[1].x = 1<<10; q->m_aTexcoords[1].y = 0; - + q->m_aTexcoords[2].x = 0; q->m_aTexcoords[2].y = 1<<10; - + q->m_aTexcoords[3].x = 1<<10; q->m_aTexcoords[3].y = 1<<10; - + q->m_aColors[0].r = 255; q->m_aColors[0].g = 255; q->m_aColors[0].b = 255; q->m_aColors[0].a = 255; q->m_aColors[1].r = 255; q->m_aColors[1].g = 255; q->m_aColors[1].b = 255; q->m_aColors[1].a = 255; q->m_aColors[2].r = 255; q->m_aColors[2].g = 255; q->m_aColors[2].b = 255; q->m_aColors[2].a = 255; @@ -119,29 +119,29 @@ int CLayerQuads::BrushGrab(CLayerGroup *pBrush, CUIRect Rect) pGrabbed->m_pEditor = m_pEditor; pGrabbed->m_Image = m_Image; pBrush->AddLayer(pGrabbed); - + //dbg_msg("", "%f %f %f %f", rect.x, rect.y, rect.w, rect.h); for(int i = 0; i < m_lQuads.size(); i++) { CQuad *q = &m_lQuads[i]; float px = fx2f(q->m_aPoints[4].x); float py = fx2f(q->m_aPoints[4].y); - + if(px > Rect.x && px < Rect.x+Rect.w && py > Rect.y && py < Rect.y+Rect.h) { CQuad n; n = *q; - + for(int p = 0; p < 5; p++) { n.m_aPoints[p].x -= f2fx(Rect.x); n.m_aPoints[p].y -= f2fx(Rect.y); } - + pGrabbed->m_lQuads.add(n); } } - + return pGrabbed->m_lQuads.size()?1:0; } @@ -151,13 +151,13 @@ void CLayerQuads::BrushPlace(CLayer *pBrush, float wx, float wy) for(int i = 0; i < l->m_lQuads.size(); i++) { CQuad n = l->m_lQuads[i]; - + for(int p = 0; p < 5; p++) { n.m_aPoints[p].x += f2fx(wx); n.m_aPoints[p].y += f2fx(wy); } - + m_lQuads.add(n); } m_pEditor->m_Map.m_Modified = true; @@ -189,7 +189,7 @@ void CLayerQuads::BrushRotate(float Amount) for(int i = 0; i < m_lQuads.size(); i++) { CQuad *q = &m_lQuads[i]; - + for(int p = 0; p < 5; p++) { vec2 Pos(fx2f(q->m_aPoints[p].x), fx2f(q->m_aPoints[p].y)); @@ -203,7 +203,7 @@ void CLayerQuads::BrushRotate(float Amount) void CLayerQuads::GetSize(float *w, float *h) { *w = 0; *h = 0; - + for(int i = 0; i < m_lQuads.size(); i++) { for(int p = 0; p < 5; p++) @@ -224,18 +224,18 @@ int CLayerQuads::RenderProperties(CUIRect *pToolBox) PROP_IMAGE=0, NUM_PROPS, }; - + CProperty aProps[] = { {"Image", m_Image, PROPTYPE_IMAGE, -1, 0}, {0}, }; - + static int s_aIds[NUM_PROPS] = {0}; int NewVal = 0; int Prop = m_pEditor->DoProperties(pToolBox, aProps, s_aIds, &NewVal); if(Prop != -1) m_pEditor->m_Map.m_Modified = true; - + if(Prop == PROP_IMAGE) { if(NewVal >= 0) diff --git a/src/game/editor/ed_layer_tiles.cpp b/src/game/editor/ed_layer_tiles.cpp index dcbb0afe..d0c9041c 100644 --- a/src/game/editor/ed_layer_tiles.cpp +++ b/src/game/editor/ed_layer_tiles.cpp @@ -25,7 +25,7 @@ CLayerTiles::CLayerTiles(int w, int h) m_Color.g = 255; m_Color.b = 255; m_Color.a = 255; - + m_pTiles = new CTile[m_Width*m_Height]; mem_zero(m_pTiles, m_Width*m_Height*sizeof(CTile)); } @@ -93,19 +93,19 @@ void CLayerTiles::Clamp(RECTi *pRect) pRect->w += pRect->x; pRect->x = 0; } - + if(pRect->y < 0) { pRect->h += pRect->y; pRect->y = 0; } - + if(pRect->x+pRect->w > m_Width) pRect->w = m_Width - pRect->x; if(pRect->y+pRect->h > m_Height) pRect->h = m_Height - pRect->y; - + if(pRect->h < 0) pRect->h = 0; if(pRect->w < 0) @@ -131,10 +131,10 @@ int CLayerTiles::BrushGrab(CLayerGroup *pBrush, CUIRect Rect) RECTi r; Convert(Rect, &r); Clamp(&r); - + if(!r.w || !r.h) return 0; - + // create new layers CLayerTiles *pGrabbed = new CLayerTiles(r.w, r.h); pGrabbed->m_pEditor = m_pEditor; @@ -142,12 +142,12 @@ int CLayerTiles::BrushGrab(CLayerGroup *pBrush, CUIRect Rect) pGrabbed->m_Image = m_Image; pGrabbed->m_Game = m_Game; pBrush->AddLayer(pGrabbed); - + // copy the tiles for(int y = 0; y < r.h; y++) for(int x = 0; x < r.w; x++) pGrabbed->m_pTiles[y*pGrabbed->m_Width+x] = m_pTiles[(r.y+y)*m_Width+(r.x+x)]; - + return 1; } @@ -155,28 +155,28 @@ void CLayerTiles::FillSelection(bool Empty, CLayer *pBrush, CUIRect Rect) { if(m_Readonly) return; - + int sx = ConvertX(Rect.x); int sy = ConvertY(Rect.y); int w = ConvertX(Rect.w); int h = ConvertY(Rect.h); - + CLayerTiles *pLt = static_cast<CLayerTiles*>(pBrush); - + for(int y = 0; y <= h; y++) { for(int x = 0; x <= w; x++) { int fx = x+sx; int fy = y+sy; - + if(fx < 0 || fx >= m_Width || fy < 0 || fy >= m_Height) continue; - - if(Empty) - m_pTiles[fy*m_Width+fx].m_Index = 1; - else - m_pTiles[fy*m_Width+fx] = pLt->m_pTiles[(y*pLt->m_Width + x%pLt->m_Width) % (pLt->m_Width*pLt->m_Height)]; + + if(Empty) + m_pTiles[fy*m_Width+fx].m_Index = 1; + else + m_pTiles[fy*m_Width+fx] = pLt->m_pTiles[(y*pLt->m_Width + x%pLt->m_Width) % (pLt->m_Width*pLt->m_Height)]; } } m_pEditor->m_Map.m_Modified = true; @@ -186,12 +186,12 @@ void CLayerTiles::BrushDraw(CLayer *pBrush, float wx, float wy) { if(m_Readonly) return; - + // CLayerTiles *l = (CLayerTiles *)pBrush; int sx = ConvertX(wx); int sy = ConvertY(wy); - + for(int y = 0; y < l->m_Height; y++) for(int x = 0; x < l->m_Width; x++) { @@ -199,7 +199,7 @@ void CLayerTiles::BrushDraw(CLayer *pBrush, float wx, float wy) int fy = y+sy; if(fx<0 || fx >= m_Width || fy < 0 || fy >= m_Height) continue; - + m_pTiles[fy*m_Width+fx] = l->m_pTiles[y*l->m_Width+x]; } m_pEditor->m_Map.m_Modified = true; @@ -279,10 +279,10 @@ void CLayerTiles::Resize(int NewW, int NewH) CTile *pNewData = new CTile[NewW*NewH]; mem_zero(pNewData, NewW*NewH*sizeof(CTile)); - // copy old data + // copy old data for(int y = 0; y < min(NewH, m_Height); y++) mem_copy(&pNewData[y*NewW], &m_pTiles[y*m_Width], min(m_Width, NewW)*sizeof(CTile)); - + // replace old delete [] m_pTiles; m_pTiles = pNewData; @@ -329,12 +329,12 @@ void CLayerTiles::ShowInfo() float ScreenX0, ScreenY0, ScreenX1, ScreenY1; Graphics()->GetScreen(&ScreenX0, &ScreenY0, &ScreenX1, &ScreenY1); Graphics()->TextureSet(m_pEditor->Client()->GetDebugFont()); - + int StartY = max(0, (int)(ScreenY0/32.0f)-1); int StartX = max(0, (int)(ScreenX0/32.0f)-1); int EndY = min((int)(ScreenY1/32.0f)+1, m_Height); int EndX = min((int)(ScreenX1/32.0f)+1, m_Width); - + for(int y = StartY; y < EndY; y++) for(int x = StartX; x < EndX; x++) { @@ -359,7 +359,7 @@ int CLayerTiles::RenderProperties(CUIRect *pToolBox) { CUIRect Button; pToolBox->HSplitBottom(12.0f, pToolBox, &Button); - + bool InGameGroup = !find_linear(m_pEditor->m_Map.m_pGameGroup->m_lLayers.all(), this).empty(); if(m_pEditor->m_Map.m_pGameLayer == this) InGameGroup = false; @@ -384,7 +384,7 @@ int CLayerTiles::RenderProperties(CUIRect *pToolBox) return 1; } } - + enum { PROP_WIDTH=0, @@ -394,13 +394,13 @@ int CLayerTiles::RenderProperties(CUIRect *pToolBox) PROP_COLOR, NUM_PROPS, }; - + int Color = 0; Color |= m_Color.r<<24; Color |= m_Color.g<<16; Color |= m_Color.b<<8; Color |= m_Color.a; - + CProperty aProps[] = { {"Width", m_Width, PROPTYPE_INT_SCROLL, 1, 1000000000}, {"Height", m_Height, PROPTYPE_INT_SCROLL, 1, 1000000000}, @@ -409,19 +409,19 @@ int CLayerTiles::RenderProperties(CUIRect *pToolBox) {"Color", Color, PROPTYPE_COLOR, 0, 0}, {0}, }; - + if(m_pEditor->m_Map.m_pGameLayer == this) // remove the image and color properties if this is the game layer { aProps[3].m_pName = 0; aProps[4].m_pName = 0; } - + static int s_aIds[NUM_PROPS] = {0}; int NewVal = 0; int Prop = m_pEditor->DoProperties(pToolBox, aProps, s_aIds, &NewVal); if(Prop != -1) m_pEditor->m_Map.m_Modified = true; - + if(Prop == PROP_WIDTH && NewVal > 1) Resize(NewVal, m_Height); else if(Prop == PROP_HEIGHT && NewVal > 1) @@ -445,7 +445,7 @@ int CLayerTiles::RenderProperties(CUIRect *pToolBox) m_Color.b = (NewVal>>8)&0xff; m_Color.a = NewVal&0xff; } - + return 0; } diff --git a/src/game/editor/ed_popups.cpp b/src/game/editor/ed_popups.cpp index 8f2c929a..f572e43c 100644 --- a/src/game/editor/ed_popups.cpp +++ b/src/game/editor/ed_popups.cpp @@ -44,7 +44,7 @@ void CEditor::UiDoPopupMenu() { bool Inside = UI()->MouseInside(&s_UiPopups[i].m_Rect); UI()->SetHotItem(&s_UiPopups[i].m_pId); - + if(UI()->ActiveItem() == &s_UiPopups[i].m_pId) { if(!UI()->MouseButton(0)) @@ -59,20 +59,20 @@ void CEditor::UiDoPopupMenu() if(UI()->MouseButton(0)) UI()->SetActiveItem(&s_UiPopups[i].m_pId); } - + int Corners = CUI::CORNER_ALL; if(s_UiPopups[i].m_IsMenu) Corners = CUI::CORNER_R|CUI::CORNER_B; - + CUIRect r = s_UiPopups[i].m_Rect; RenderTools()->DrawUIRect(&r, vec4(0.5f,0.5f,0.5f,0.75f), Corners, 3.0f); r.Margin(1.0f, &r); RenderTools()->DrawUIRect(&r, vec4(0,0,0,0.75f), Corners, 3.0f); r.Margin(4.0f, &r); - + if(s_UiPopups[i].m_pfnFunc(this, r)) g_UiNumPopups--; - + if(Input()->KeyDown(KEY_ESCAPE)) g_UiNumPopups--; } @@ -85,7 +85,7 @@ int CEditor::PopupGroup(CEditor *pEditor, CUIRect View) CUIRect Button; View.HSplitBottom(12.0f, &View, &Button); static int s_DeleteButton = 0; - + // don't allow deletion of game group if(pEditor->m_Map.m_pGameGroup != pEditor->GetSelectedGroup()) { @@ -162,7 +162,7 @@ int CEditor::PopupGroup(CEditor *pEditor, CUIRect View) pEditor->m_SelectedLayer = pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->m_lLayers.size()-1; return 1; } - + enum { PROP_ORDER=0, @@ -177,7 +177,7 @@ int CEditor::PopupGroup(CEditor *pEditor, CUIRect View) PROP_CLIP_H, NUM_PROPS, }; - + CProperty aProps[] = { {"Order", pEditor->m_SelectedGroup, PROPTYPE_INT_STEP, 0, pEditor->m_Map.m_lGroups.size()-1}, {"Pos X", -pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->m_OffsetX, PROPTYPE_INT_SCROLL, -1000000, 1000000}, @@ -192,21 +192,21 @@ int CEditor::PopupGroup(CEditor *pEditor, CUIRect View) {"Clip H", pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->m_ClipH, PROPTYPE_INT_SCROLL, -1000000, 1000000}, {0}, }; - + static int s_aIds[NUM_PROPS] = {0}; int NewVal = 0; - + // cut the properties that isn't needed if(pEditor->GetSelectedGroup()->m_GameGroup) aProps[PROP_POS_X].m_pName = 0; - + int Prop = pEditor->DoProperties(&View, aProps, s_aIds, &NewVal); if(Prop != -1) pEditor->m_Map.m_Modified = true; if(Prop == PROP_ORDER) pEditor->m_SelectedGroup = pEditor->m_Map.SwapGroups(pEditor->m_SelectedGroup, NewVal); - + // these can not be changed on the game group if(!pEditor->GetSelectedGroup()->m_GameGroup) { @@ -220,7 +220,7 @@ int CEditor::PopupGroup(CEditor *pEditor, CUIRect View) else if(Prop == PROP_CLIP_W) pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->m_ClipW = NewVal; else if(Prop == PROP_CLIP_H) pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->m_ClipH = NewVal; } - + return 0; } @@ -230,7 +230,7 @@ int CEditor::PopupLayer(CEditor *pEditor, CUIRect View) CUIRect Button; View.HSplitBottom(12.0f, &View, &Button); static int s_DeleteButton = 0; - + // don't allow deletion of game layer if(pEditor->m_Map.m_pGameLayer != pEditor->GetSelectedLayer(0) && pEditor->DoButton_Editor(&s_DeleteButton, "Delete layer", 0, &Button, 0, "Deletes the layer")) @@ -240,10 +240,10 @@ int CEditor::PopupLayer(CEditor *pEditor, CUIRect View) } View.HSplitBottom(10.0f, &View, 0); - + CLayerGroup *pCurrentGroup = pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]; CLayer *pCurrentLayer = pEditor->GetSelectedLayer(0); - + enum { PROP_GROUP=0, @@ -251,7 +251,7 @@ int CEditor::PopupLayer(CEditor *pEditor, CUIRect View) PROP_HQ, NUM_PROPS, }; - + CProperty aProps[] = { {"Group", pEditor->m_SelectedGroup, PROPTYPE_INT_STEP, 0, pEditor->m_Map.m_lGroups.size()-1}, {"Order", pEditor->m_SelectedLayer, PROPTYPE_INT_STEP, 0, pCurrentGroup->m_lLayers.size()}, @@ -264,13 +264,13 @@ int CEditor::PopupLayer(CEditor *pEditor, CUIRect View) aProps[0].m_Type = PROPTYPE_NULL; aProps[2].m_Type = PROPTYPE_NULL; } - + static int s_aIds[NUM_PROPS] = {0}; int NewVal = 0; int Prop = pEditor->DoProperties(&View, aProps, s_aIds, &NewVal); if(Prop != -1) pEditor->m_Map.m_Modified = true; - + if(Prop == PROP_ORDER) pEditor->m_SelectedLayer = pCurrentGroup->SwapLayers(pEditor->m_SelectedLayer, NewVal); else if(Prop == PROP_GROUP && pCurrentLayer->m_Type != LAYERTYPE_GAME) @@ -289,7 +289,7 @@ int CEditor::PopupLayer(CEditor *pEditor, CUIRect View) if(NewVal) pCurrentLayer->m_Flags |= LAYERFLAG_DETAIL; } - + return pCurrentLayer->RenderProperties(&View); } @@ -298,7 +298,7 @@ int CEditor::PopupQuad(CEditor *pEditor, CUIRect View) CQuad *pQuad = pEditor->GetSelectedQuad(); CUIRect Button; - + // delete button View.HSplitBottom(12.0f, &View, &Button); static int s_DeleteButton = 0; @@ -335,7 +335,7 @@ int CEditor::PopupQuad(CEditor *pEditor, CUIRect View) } int Height = (Right-Left)*pEditor->m_Map.m_lImages[pLayer->m_Image]->m_Height/pEditor->m_Map.m_lImages[pLayer->m_Image]->m_Width; - + pQuad->m_aPoints[0].x = Left; pQuad->m_aPoints[0].y = Top; pQuad->m_aPoints[1].x = Right; pQuad->m_aPoints[1].y = Top; pQuad->m_aPoints[2].x = Left; pQuad->m_aPoints[2].y = Top+Height; @@ -370,7 +370,7 @@ int CEditor::PopupQuad(CEditor *pEditor, CUIRect View) int Left = pQuad->m_aPoints[0].x; int Bottom = pQuad->m_aPoints[0].y; int Right = pQuad->m_aPoints[0].x; - + for(int k = 1; k < 4; k++) { if(pQuad->m_aPoints[k].y < Top) Top = pQuad->m_aPoints[k].y; @@ -378,7 +378,7 @@ int CEditor::PopupQuad(CEditor *pEditor, CUIRect View) if(pQuad->m_aPoints[k].y > Bottom) Bottom = pQuad->m_aPoints[k].y; if(pQuad->m_aPoints[k].x > Right) Right = pQuad->m_aPoints[k].x; } - + pQuad->m_aPoints[0].x = Left; pQuad->m_aPoints[0].y = Top; pQuad->m_aPoints[1].x = Right; pQuad->m_aPoints[1].y = Top; pQuad->m_aPoints[2].x = Left; pQuad->m_aPoints[2].y = Bottom; @@ -398,7 +398,7 @@ int CEditor::PopupQuad(CEditor *pEditor, CUIRect View) PROP_COLOR_ENV_OFFSET, NUM_PROPS, }; - + CProperty aProps[] = { {"Pos X", pQuad->m_aPoints[4].x/1000, PROPTYPE_INT_SCROLL, -1000000, 1000000}, {"Pos Y", pQuad->m_aPoints[4].y/1000, PROPTYPE_INT_SCROLL, -1000000, 1000000}, @@ -406,16 +406,16 @@ int CEditor::PopupQuad(CEditor *pEditor, CUIRect View) {"Pos. TO", pQuad->m_PosEnvOffset, PROPTYPE_INT_SCROLL, -1000000, 1000000}, {"Color Env", pQuad->m_ColorEnv+1, PROPTYPE_INT_STEP, 0, pEditor->m_Map.m_lEnvelopes.size()+1}, {"Color TO", pQuad->m_ColorEnvOffset, PROPTYPE_INT_SCROLL, -1000000, 1000000}, - + {0}, }; - + static int s_aIds[NUM_PROPS] = {0}; int NewVal = 0; int Prop = pEditor->DoProperties(&View, aProps, s_aIds, &NewVal); if(Prop != -1) pEditor->m_Map.m_Modified = true; - + if(Prop == PROP_POS_X) { float Offset = NewVal*1000-pQuad->m_aPoints[4].x; @@ -432,14 +432,14 @@ int CEditor::PopupQuad(CEditor *pEditor, CUIRect View) if(Prop == PROP_POS_ENV_OFFSET) pQuad->m_PosEnvOffset = NewVal; if(Prop == PROP_COLOR_ENV) pQuad->m_ColorEnv = clamp(NewVal-1, -1, pEditor->m_Map.m_lEnvelopes.size()-1); if(Prop == PROP_COLOR_ENV_OFFSET) pQuad->m_ColorEnvOffset = NewVal; - + return 0; } int CEditor::PopupPoint(CEditor *pEditor, CUIRect View) { CQuad *pQuad = pEditor->GetSelectedQuad(); - + enum { PROP_POS_X=0, @@ -447,7 +447,7 @@ int CEditor::PopupPoint(CEditor *pEditor, CUIRect View) PROP_COLOR, NUM_PROPS, }; - + int Color = 0; int x = 0, y = 0; @@ -465,15 +465,15 @@ int CEditor::PopupPoint(CEditor *pEditor, CUIRect View) y = pQuad->m_aPoints[v].y/1000; } } - - + + CProperty aProps[] = { {"Pos X", x, PROPTYPE_INT_SCROLL, -1000000, 1000000}, {"Pos Y", y, PROPTYPE_INT_SCROLL, -1000000, 1000000}, {"Color", Color, PROPTYPE_COLOR, -1, pEditor->m_Map.m_lEnvelopes.size()}, {0}, }; - + static int s_aIds[NUM_PROPS] = {0}; int NewVal = 0; int Prop = pEditor->DoProperties(&View, aProps, s_aIds, &NewVal); @@ -506,8 +506,8 @@ int CEditor::PopupPoint(CEditor *pEditor, CUIRect View) } } } - - return 0; + + return 0; } int CEditor::PopupNewFolder(CEditor *pEditor, CUIRect View) @@ -520,7 +520,7 @@ int CEditor::PopupNewFolder(CEditor *pEditor, CUIRect View) pEditor->UI()->DoLabel(&Label, "Create new folder", 20.0f, 0); View.HSplitBottom(10.0f, &View, 0); - View.HSplitBottom(20.0f, &View, &ButtonBar); + View.HSplitBottom(20.0f, &View, &ButtonBar); if(pEditor->m_FileDialogErrString[0] == 0) { @@ -551,7 +551,7 @@ int CEditor::PopupNewFolder(CEditor *pEditor, CUIRect View) } else str_copy(pEditor->m_FileDialogErrString, "Unable to create the folder", sizeof(pEditor->m_FileDialogErrString)); - } + } } ButtonBar.VSplitRight(30.0f, &ButtonBar, 0); ButtonBar.VSplitRight(110.0f, &ButtonBar, &Label); @@ -576,7 +576,7 @@ int CEditor::PopupNewFolder(CEditor *pEditor, CUIRect View) return 1; } - return 0; + return 0; } int CEditor::PopupEvent(CEditor *pEditor, CUIRect View) @@ -596,7 +596,7 @@ int CEditor::PopupEvent(CEditor *pEditor, CUIRect View) pEditor->UI()->DoLabel(&Label, "Save map", 20.0f, 0); View.HSplitBottom(10.0f, &View, 0); - View.HSplitBottom(20.0f, &View, &ButtonBar); + View.HSplitBottom(20.0f, &View, &ButtonBar); // notification text View.HSplitTop(30.0f, 0, &View); @@ -648,18 +648,18 @@ int CEditor::PopupSelectImage(CEditor *pEditor, CUIRect View) CUIRect ButtonBar, ImageView; View.VSplitLeft(80.0f, &ButtonBar, &View); View.Margin(10.0f, &ImageView); - + int ShowImage = g_SelectImageCurrent; - + for(int i = -1; i < pEditor->m_Map.m_lImages.size(); i++) { CUIRect Button; ButtonBar.HSplitTop(12.0f, &Button, &ButtonBar); ButtonBar.HSplitTop(2.0f, 0, &ButtonBar); - + if(pEditor->UI()->MouseInside(&Button)) ShowImage = i; - + if(i == -1) { if(pEditor->DoButton_MenuItem(&pEditor->m_Map.m_lImages[i], "None", i==g_SelectImageCurrent, &Button)) @@ -671,7 +671,7 @@ int CEditor::PopupSelectImage(CEditor *pEditor, CUIRect View) g_SelectImageSelected = i; } } - + if(ShowImage >= 0 && ShowImage < pEditor->m_Map.m_lImages.size()) pEditor->Graphics()->TextureSet(pEditor->m_Map.m_lImages[ShowImage]->m_TexID); else @@ -696,7 +696,7 @@ int CEditor::PopupSelectImageResult() { if(g_SelectImageSelected == -100) return -100; - + g_SelectImageCurrent = g_SelectImageSelected; g_SelectImageSelected = -100; return g_SelectImageCurrent; @@ -732,7 +732,7 @@ int CEditor::PopupSelectGameTileOpResult() { if(s_GametileOpSelected < 0) return -1; - + int Result = s_GametileOpSelected; s_GametileOpSelected = -1; return Result; diff --git a/src/game/gamecore.cpp b/src/game/gamecore.cpp index e41e1fab..d2a1652c 100644 --- a/src/game/gamecore.cpp +++ b/src/game/gamecore.cpp @@ -39,7 +39,7 @@ bool CTuningParams::Get(const char *pName, float *pValue) for(int i = 0; i < Num(); i++) if(str_comp_nocase(pName, m_apNames[i]) == 0) return Get(i, pValue); - + return false; } @@ -78,22 +78,22 @@ void CCharacterCore::Tick(bool UseInput) { float PhysSize = 28.0f; m_TriggeredEvents = 0; - + // get ground state bool Grounded = false; if(m_pCollision->CheckPoint(m_Pos.x+PhysSize/2, m_Pos.y+PhysSize/2+5)) Grounded = true; if(m_pCollision->CheckPoint(m_Pos.x-PhysSize/2, m_Pos.y+PhysSize/2+5)) Grounded = true; - + vec2 TargetDirection = normalize(vec2(m_Input.m_TargetX, m_Input.m_TargetY)); m_Vel.y += m_pWorld->m_Tuning.m_Gravity; - + float MaxSpeed = Grounded ? m_pWorld->m_Tuning.m_GroundControlSpeed : m_pWorld->m_Tuning.m_AirControlSpeed; float Accel = Grounded ? m_pWorld->m_Tuning.m_GroundControlAccel : m_pWorld->m_Tuning.m_AirControlAccel; float Friction = Grounded ? m_pWorld->m_Tuning.m_GroundFriction : m_pWorld->m_Tuning.m_AirFriction; - + // handle input if(UseInput) { @@ -105,10 +105,10 @@ void CCharacterCore::Tick(bool UseInput) a = atanf((float)m_Input.m_TargetY); else a = atanf((float)m_Input.m_TargetY/(float)m_Input.m_TargetX); - + if(m_Input.m_TargetX < 0) a = a+pi; - + m_Angle = (int)(a*256.0f); // handle jump @@ -144,16 +144,16 @@ void CCharacterCore::Tick(bool UseInput) m_HookedPlayer = -1; m_HookTick = 0; m_TriggeredEvents |= COREEVENT_HOOK_LAUNCH; - } + } } else { m_HookedPlayer = -1; m_HookState = HOOK_IDLE; - m_HookPos = m_Pos; - } + m_HookPos = m_Pos; + } } - + // add the speed modification according to players wanted direction if(m_Direction < 0) m_Vel.x = SaturatedAdd(-MaxSpeed, MaxSpeed, m_Vel.x, -Accel); @@ -161,13 +161,13 @@ void CCharacterCore::Tick(bool UseInput) m_Vel.x = SaturatedAdd(-MaxSpeed, MaxSpeed, m_Vel.x, Accel); if(m_Direction == 0) m_Vel.x *= Friction; - + // handle jumping // 1 bit = to keep track if a jump has been made on this input // 2 bit = to keep track if a air-jump has been made if(Grounded) m_Jumped &= ~2; - + // do hook if(m_HookState == HOOK_IDLE) { @@ -193,7 +193,7 @@ void CCharacterCore::Tick(bool UseInput) m_HookState = HOOK_RETRACT_START; NewPos = m_Pos + normalize(NewPos-m_Pos) * m_pWorld->m_Tuning.m_HookLength; } - + // make sure that the hook doesn't go though the ground bool GoingToHitGround = false; bool GoingToRetract = false; @@ -229,7 +229,7 @@ void CCharacterCore::Tick(bool UseInput) } } } - + if(m_HookState == HOOK_FLYING) { // check against ground @@ -243,11 +243,11 @@ void CCharacterCore::Tick(bool UseInput) m_TriggeredEvents |= COREEVENT_HOOK_HIT_NOHOOK; m_HookState = HOOK_RETRACT_START; } - + m_HookPos = NewPos; } } - + if(m_HookState == HOOK_GRABBED) { if(m_HookedPlayer != -1) @@ -260,14 +260,14 @@ void CCharacterCore::Tick(bool UseInput) // release hook m_HookedPlayer = -1; m_HookState = HOOK_RETRACTED; - m_HookPos = m_Pos; + m_HookPos = m_Pos; } - + // keep players hooked for a max of 1.5sec //if(Server()->Tick() > hook_tick+(Server()->TickSpeed()*3)/2) //release_hooked(); } - + // don't do this hook rutine when we are hook to a player if(m_HookedPlayer == -1 && distance(m_HookPos, m_Pos) > 46.0f) { @@ -276,20 +276,20 @@ void CCharacterCore::Tick(bool UseInput) // this makes it easier to get on top of an platform if(HookVel.y > 0) HookVel.y *= 0.3f; - + // the hook will boost it's power if the player wants to move // in that direction. otherwise it will dampen everything abit - if((HookVel.x < 0 && m_Direction < 0) || (HookVel.x > 0 && m_Direction > 0)) + if((HookVel.x < 0 && m_Direction < 0) || (HookVel.x > 0 && m_Direction > 0)) HookVel.x *= 0.95f; else HookVel.x *= 0.75f; - + vec2 NewVel = m_Vel+HookVel; // check if we are under the legal limit for the hook if(length(NewVel) < m_pWorld->m_Tuning.m_HookDragSpeed || length(NewVel) < length(m_Vel)) m_Vel = NewVel; // no problem. apply - + } // release hook (max hook time is 1.25 @@ -298,10 +298,10 @@ void CCharacterCore::Tick(bool UseInput) { m_HookedPlayer = -1; m_HookState = HOOK_RETRACTED; - m_HookPos = m_Pos; + m_HookPos = m_Pos; } } - + if(m_pWorld && m_pWorld->m_Tuning.m_PlayerCollision) { for(int i = 0; i < MAX_CLIENTS; i++) @@ -309,11 +309,11 @@ void CCharacterCore::Tick(bool UseInput) CCharacterCore *pCharCore = m_pWorld->m_apCharacters[i]; if(!pCharCore) continue; - + //player *p = (player*)ent; if(pCharCore == this) // || !(p->flags&FLAG_ALIVE) continue; // make sure that we don't nudge our self - + // handle player <-> player collision float Distance = distance(m_Pos, pCharCore->m_Pos); vec2 Dir = normalize(m_Pos - pCharCore->m_Pos); @@ -330,7 +330,7 @@ void CCharacterCore::Tick(bool UseInput) m_Vel += Dir*a*(Velocity*0.75f); m_Vel *= 0.85f; } - + // handle hook influence if(m_HookedPlayer == i) { @@ -338,7 +338,7 @@ void CCharacterCore::Tick(bool UseInput) { float Accel = m_pWorld->m_Tuning.m_HookDragAccel * (Distance/m_pWorld->m_Tuning.m_HookLength); float DragSpeed = m_pWorld->m_Tuning.m_HookDragSpeed; - + // add force to the hooked player pCharCore->m_Vel.x = SaturatedAdd(-DragSpeed, DragSpeed, pCharCore->m_Vel.x, Accel*Dir.x*1.5f); pCharCore->m_Vel.y = SaturatedAdd(-DragSpeed, DragSpeed, pCharCore->m_Vel.y, Accel*Dir.y*1.5f); @@ -349,7 +349,7 @@ void CCharacterCore::Tick(bool UseInput) } } } - } + } // clamp the velocity to something sane if(length(m_Vel) > 6000) @@ -359,9 +359,9 @@ void CCharacterCore::Tick(bool UseInput) void CCharacterCore::Move() { float RampValue = VelocityRamp(length(m_Vel)*50, m_pWorld->m_Tuning.m_VelrampStart, m_pWorld->m_Tuning.m_VelrampRange, m_pWorld->m_Tuning.m_VelrampCurvature); - + m_Vel.x = m_Vel.x*RampValue; - + vec2 NewPos = m_Pos; m_pCollision->MoveBox(&NewPos, &m_Vel, vec2(28.0f, 28.0f), 0); @@ -393,7 +393,7 @@ void CCharacterCore::Move() } } } - + m_Pos = NewPos; } @@ -401,7 +401,7 @@ void CCharacterCore::Write(CNetObj_CharacterCore *pObjCore) { pObjCore->m_X = round(m_Pos.x); pObjCore->m_Y = round(m_Pos.y); - + pObjCore->m_VelX = round(m_Vel.x*256.0f); pObjCore->m_VelY = round(m_Vel.y*256.0f); pObjCore->m_HookState = m_HookState; diff --git a/src/game/gamecore.h b/src/game/gamecore.h index 9e9ccf4d..611f5ed7 100644 --- a/src/game/gamecore.h +++ b/src/game/gamecore.h @@ -35,11 +35,11 @@ public: } static const char *m_apNames[]; - + #define MACRO_TUNING_PARAM(Name,ScriptName,Value) CTuneParam m_##Name; #include "tuning.h" #undef MACRO_TUNING_PARAM - + static int Num() { return sizeof(CTuningParams)/sizeof(int); } bool Set(int Index, float Value); bool Set(const char *pName, float Value); @@ -81,7 +81,7 @@ inline void StrToInts(int *pInts, int Num, const char *pStr) pInts++; Num--; } - + // null terminate pInts[-1] &= 0xffffff00; } @@ -98,7 +98,7 @@ inline void IntsToStr(const int *pInts, int Num, char *pStr) pInts++; Num--; } - + // null terminate pStr[-1] = 0; } @@ -150,7 +150,7 @@ enum HOOK_RETRACT_END=3, HOOK_FLYING, HOOK_GRABBED, - + COREEVENT_GROUND_JUMP=0x01, COREEVENT_AIR_JUMP=0x02, COREEVENT_HOOK_LAUNCH=0x04, @@ -167,7 +167,7 @@ public: { mem_zero(m_apCharacters, sizeof(m_apCharacters)); } - + CTuningParams m_Tuning; class CCharacterCore *m_apCharacters[MAX_CLIENTS]; }; @@ -179,26 +179,26 @@ class CCharacterCore public: vec2 m_Pos; vec2 m_Vel; - + vec2 m_HookPos; vec2 m_HookDir; int m_HookTick; int m_HookState; int m_HookedPlayer; - + int m_Jumped; - + int m_Direction; int m_Angle; CNetObj_PlayerInput m_Input; - + int m_TriggeredEvents; - + void Init(CWorldCore *pWorld, CCollision *pCollision); void Reset(); void Tick(bool UseInput); void Move(); - + void Read(const CNetObj_CharacterCore *pObjCore); void Write(CNetObj_CharacterCore *pObjCore); void Quantize(); diff --git a/src/game/layers.cpp b/src/game/layers.cpp index aafd3dd4..82c0a61b 100644 --- a/src/game/layers.cpp +++ b/src/game/layers.cpp @@ -18,14 +18,14 @@ void CLayers::Init(class IKernel *pKernel) m_pMap = pKernel->RequestInterface<IMap>(); m_pMap->GetType(MAPITEMTYPE_GROUP, &m_GroupsStart, &m_GroupsNum); m_pMap->GetType(MAPITEMTYPE_LAYER, &m_LayersStart, &m_LayersNum); - + for(int g = 0; g < NumGroups(); g++) { CMapItemGroup *pGroup = GetGroup(g); for(int l = 0; l < pGroup->m_NumLayers; l++) { CMapItemLayer *pLayer = GetLayer(pGroup->m_StartLayer+l); - + if(pLayer->m_Type == LAYERTYPE_TILES) { CMapItemLayerTilemap *pTilemap = reinterpret_cast<CMapItemLayerTilemap *>(pLayer); @@ -39,7 +39,7 @@ void CLayers::Init(class IKernel *pKernel) m_pGameGroup->m_OffsetY = 0; m_pGameGroup->m_ParallaxX = 100; m_pGameGroup->m_ParallaxY = 100; - + if(m_pGameGroup->m_Version >= 2) { m_pGameGroup->m_UseClipping = 0; @@ -51,7 +51,7 @@ void CLayers::Init(class IKernel *pKernel) break; } - } + } } } } diff --git a/src/game/layers.h b/src/game/layers.h index 3f8eacaa..5ddcd73e 100644 --- a/src/game/layers.h +++ b/src/game/layers.h @@ -24,7 +24,7 @@ public: CMapItemGroup *GameGroup() const { return m_pGameGroup; }; CMapItemLayerTilemap *GameLayer() const { return m_pGameLayer; }; CMapItemGroup *GetGroup(int Index) const; - CMapItemLayer *GetLayer(int Index) const; + CMapItemLayer *GetLayer(int Index) const; }; #endif diff --git a/src/game/localization.cpp b/src/game/localization.cpp index 69896300..8ab8831d 100644 --- a/src/game/localization.cpp +++ b/src/game/localization.cpp @@ -53,16 +53,16 @@ bool CLocalizationDatabase::Load(const char *pFilename, IStorage *pStorage, ICon m_CurrentVersion = 0; return true; } - + IOHANDLE IoHandle = pStorage->OpenFile(pFilename, IOFLAG_READ, IStorage::TYPE_ALL); if(!IoHandle) return false; - + char aBuf[256]; str_format(aBuf, sizeof(aBuf), "loaded '%s'", pFilename); pConsole->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "localization", aBuf); m_Strings.clear(); - + char aOrigin[512]; CLineReader LineReader; LineReader.Init(IoHandle); @@ -71,10 +71,10 @@ bool CLocalizationDatabase::Load(const char *pFilename, IStorage *pStorage, ICon { if(!str_length(pLine)) continue; - + if(pLine[0] == '#') // skip comments continue; - + str_copy(aOrigin, pLine, sizeof(aOrigin)); char *pReplacement = LineReader.Get(); if(!pReplacement) @@ -82,7 +82,7 @@ bool CLocalizationDatabase::Load(const char *pFilename, IStorage *pStorage, ICon pConsole->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "localization", "unexpected end of file"); break; } - + if(pReplacement[0] != '=' || pReplacement[1] != '=' || pReplacement[2] != ' ') { str_format(aBuf, sizeof(aBuf), "malform replacement line for '%s'", aOrigin); @@ -94,7 +94,7 @@ bool CLocalizationDatabase::Load(const char *pFilename, IStorage *pStorage, ICon AddString(aOrigin, pReplacement); } io_close(IoHandle); - + m_CurrentVersion = ++m_VersionCounter; return true; } diff --git a/src/game/localization.h b/src/game/localization.h index 277d637e..49edd860 100644 --- a/src/game/localization.h +++ b/src/game/localization.h @@ -11,7 +11,7 @@ class CLocalizationDatabase { public: unsigned m_Hash; - + // TODO: do this as an const char * and put everything on a incremental heap string m_Replacement; @@ -23,14 +23,14 @@ class CLocalizationDatabase sorted_array<CString> m_Strings; int m_VersionCounter; int m_CurrentVersion; - + public: CLocalizationDatabase(); bool Load(const char *pFilename, class IStorage *pStorage, class IConsole *pConsole); int Version() { return m_CurrentVersion; } - + void AddString(const char *pOrgStr, const char *pNewStr); const char *FindString(unsigned Hash); }; @@ -46,7 +46,7 @@ class CLocConstString public: CLocConstString(const char *pStr); void Reload(); - + inline operator const char *() { if(m_Version != g_Localization.Version()) diff --git a/src/game/mapitems.h b/src/game/mapitems.h index 31f7299f..d99d6724 100644 --- a/src/game/mapitems.h +++ b/src/game/mapitems.h @@ -10,7 +10,7 @@ enum LAYERTYPE_GAME, // not used LAYERTYPE_TILES, LAYERTYPE_QUADS, - + MAPITEMTYPE_VERSION=0, MAPITEMTYPE_INFO, MAPITEMTYPE_IMAGE, @@ -18,7 +18,7 @@ enum MAPITEMTYPE_GROUP, MAPITEMTYPE_LAYER, MAPITEMTYPE_ENVPOINTS, - + CURVETYPE_STEP=0, CURVETYPE_LINEAR, @@ -26,7 +26,7 @@ enum CURVETYPE_FAST, CURVETYPE_SMOOTH, NUM_CURVETYPES, - + // game layer tiles ENTITY_NULL=0, ENTITY_SPAWN, @@ -41,19 +41,19 @@ enum ENTITY_POWERUP_NINJA, ENTITY_WEAPON_RIFLE, NUM_ENTITIES, - + TILE_AIR=0, TILE_SOLID, TILE_DEATH, TILE_NOHOOK, - + TILEFLAG_VFLIP=1, TILEFLAG_HFLIP=2, TILEFLAG_OPAQUE=4, TILEFLAG_ROTATE=8, - + LAYERFLAG_DETAIL=1, - + ENTITY_OFFSET=255-16*4, }; @@ -72,10 +72,10 @@ struct CQuad CPoint m_aPoints[5]; CColor m_aColors[4]; CPoint m_aTexcoords[4]; - + int m_PosEnv; int m_PosEnvOffset; - + int m_ColorEnv; int m_ColorEnvOffset; }; @@ -115,7 +115,7 @@ struct CMapItemGroup_v1 struct CMapItemGroup : public CMapItemGroup_v1 { enum { CURRENT_VERSION=2 }; - + int m_UseClipping; int m_ClipX; int m_ClipY; @@ -134,15 +134,15 @@ struct CMapItemLayerTilemap { CMapItemLayer m_Layer; int m_Version; - + int m_Width; int m_Height; int m_Flags; - + CColor m_Color; int m_ColorEnv; int m_ColorEnvOffset; - + int m_Image; int m_Data; } ; @@ -151,7 +151,7 @@ struct CMapItemLayerQuads { CMapItemLayer m_Layer; int m_Version; - + int m_NumQuads; int m_Data; int m_Image; @@ -167,7 +167,7 @@ struct CEnvPoint int m_Time; // in ms int m_Curvetype; int m_aValues[4]; // 1-4 depending on envelope (22.10 fixed point) - + bool operator<(const CEnvPoint &Other) { return m_Time < Other.m_Time; } } ; diff --git a/src/game/server/entities/character.cpp b/src/game/server/entities/character.cpp index b40e768b..821aade5 100644 --- a/src/game/server/entities/character.cpp +++ b/src/game/server/entities/character.cpp @@ -22,7 +22,7 @@ CInputCount CountInput(int Prev, int Cur) Prev &= INPUT_STATE_MASK; Cur &= INPUT_STATE_MASK; int i = Prev; - + while(i != Cur) { i = (i+1)&INPUT_STATE_MASK; @@ -59,10 +59,10 @@ bool CCharacter::Spawn(CPlayer *pPlayer, vec2 Pos) m_ActiveWeapon = WEAPON_GUN; m_LastWeapon = WEAPON_HAMMER; m_QueuedWeapon = -1; - + m_pPlayer = pPlayer; m_Pos = Pos; - + m_Core.Reset(); m_Core.Init(&GameServer()->m_World.m_Core, GameServer()->Collision()); m_Core.m_Pos = m_Pos; @@ -71,7 +71,7 @@ bool CCharacter::Spawn(CPlayer *pPlayer, vec2 Pos) m_ReckoningTick = 0; mem_zero(&m_SendCore, sizeof(m_SendCore)); mem_zero(&m_ReckoningCore, sizeof(m_ReckoningCore)); - + GameServer()->m_World.InsertEntity(this); m_Alive = true; @@ -90,12 +90,12 @@ void CCharacter::SetWeapon(int W) { if(W == m_ActiveWeapon) return; - + m_LastWeapon = m_ActiveWeapon; m_QueuedWeapon = -1; m_ActiveWeapon = W; GameServer()->CreateSound(m_Pos, SOUND_WEAPON_SWITCH); - + if(m_ActiveWeapon < 0 || m_ActiveWeapon >= NUM_WEAPONS) m_ActiveWeapon = 0; } @@ -114,7 +114,7 @@ void CCharacter::HandleNinja() { if(m_ActiveWeapon != WEAPON_NINJA) return; - + vec2 Direction = normalize(vec2(m_LatestInput.m_TargetX, m_LatestInput.m_TargetY)); if ((Server()->Tick() - m_Ninja.m_ActivationTick) > (g_pData->m_Weapons.m_Ninja.m_Duration * Server()->TickSpeed() / 1000)) @@ -124,11 +124,11 @@ void CCharacter::HandleNinja() m_ActiveWeapon = m_LastWeapon; if(m_ActiveWeapon == WEAPON_NINJA) m_ActiveWeapon = WEAPON_GUN; - + SetWeapon(m_ActiveWeapon); return; } - + // force ninja Weapon SetWeapon(WEAPON_NINJA); @@ -146,7 +146,7 @@ void CCharacter::HandleNinja() m_Core.m_Vel = m_Ninja.m_ActivationDir * g_pData->m_Weapons.m_Ninja.m_Velocity; vec2 OldPos = m_Pos; GameServer()->Collision()->MoveBox(&m_Core.m_Pos, &m_Core.m_Vel, vec2(m_ProximityRadius, m_ProximityRadius), 0.f); - + // reset velocity so the client doesn't predict stuff m_Core.m_Vel = vec2(0.f, 0.f); @@ -162,7 +162,7 @@ void CCharacter::HandleNinja() { if (aEnts[i] == this) continue; - + // make sure we haven't Hit this object before bool bAlreadyHit = false; for (int j = 0; j < m_NumObjectsHit; j++) @@ -182,11 +182,11 @@ void CCharacter::HandleNinja() // set his velocity to fast upward (for now) if(m_NumObjectsHit < 10) m_apHitObjects[m_NumObjectsHit++] = aEnts[i]; - + aEnts[i]->TakeDamage(vec2(0, 10.0f), g_pData->m_Weapons.m_Ninja.m_pBase->m_Damage, m_pPlayer->GetCID(), WEAPON_NINJA); } } - + return; } @@ -209,7 +209,7 @@ void CCharacter::HandleWeaponSwitch() int WantedWeapon = m_ActiveWeapon; if(m_QueuedWeapon != -1) WantedWeapon = m_QueuedWeapon; - + // select Weapon int Next = CountInput(m_LatestPrevInput.m_NextWeapon, m_LatestInput.m_NextWeapon).m_Presses; int Prev = CountInput(m_LatestPrevInput.m_PrevWeapon, m_LatestInput.m_PrevWeapon).m_Presses; @@ -241,7 +241,7 @@ void CCharacter::HandleWeaponSwitch() // check for insane values if(WantedWeapon >= 0 && WantedWeapon < NUM_WEAPONS && WantedWeapon != m_ActiveWeapon && m_aWeapons[WantedWeapon].m_Got) m_QueuedWeapon = WantedWeapon; - + DoWeaponSwitch(); } @@ -249,10 +249,10 @@ void CCharacter::FireWeapon() { if(m_ReloadTimer != 0) return; - + DoWeaponSwitch(); vec2 Direction = normalize(vec2(m_LatestInput.m_TargetX, m_LatestInput.m_TargetY)); - + bool FullAuto = false; if(m_ActiveWeapon == WEAPON_GRENADE || m_ActiveWeapon == WEAPON_SHOTGUN || m_ActiveWeapon == WEAPON_RIFLE) FullAuto = true; @@ -262,13 +262,13 @@ void CCharacter::FireWeapon() bool WillFire = false; if(CountInput(m_LatestPrevInput.m_Fire, m_LatestInput.m_Fire).m_Presses) WillFire = true; - + if(FullAuto && (m_LatestInput.m_Fire&1) && m_aWeapons[m_ActiveWeapon].m_Ammo) WillFire = true; - + if(!WillFire) return; - + // check for ammo if(!m_aWeapons[m_ActiveWeapon].m_Ammo) { @@ -277,9 +277,9 @@ void CCharacter::FireWeapon() GameServer()->CreateSound(m_Pos, SOUND_WEAPON_NOAMMO); return; } - + vec2 ProjStartPos = m_Pos+Direction*m_ProximityRadius*0.75f; - + switch(m_ActiveWeapon) { case WEAPON_HAMMER: @@ -287,16 +287,16 @@ void CCharacter::FireWeapon() // reset objects Hit m_NumObjectsHit = 0; GameServer()->CreateSound(m_Pos, SOUND_HAMMER_FIRE); - + CCharacter *apEnts[MAX_CLIENTS]; int Hits = 0; - int Num = GameServer()->m_World.FindEntities(ProjStartPos, m_ProximityRadius*0.5f, (CEntity**)apEnts, + int Num = GameServer()->m_World.FindEntities(ProjStartPos, m_ProximityRadius*0.5f, (CEntity**)apEnts, MAX_CLIENTS, CGameWorld::ENTTYPE_CHARACTER); for (int i = 0; i < Num; ++i) { CCharacter *pTarget = apEnts[i]; - + if ((pTarget == this) || GameServer()->Collision()->IntersectLine(ProjStartPos, pTarget->m_Pos, NULL, NULL)) continue; @@ -305,22 +305,22 @@ void CCharacter::FireWeapon() GameServer()->CreateHammerHit(pTarget->m_Pos-normalize(pTarget->m_Pos-ProjStartPos)*m_ProximityRadius*0.5f); else GameServer()->CreateHammerHit(ProjStartPos); - + vec2 Dir; if (length(pTarget->m_Pos - m_Pos) > 0.0f) Dir = normalize(pTarget->m_Pos - m_Pos); else Dir = vec2(0.f, -1.f); - + pTarget->TakeDamage(vec2(0.f, -1.f) + normalize(Dir + vec2(0.f, -1.1f)) * 10.0f, g_pData->m_Weapons.m_Hammer.m_pBase->m_Damage, m_pPlayer->GetCID(), m_ActiveWeapon); Hits++; } - + // if we Hit anything, we have to wait for the reload if(Hits) m_ReloadTimer = Server()->TickSpeed()/3; - + } break; case WEAPON_GUN: @@ -331,28 +331,28 @@ void CCharacter::FireWeapon() Direction, (int)(Server()->TickSpeed()*GameServer()->Tuning()->m_GunLifetime), 1, 0, 0, -1, WEAPON_GUN); - + // pack the Projectile and send it to the client Directly CNetObj_Projectile p; pProj->FillInfo(&p); - + CMsgPacker Msg(NETMSGTYPE_SV_EXTRAPROJECTILE); Msg.AddInt(1); for(unsigned i = 0; i < sizeof(CNetObj_Projectile)/sizeof(int); i++) Msg.AddInt(((int *)&p)[i]); - + Server()->SendMsg(&Msg, 0, m_pPlayer->GetCID()); - + GameServer()->CreateSound(m_Pos, SOUND_GUN_FIRE); } break; - + case WEAPON_SHOTGUN: { int ShotSpread = 2; CMsgPacker Msg(NETMSGTYPE_SV_EXTRAPROJECTILE); Msg.AddInt(ShotSpread*2+1); - + for(int i = -ShotSpread; i <= ShotSpread; ++i) { float Spreading[] = {-0.185f, -0.070f, 0, 0.070f, 0.185f}; @@ -366,17 +366,17 @@ void CCharacter::FireWeapon() vec2(cosf(a), sinf(a))*Speed, (int)(Server()->TickSpeed()*GameServer()->Tuning()->m_ShotgunLifetime), 1, 0, 0, -1, WEAPON_SHOTGUN); - + // pack the Projectile and send it to the client Directly CNetObj_Projectile p; pProj->FillInfo(&p); - + for(unsigned i = 0; i < sizeof(CNetObj_Projectile)/sizeof(int); i++) Msg.AddInt(((int *)&p)[i]); } - Server()->SendMsg(&Msg, 0,m_pPlayer->GetCID()); - + Server()->SendMsg(&Msg, 0,m_pPlayer->GetCID()); + GameServer()->CreateSound(m_Pos, SOUND_SHOTGUN_FIRE); } break; @@ -392,41 +392,41 @@ void CCharacter::FireWeapon() // pack the Projectile and send it to the client Directly CNetObj_Projectile p; pProj->FillInfo(&p); - + CMsgPacker Msg(NETMSGTYPE_SV_EXTRAPROJECTILE); Msg.AddInt(1); for(unsigned i = 0; i < sizeof(CNetObj_Projectile)/sizeof(int); i++) Msg.AddInt(((int *)&p)[i]); Server()->SendMsg(&Msg, 0, m_pPlayer->GetCID()); - + GameServer()->CreateSound(m_Pos, SOUND_GRENADE_FIRE); } break; - + case WEAPON_RIFLE: { new CLaser(GameWorld(), m_Pos, Direction, GameServer()->Tuning()->m_LaserReach, m_pPlayer->GetCID()); GameServer()->CreateSound(m_Pos, SOUND_RIFLE_FIRE); } break; - + case WEAPON_NINJA: { // reset Hit objects m_NumObjectsHit = 0; - + m_Ninja.m_ActivationDir = Direction; m_Ninja.m_CurrentMoveTime = g_pData->m_Weapons.m_Ninja.m_Movetime * Server()->TickSpeed() / 1000; m_Ninja.m_OldVelAmount = length(m_Core.m_Vel); GameServer()->CreateSound(m_Pos, SOUND_NINJA_FIRE); } break; - + } - + m_AttackTick = Server()->Tick(); - + if(m_aWeapons[m_ActiveWeapon].m_Ammo > 0) // -1 == unlimited m_aWeapons[m_ActiveWeapon].m_Ammo--; - + if(!m_ReloadTimer) m_ReloadTimer = g_pData->m_Weapons.m_aId[m_ActiveWeapon].m_Firedelay * Server()->TickSpeed() / 1000; } @@ -435,7 +435,7 @@ void CCharacter::HandleWeapons() { //ninja HandleNinja(); - + vec2 Direction = normalize(vec2(m_LatestInput.m_TargetX, m_LatestInput.m_TargetY)); // check reload timer @@ -470,14 +470,14 @@ void CCharacter::HandleWeapons() m_aWeapons[m_ActiveWeapon].m_AmmoRegenStart = -1; } } - + return; } bool CCharacter::GiveWeapon(int Weapon, int Ammo) { if(m_aWeapons[Weapon].m_Ammo < g_pData->m_Weapons.m_aId[Weapon].m_Maxammo || !m_aWeapons[Weapon].m_Got) - { + { m_aWeapons[Weapon].m_Got = true; m_aWeapons[Weapon].m_Ammo = min(g_pData->m_Weapons.m_aId[Weapon].m_Maxammo, Ammo); return true; @@ -492,7 +492,7 @@ void CCharacter::GiveNinja() m_aWeapons[WEAPON_NINJA].m_Ammo = -1; m_LastWeapon = m_ActiveWeapon; m_ActiveWeapon = WEAPON_NINJA; - + GameServer()->CreateSound(m_Pos, SOUND_PICKUP_NINJA); } @@ -507,27 +507,27 @@ void CCharacter::OnPredictedInput(CNetObj_PlayerInput *pNewInput) // check for changes if(mem_comp(&m_Input, pNewInput, sizeof(CNetObj_PlayerInput)) != 0) m_LastAction = Server()->Tick(); - + // copy new input mem_copy(&m_Input, pNewInput, sizeof(m_Input)); m_NumInputs++; - + // or are not allowed to aim in the center if(m_Input.m_TargetX == 0 && m_Input.m_TargetY == 0) - m_Input.m_TargetY = -1; + m_Input.m_TargetY = -1; } void CCharacter::OnDirectInput(CNetObj_PlayerInput *pNewInput) { mem_copy(&m_LatestPrevInput, &m_LatestInput, sizeof(m_LatestInput)); mem_copy(&m_LatestInput, pNewInput, sizeof(m_LatestInput)); - + if(m_NumInputs > 2 && m_pPlayer->GetTeam() != TEAM_SPECTATORS) { HandleWeaponSwitch(); FireWeapon(); } - + mem_copy(&m_LatestPrevInput, &m_LatestInput, sizeof(m_LatestInput)); } @@ -538,13 +538,13 @@ void CCharacter::Tick() char Buf[128]; str_format(Buf, sizeof(Buf), "You were moved to %s due to team balancing", GameServer()->m_pController->GetTeamName(m_pPlayer->GetTeam())); GameServer()->SendBroadcast(Buf, m_pPlayer->GetCID()); - + m_pPlayer->m_ForceBalanced = false; } m_Core.m_Input = m_Input; m_Core.Tick(true); - + // handle death-tiles and leaving gamelayer if(GameServer()->Collision()->GetCollisionAt(m_Pos.x+m_ProximityRadius/3.f, m_Pos.y-m_ProximityRadius/3.f)&CCollision::COLFLAG_DEATH || GameServer()->Collision()->GetCollisionAt(m_Pos.x+m_ProximityRadius/3.f, m_Pos.y+m_ProximityRadius/3.f)&CCollision::COLFLAG_DEATH || @@ -554,7 +554,7 @@ void CCharacter::Tick() { Die(m_pPlayer->GetCID(), WEAPON_WORLD); } - + // handle Weapons HandleWeapons(); @@ -573,18 +573,18 @@ void CCharacter::TickDefered() m_ReckoningCore.Move(); m_ReckoningCore.Quantize(); } - + //lastsentcore vec2 StartPos = m_Core.m_Pos; vec2 StartVel = m_Core.m_Vel; bool StuckBefore = GameServer()->Collision()->TestBox(m_Core.m_Pos, vec2(28.0f, 28.0f)); - + m_Core.Move(); bool StuckAfterMove = GameServer()->Collision()->TestBox(m_Core.m_Pos, vec2(28.0f, 28.0f)); m_Core.Quantize(); bool StuckAfterQuant = GameServer()->Collision()->TestBox(m_Core.m_Pos, vec2(28.0f, 28.0f)); m_Pos = m_Core.m_Pos; - + if(!StuckBefore && (StuckAfterMove || StuckAfterQuant)) { // Hackish solution to get rid of strict-aliasing warning @@ -600,7 +600,7 @@ void CCharacter::TickDefered() StartVelY.f = StartVel.y; char aBuf[256]; - str_format(aBuf, sizeof(aBuf), "STUCK!!! %d %d %d %f %f %f %f %x %x %x %x", + str_format(aBuf, sizeof(aBuf), "STUCK!!! %d %d %d %f %f %f %f %x %x %x %x", StuckBefore, StuckAfterMove, StuckAfterQuant, @@ -613,20 +613,20 @@ void CCharacter::TickDefered() int Events = m_Core.m_TriggeredEvents; int Mask = CmaskAllExceptOne(m_pPlayer->GetCID()); - + if(Events&COREEVENT_GROUND_JUMP) GameServer()->CreateSound(m_Pos, SOUND_PLAYER_JUMP, Mask); - + if(Events&COREEVENT_HOOK_ATTACH_PLAYER) GameServer()->CreateSound(m_Pos, SOUND_HOOK_ATTACH_PLAYER, CmaskAll()); if(Events&COREEVENT_HOOK_ATTACH_GROUND) GameServer()->CreateSound(m_Pos, SOUND_HOOK_ATTACH_GROUND, Mask); if(Events&COREEVENT_HOOK_HIT_NOHOOK) GameServer()->CreateSound(m_Pos, SOUND_HOOK_NOATTACH, Mask); - + if(m_pPlayer->GetTeam() == TEAM_SPECTATORS) { m_Pos.x = m_Input.m_TargetX; m_Pos.y = m_Input.m_TargetY; } - + // update the m_SendCore if needed { CNetObj_Character Predicted; @@ -684,10 +684,10 @@ void CCharacter::Die(int Killer, int Weapon) // a nice sound GameServer()->CreateSound(m_Pos, SOUND_PLAYER_DIE); - + // this is for auto respawn after 3 secs m_pPlayer->m_DieTick = Server()->Tick(); - + m_Alive = false; GameServer()->m_World.RemoveEntity(this); GameServer()->m_World.m_Core.m_apCharacters[m_pPlayer->GetCID()] = 0; @@ -697,7 +697,7 @@ void CCharacter::Die(int Killer, int Weapon) bool CCharacter::TakeDamage(vec2 Force, int Dmg, int From, int Weapon) { m_Core.m_Vel += Force; - + if(GameServer()->m_pController->IsFriendlyFire(m_pPlayer->GetCID(), From) && !g_Config.m_SvTeamdamage) return false; @@ -728,7 +728,7 @@ bool CCharacter::TakeDamage(vec2 Force, int Dmg, int From, int Weapon) m_Health--; Dmg--; } - + if(Dmg > m_Armor) { Dmg -= m_Armor; @@ -740,7 +740,7 @@ bool CCharacter::TakeDamage(vec2 Force, int Dmg, int From, int Weapon) Dmg = 0; } } - + m_Health -= Dmg; } @@ -754,7 +754,7 @@ bool CCharacter::TakeDamage(vec2 Force, int Dmg, int From, int Weapon) if(m_Health <= 0) { Die(From, Weapon); - + // set attacker's face to happy (taunt!) if (From >= 0 && From != m_pPlayer->GetCID() && GameServer()->m_apPlayers[From]) { @@ -765,7 +765,7 @@ bool CCharacter::TakeDamage(vec2 Force, int Dmg, int From, int Weapon) pChr->m_EmoteStop = Server()->Tick() + Server()->TickSpeed(); } } - + return false; } @@ -784,11 +784,11 @@ void CCharacter::Snap(int SnappingClient) { if(NetworkClipped(SnappingClient)) return; - + CNetObj_Character *pCharacter = static_cast<CNetObj_Character *>(Server()->SnapNewItem(NETOBJTYPE_CHARACTER, m_pPlayer->GetCID(), sizeof(CNetObj_Character))); if(!pCharacter) return; - + // write down the m_Core if(!m_ReckoningTick || GameServer()->m_World.m_Paused) { @@ -802,7 +802,7 @@ void CCharacter::Snap(int SnappingClient) pCharacter->m_Tick = m_ReckoningTick; m_SendCore.Write(pCharacter); } - + // set emote if (m_EmoteStop < Server()->Tick()) { @@ -815,7 +815,7 @@ void CCharacter::Snap(int SnappingClient) pCharacter->m_AmmoCount = 0; pCharacter->m_Health = 0; pCharacter->m_Armor = 0; - + pCharacter->m_Weapon = m_ActiveWeapon; pCharacter->m_AttackTick = m_AttackTick; diff --git a/src/game/server/entities/character.h b/src/game/server/entities/character.h index b4009058..611dc427 100644 --- a/src/game/server/entities/character.h +++ b/src/game/server/entities/character.h @@ -19,25 +19,25 @@ enum class CCharacter : public CEntity { MACRO_ALLOC_POOL_ID() - + public: //character's size static const int ms_PhysSize = 28; CCharacter(CGameWorld *pWorld); - + virtual void Reset(); virtual void Destroy(); virtual void Tick(); virtual void TickDefered(); virtual void Snap(int SnappingClient); - + bool IsGrounded(); - + void SetWeapon(int W); void HandleWeaponSwitch(); void DoWeaponSwitch(); - + void HandleWeapons(); void HandleNinja(); @@ -46,53 +46,53 @@ public: void FireWeapon(); void Die(int Killer, int Weapon); - bool TakeDamage(vec2 Force, int Dmg, int From, int Weapon); + bool TakeDamage(vec2 Force, int Dmg, int From, int Weapon); bool Spawn(class CPlayer *pPlayer, vec2 Pos); bool Remove(); - + bool IncreaseHealth(int Amount); bool IncreaseArmor(int Amount); - + bool GiveWeapon(int Weapon, int Ammo); void GiveNinja(); - + void SetEmote(int Emote, int Tick); - + bool IsAlive() const { return m_Alive; } class CPlayer *GetPlayer() { return m_pPlayer; } - + private: // player controlling this character class CPlayer *m_pPlayer; - + bool m_Alive; // weapon info CEntity *m_apHitObjects[10]; int m_NumObjectsHit; - + struct WeaponStat { int m_AmmoRegenStart; int m_Ammo; int m_Ammocost; bool m_Got; - + } m_aWeapons[NUM_WEAPONS]; - + int m_ActiveWeapon; int m_LastWeapon; int m_QueuedWeapon; - + int m_ReloadTimer; int m_AttackTick; - + int m_DamageTaken; int m_EmoteType; int m_EmoteStop; - + // last tick that the player took any action ie some input int m_LastAction; @@ -100,12 +100,12 @@ private: CNetObj_PlayerInput m_LatestPrevInput; CNetObj_PlayerInput m_LatestInput; - // input + // input CNetObj_PlayerInput m_PrevInput; CNetObj_PlayerInput m_Input; int m_NumInputs; int m_Jumped; - + int m_DamageTakenTick; int m_Health; @@ -120,9 +120,9 @@ private: int m_OldVelAmount; } m_Ninja; - // the player core for the physics + // the player core for the physics CCharacterCore m_Core; - + // info for dead reckoning int m_ReckoningTick; // tick that we are performing dead reckoning From CCharacterCore m_SendCore; // core that we should send diff --git a/src/game/server/entities/flag.cpp b/src/game/server/entities/flag.cpp index 5ac3de47..d279e4df 100644 --- a/src/game/server/entities/flag.cpp +++ b/src/game/server/entities/flag.cpp @@ -10,7 +10,7 @@ CFlag::CFlag(CGameWorld *pGameWorld, int Team) m_ProximityRadius = ms_PhysSize; m_pCarryingCharacter = NULL; m_GrabTick = 0; - + Reset(); } diff --git a/src/game/server/entities/flag.h b/src/game/server/entities/flag.h index 89f5e2c5..2f91bc02 100644 --- a/src/game/server/entities/flag.h +++ b/src/game/server/entities/flag.h @@ -12,12 +12,12 @@ public: CCharacter *m_pCarryingCharacter; vec2 m_Vel; vec2 m_StandPos; - + int m_Team; int m_AtStand; int m_DropTick; int m_GrabTick; - + CFlag(CGameWorld *pGameWorld, int Team); virtual void Reset(); diff --git a/src/game/server/entities/laser.cpp b/src/game/server/entities/laser.cpp index 184702cb..30ed0a9b 100644 --- a/src/game/server/entities/laser.cpp +++ b/src/game/server/entities/laser.cpp @@ -28,7 +28,7 @@ bool CLaser::HitCharacter(vec2 From, vec2 To) m_From = From; m_Pos = At; - m_Energy = -1; + m_Energy = -1; Hit->TakeDamage(vec2(0.f, 0.f), GameServer()->Tuning()->m_LaserDamage, m_Owner, WEAPON_RIFLE); return true; } @@ -36,16 +36,16 @@ bool CLaser::HitCharacter(vec2 From, vec2 To) void CLaser::DoBounce() { m_EvalTick = Server()->Tick(); - + if(m_Energy < 0) { GameServer()->m_World.DestroyEntity(this); return; } - + vec2 To = m_Pos + m_Dir * m_Energy; vec2 OrgTo = To; - + if(GameServer()->Collision()->IntersectLine(m_Pos, To, 0x0, &To)) { if(!HitCharacter(m_Pos, To)) @@ -56,17 +56,17 @@ void CLaser::DoBounce() vec2 TempPos = m_Pos; vec2 TempDir = m_Dir * 4.0f; - + GameServer()->Collision()->MovePoint(&TempPos, &TempDir, 1.0f, 0); m_Pos = TempPos; m_Dir = normalize(TempDir); - + m_Energy -= distance(m_From, m_Pos) + GameServer()->Tuning()->m_LaserBounceCost; m_Bounces++; - + if(m_Bounces > GameServer()->Tuning()->m_LaserBounceNum) m_Energy = -1; - + GameServer()->CreateSound(m_Pos, SOUND_RIFLE_BOUNCE); } } @@ -80,7 +80,7 @@ void CLaser::DoBounce() } } } - + void CLaser::Reset() { GameServer()->m_World.DestroyEntity(this); diff --git a/src/game/server/entities/laser.h b/src/game/server/entities/laser.h index 91ba5df6..1d7fa227 100644 --- a/src/game/server/entities/laser.h +++ b/src/game/server/entities/laser.h @@ -9,15 +9,15 @@ class CLaser : public CEntity { public: CLaser(CGameWorld *pGameWorld, vec2 Pos, vec2 Direction, float StartEnergy, int Owner); - + virtual void Reset(); virtual void Tick(); virtual void Snap(int SnappingClient); - + protected: bool HitCharacter(vec2 From, vec2 To); void DoBounce(); - + private: vec2 m_From; vec2 m_Dir; diff --git a/src/game/server/entities/pickup.cpp b/src/game/server/entities/pickup.cpp index 56b319d2..ba26d85b 100644 --- a/src/game/server/entities/pickup.cpp +++ b/src/game/server/entities/pickup.cpp @@ -12,7 +12,7 @@ CPickup::CPickup(CGameWorld *pGameWorld, int Type, int SubType) m_ProximityRadius = PickupPhysSize; Reset(); - + GameWorld()->InsertEntity(this); } @@ -55,7 +55,7 @@ void CPickup::Tick() RespawnTime = g_pData->m_aPickups[m_Type].m_Respawntime; } break; - + case POWERUP_ARMOR: if(pChr->IncreaseArmor(1)) { @@ -83,7 +83,7 @@ void CPickup::Tick() } } break; - + case POWERUP_NINJA: { // activate ninja on target player @@ -101,7 +101,7 @@ void CPickup::Tick() pChr->SetEmote(EMOTE_ANGRY, Server()->Tick() + 1200 * Server()->TickSpeed() / 1000); break; } - + default: break; }; diff --git a/src/game/server/entities/pickup.h b/src/game/server/entities/pickup.h index 47a8ed6f..77347de2 100644 --- a/src/game/server/entities/pickup.h +++ b/src/game/server/entities/pickup.h @@ -11,11 +11,11 @@ class CPickup : public CEntity { public: CPickup(CGameWorld *pGameWorld, int Type, int SubType = 0); - + virtual void Reset(); virtual void Tick(); virtual void Snap(int SnappingClient); - + private: int m_Type; int m_Subtype; diff --git a/src/game/server/entities/projectile.cpp b/src/game/server/entities/projectile.cpp index 07e96627..2baa24b1 100644 --- a/src/game/server/entities/projectile.cpp +++ b/src/game/server/entities/projectile.cpp @@ -32,25 +32,25 @@ vec2 CProjectile::GetPos(float Time) { float Curvature = 0; float Speed = 0; - + switch(m_Type) { case WEAPON_GRENADE: Curvature = GameServer()->Tuning()->m_GrenadeCurvature; Speed = GameServer()->Tuning()->m_GrenadeSpeed; break; - + case WEAPON_SHOTGUN: Curvature = GameServer()->Tuning()->m_ShotgunCurvature; Speed = GameServer()->Tuning()->m_ShotgunSpeed; break; - + case WEAPON_GUN: Curvature = GameServer()->Tuning()->m_GunCurvature; Speed = GameServer()->Tuning()->m_GunSpeed; break; } - + return CalcPos(m_Pos, m_Direction, Curvature, Speed, Time); } @@ -66,7 +66,7 @@ void CProjectile::Tick() CCharacter *TargetChr = GameServer()->m_World.IntersectCharacter(PrevPos, CurPos, 6.0f, CurPos, OwnerChar); m_LifeSpan--; - + if(TargetChr || Collide || m_LifeSpan < 0 || GameLayerClipped(CurPos)) { if(m_LifeSpan >= 0 || m_Weapon == WEAPON_GRENADE) @@ -74,7 +74,7 @@ void CProjectile::Tick() if(m_Explosive) GameServer()->CreateExplosion(CurPos, m_Owner, m_Weapon, false); - + else if(TargetChr) TargetChr->TakeDamage(m_Direction * max(0.001f, m_Force), m_Damage, m_Owner, m_Weapon); @@ -95,7 +95,7 @@ void CProjectile::FillInfo(CNetObj_Projectile *pProj) void CProjectile::Snap(int SnappingClient) { float Ct = (Server()->Tick()-m_StartTick)/(float)Server()->TickSpeed(); - + if(NetworkClipped(SnappingClient, GetPos(Ct))) return; diff --git a/src/game/server/entities/projectile.h b/src/game/server/entities/projectile.h index 5e534066..5df04bcd 100644 --- a/src/game/server/entities/projectile.h +++ b/src/game/server/entities/projectile.h @@ -15,7 +15,7 @@ public: virtual void Reset(); virtual void Tick(); virtual void Snap(int SnappingClient); - + private: vec2 m_Direction; int m_LifeSpan; diff --git a/src/game/server/entity.cpp b/src/game/server/entity.cpp index 03b55982..788c3f45 100644 --- a/src/game/server/entity.cpp +++ b/src/game/server/entity.cpp @@ -10,12 +10,12 @@ CEntity::CEntity(CGameWorld *pGameWorld, int ObjType) { m_pGameWorld = pGameWorld; - + m_ObjType = ObjType; m_Pos = vec2(0,0); m_ProximityRadius = 0; - m_MarkedForDestroy = false; + m_MarkedForDestroy = false; m_ID = Server()->SnapNewID(); m_pPrevTypeEntity = 0; @@ -37,13 +37,13 @@ int CEntity::NetworkClipped(int SnappingClient, vec2 CheckPos) { if(SnappingClient == -1) return 0; - + float dx = GameServer()->m_apPlayers[SnappingClient]->m_ViewPos.x-CheckPos.x; float dy = GameServer()->m_apPlayers[SnappingClient]->m_ViewPos.y-CheckPos.y; - + if(absolute(dx) > 1000.0f || absolute(dy) > 800.0f) return 1; - + if(distance(GameServer()->m_apPlayers[SnappingClient]->m_ViewPos, CheckPos) > 1100.0f) return 1; return 0; diff --git a/src/game/server/entity.h b/src/game/server/entity.h index ff4d82eb..b9b33eb7 100644 --- a/src/game/server/entity.h +++ b/src/game/server/entity.h @@ -28,7 +28,7 @@ void *operator new(size_t Size, int id); \ void operator delete(void *p); \ private: - + #define MACRO_ALLOC_POOL_ID_IMPL(POOLTYPE, PoolSize) \ static char ms_PoolData##POOLTYPE[PoolSize][sizeof(POOLTYPE)] = {{0}}; \ static int ms_PoolUsed##POOLTYPE[PoolSize] = {0}; \ @@ -49,7 +49,7 @@ ms_PoolUsed##POOLTYPE[id] = 0; \ mem_zero(ms_PoolData##POOLTYPE[id], sizeof(POOLTYPE)); \ } - + /* Class: Entity Basic entity class. @@ -61,7 +61,7 @@ class CEntity friend class CGameWorld; // entity list handling CEntity *m_pPrevTypeEntity; CEntity *m_pNextTypeEntity; - + class CGameWorld *m_pGameWorld; protected: bool m_MarkedForDestroy; @@ -70,12 +70,12 @@ protected: public: CEntity(CGameWorld *pGameWorld, int Objtype); virtual ~CEntity(); - + class CGameWorld *GameWorld() { return m_pGameWorld; } class CGameContext *GameServer() { return GameWorld()->GameServer(); } class IServer *Server() { return GameWorld()->Server(); } - - + + CEntity *TypeNext() { return m_pNextTypeEntity; } CEntity *TypePrev() { return m_pPrevTypeEntity; } @@ -84,14 +84,14 @@ public: Destorys the entity. */ virtual void Destroy() { delete this; } - + /* Function: reset Called when the game resets the map. Puts the entity back to it's starting state or perhaps destroys it. */ virtual void Reset() {} - + /* Function: tick Called progress the entity to the next tick. Updates @@ -104,12 +104,12 @@ public: Called after all entities tick() function has been called. */ virtual void TickDefered() {} - + /* Function: snap Called when a new snapshot is being generated for a specific client. - + Arguments: snapping_client - ID of the client which snapshot is being generated. Could be -1 to create a complete @@ -117,7 +117,7 @@ public: recording. */ virtual void Snap(int SnappingClient) {} - + /* Function: networkclipped(int snapping_client) Performs a series of test to see if a client can see the @@ -128,13 +128,13 @@ public: being generated. Could be -1 to create a complete snapshot of everything in the game for demo recording. - + Returns: Non-zero if the entity doesn't have to be in the snapshot. */ int NetworkClipped(int SnappingClient); int NetworkClipped(int SnappingClient, vec2 CheckPos); - + bool GameLayerClipped(vec2 CheckPos); /* @@ -142,7 +142,7 @@ public: Contains the physical size of the entity. */ float m_ProximityRadius; - + /* Variable: pos Contains the current posititon of the entity. diff --git a/src/game/server/eventhandler.h b/src/game/server/eventhandler.h index ea9fcb15..721b59af 100644 --- a/src/game/server/eventhandler.h +++ b/src/game/server/eventhandler.h @@ -9,20 +9,20 @@ class CEventHandler static const int MAX_EVENTS = 128; static const int MAX_DATASIZE = 128*64; - int m_aTypes[MAX_EVENTS]; // TODO: remove some of these arrays + int m_aTypes[MAX_EVENTS]; // TODO: remove some of these arrays int m_aOffsets[MAX_EVENTS]; int m_aSizes[MAX_EVENTS]; int m_aClientMasks[MAX_EVENTS]; char m_aData[MAX_DATASIZE]; - + class CGameContext *m_pGameServer; - + int m_CurrentOffset; int m_NumEvents; public: CGameContext *GameServer() const { return m_pGameServer; } void SetGameServer(CGameContext *pGameServer); - + CEventHandler(); void *Create(int Type, int Size, int Mask = -1); void Clear(); diff --git a/src/game/server/gamecontext.cpp b/src/game/server/gamecontext.cpp index a0c1c64a..82adcbef 100644 --- a/src/game/server/gamecontext.cpp +++ b/src/game/server/gamecontext.cpp @@ -24,10 +24,10 @@ void CGameContext::Construct(int Resetting) { m_Resetting = 0; m_pServer = 0; - + for(int i = 0; i < MAX_CLIENTS; i++) m_apPlayers[i] = 0; - + m_pController = 0; m_VoteCloseTime = 0; m_pVoteOptionFirst = 0; @@ -241,7 +241,7 @@ void CGameContext::SendChat(int ChatterClientID, int Team, const char *pText) Msg.m_Team = 1; Msg.m_ClientID = ChatterClientID; Msg.m_pMessage = pText; - + // pack one for the recording only Server()->SendPackMsg(&Msg, MSGFLAG_VITAL|MSGFLAG_NOSEND, -1); @@ -277,7 +277,7 @@ void CGameContext::SendBroadcast(const char *pText, int ClientID) Server()->SendPackMsg(&Msg, MSGFLAG_VITAL, ClientID); } -// +// void CGameContext::StartVote(const char *pDesc, const char *pCommand, const char *pReason) { // check if a vote is already running @@ -294,7 +294,7 @@ void CGameContext::StartVote(const char *pDesc, const char *pCommand, const char m_apPlayers[i]->m_VotePos = 0; } } - + // start vote m_VoteCloseTime = time_get() + time_freq()*25; str_copy(m_aVoteDescription, pDesc, sizeof(m_aVoteDescription)); @@ -338,7 +338,7 @@ void CGameContext::SendVoteStatus(int ClientID, int Total, int Yes, int No) Msg.m_Pass = Total - (Yes+No); Server()->SendPackMsg(&Msg, MSGFLAG_VITAL, ClientID); - + } void CGameContext::AbortVoteKickOnDisconnect(int ClientID) @@ -353,7 +353,7 @@ void CGameContext::CheckPureTuning() // might not be created yet during start up if(!m_pController) return; - + if( str_comp(m_pController->m_pGameType, "DM")==0 || str_comp(m_pController->m_pGameType, "TDM")==0 || str_comp(m_pController->m_pGameType, "CTF")==0) @@ -364,13 +364,13 @@ void CGameContext::CheckPureTuning() Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", "resetting tuning due to pure server"); m_Tuning = p; } - } + } } void CGameContext::SendTuningParams(int ClientID) { CheckPureTuning(); - + CMsgPacker Msg(NETMSGTYPE_SV_TUNEPARAMS); int *pParams = (int *)&m_Tuning; for(unsigned i = 0; i < sizeof(m_Tuning)/sizeof(int); i++) @@ -389,7 +389,7 @@ void CGameContext::OnTick() //if(world.paused) // make sure that the game object always updates m_pController->Tick(); - + for(int i = 0; i < MAX_CLIENTS; i++) { if(m_apPlayers[i]) @@ -398,7 +398,7 @@ void CGameContext::OnTick() m_apPlayers[i]->PostTick(); } } - + // update voting if(m_VoteCloseTime) { @@ -423,10 +423,10 @@ void CGameContext::OnTick() { if(!m_apPlayers[i] || m_apPlayers[i]->GetTeam() == TEAM_SPECTATORS || aVoteChecked[i]) // don't count in votes by spectators continue; - + int ActVote = m_apPlayers[i]->m_Vote; int ActVotePos = m_apPlayers[i]->m_VotePos; - + // check for more players with the same ip (only use the vote of the one who voted first) for(int j = i+1; j < MAX_CLIENTS; ++j) { @@ -453,13 +453,13 @@ void CGameContext::OnTick() else if(No >= (Total+1)/2) m_VoteEnforce = VOTE_ENFORCE_NO; } - + if(m_VoteEnforce == VOTE_ENFORCE_YES) { Console()->ExecuteLine(m_aVoteCommand); EndVote(); SendChat(-1, CGameContext::CHAT_ALL, "Vote passed"); - + if(m_apPlayers[m_VoteCreator]) m_apPlayers[m_VoteCreator]->m_LastVoteCall = 0; } @@ -475,7 +475,7 @@ void CGameContext::OnTick() } } } - + #ifdef CONF_DEBUG if(g_Config.m_DbgDummies) @@ -487,7 +487,7 @@ void CGameContext::OnTick() m_apPlayers[MAX_CLIENTS-i-1]->OnPredictedInput(&Input); } } -#endif +#endif } // Server hooks @@ -509,7 +509,7 @@ void CGameContext::OnClientEnter(int ClientID) m_apPlayers[ClientID]->Respawn(); char aBuf[512]; str_format(aBuf, sizeof(aBuf), "'%s' entered and joined the %s", Server()->ClientName(ClientID), m_pController->GetTeamName(m_apPlayers[ClientID]->GetTeam())); - SendChat(-1, CGameContext::CHAT_ALL, aBuf); + SendChat(-1, CGameContext::CHAT_ALL, aBuf); str_format(aBuf, sizeof(aBuf), "team_join player='%d:%s' team=%d", ClientID, Server()->ClientName(ClientID), m_apPlayers[ClientID]->GetTeam()); Console()->Print(IConsole::OUTPUT_LEVEL_DEBUG, "game", aBuf); @@ -525,7 +525,7 @@ void CGameContext::OnClientConnected(int ClientID) m_apPlayers[ClientID] = new(ClientID) CPlayer(this, ClientID, StartTeam); //players[client_id].init(client_id); //players[client_id].client_id = client_id; - + (void)m_pController->CheckTeamBalance(); #ifdef CONF_DEBUG @@ -552,7 +552,7 @@ void CGameContext::OnClientDrop(int ClientID, const char *pReason) m_apPlayers[ClientID]->OnDisconnect(pReason); delete m_apPlayers[ClientID]; m_apPlayers[ClientID] = 0; - + (void)m_pController->CheckTeamBalance(); m_VoteUpdate = true; @@ -568,7 +568,7 @@ void CGameContext::OnMessage(int MsgID, CUnpacker *pUnpacker, int ClientID) { void *pRawMsg = m_NetObjHandler.SecureUnpackMsg(MsgID, pUnpacker); CPlayer *pPlayer = m_apPlayers[ClientID]; - + if(!pRawMsg) { char aBuf[256]; @@ -576,7 +576,7 @@ void CGameContext::OnMessage(int MsgID, CUnpacker *pUnpacker, int ClientID) Console()->Print(IConsole::OUTPUT_LEVEL_DEBUG, "server", aBuf); return; } - + if(MsgID == NETMSGTYPE_CL_SAY) { CNetMsg_Cl_Say *pMsg = (CNetMsg_Cl_Say *)pRawMsg; @@ -585,10 +585,10 @@ void CGameContext::OnMessage(int MsgID, CUnpacker *pUnpacker, int ClientID) Team = pPlayer->GetTeam(); else Team = CGameContext::CHAT_ALL; - + if(g_Config.m_SvSpamprotection && pPlayer->m_LastChat && pPlayer->m_LastChat+Server()->TickSpeed() > Server()->Tick()) return; - + pPlayer->m_LastChat = Server()->Tick(); // check for invalid chars @@ -599,7 +599,7 @@ void CGameContext::OnMessage(int MsgID, CUnpacker *pUnpacker, int ClientID) *pMessage = ' '; pMessage++; } - + SendChat(ClientID, Team, pMsg->m_pMessage); } else if(MsgID == NETMSGTYPE_CL_CALLVOTE) @@ -620,7 +620,7 @@ void CGameContext::OnMessage(int MsgID, CUnpacker *pUnpacker, int ClientID) SendChatTarget(ClientID, "Wait for current vote to end before calling a new one."); return; } - + int Timeleft = pPlayer->m_LastVoteCall + Server()->TickSpeed()*60 - Now; if(pPlayer->m_LastVoteCall && Timeleft > 0) { @@ -629,7 +629,7 @@ void CGameContext::OnMessage(int MsgID, CUnpacker *pUnpacker, int ClientID) SendChatTarget(ClientID, aChatmsg); return; } - + char aChatmsg[512] = {0}; char aDesc[VOTE_DESC_LENGTH] = {0}; char aCmd[VOTE_CMD_LENGTH] = {0}; @@ -652,7 +652,7 @@ void CGameContext::OnMessage(int MsgID, CUnpacker *pUnpacker, int ClientID) pOption = pOption->m_pNext; } - + if(!pOption) { str_format(aChatmsg, sizeof(aChatmsg), "'%s' isn't an option on this server", pMsg->m_Value); @@ -682,7 +682,7 @@ void CGameContext::OnMessage(int MsgID, CUnpacker *pUnpacker, int ClientID) return; } } - + int KickID = str_toint(pMsg->m_Value); if(KickID < 0 || KickID >= MAX_CLIENTS || !m_apPlayers[KickID]) { @@ -702,7 +702,7 @@ void CGameContext::OnMessage(int MsgID, CUnpacker *pUnpacker, int ClientID) SendChatTarget(KickID, aBufKick); return; } - + str_format(aChatmsg, sizeof(aChatmsg), "'%s' called for vote to kick '%s' (%s)", Server()->ClientName(ClientID), Server()->ClientName(KickID), pReason); str_format(aDesc, sizeof(aDesc), "Kick '%s'", Server()->ClientName(KickID)); if (!g_Config.m_SvVoteKickBantime) @@ -722,7 +722,7 @@ void CGameContext::OnMessage(int MsgID, CUnpacker *pUnpacker, int ClientID) SendChatTarget(ClientID, "Server does not allow voting to move players to spectators"); return; } - + int SpectateID = str_toint(pMsg->m_Value); if(SpectateID < 0 || SpectateID >= MAX_CLIENTS || !m_apPlayers[SpectateID] || m_apPlayers[SpectateID]->GetTeam() == TEAM_SPECTATORS) { @@ -734,12 +734,12 @@ void CGameContext::OnMessage(int MsgID, CUnpacker *pUnpacker, int ClientID) SendChatTarget(ClientID, "You cant move yourself"); return; } - + str_format(aChatmsg, sizeof(aChatmsg), "'%s' called for vote to move '%s' to spectators (%s)", Server()->ClientName(ClientID), Server()->ClientName(SpectateID), pReason); str_format(aDesc, sizeof(aDesc), "move '%s' to spectators", Server()->ClientName(SpectateID)); str_format(aCmd, sizeof(aCmd), "set_team %d -1", SpectateID); } - + if(aCmd[0]) { SendChat(-1, CGameContext::CHAT_ALL, aChatmsg); @@ -769,7 +769,7 @@ void CGameContext::OnMessage(int MsgID, CUnpacker *pUnpacker, int ClientID) else if (MsgID == NETMSGTYPE_CL_SETTEAM && !m_World.m_Paused) { CNetMsg_Cl_SetTeam *pMsg = (CNetMsg_Cl_SetTeam *)pRawMsg; - + if(pPlayer->GetTeam() == pMsg->m_Team || (g_Config.m_SvSpamprotection && pPlayer->m_LastSetTeam && pPlayer->m_LastSetTeam+Server()->TickSpeed()*3 > Server()->Tick())) return; @@ -797,7 +797,7 @@ void CGameContext::OnMessage(int MsgID, CUnpacker *pUnpacker, int ClientID) else if (MsgID == NETMSGTYPE_CL_SETSPECTATORMODE && !m_World.m_Paused) { CNetMsg_Cl_SetSpectatorMode *pMsg = (CNetMsg_Cl_SetSpectatorMode *)pRawMsg; - + if(pPlayer->GetTeam() != TEAM_SPECTATORS || pPlayer->m_SpectatorID == pMsg->m_SpectatorID || ClientID == pMsg->m_SpectatorID || (g_Config.m_SvSpamprotection && pPlayer->m_LastSetSpectatorMode && pPlayer->m_LastSetSpectatorMode+Server()->TickSpeed()*3 > Server()->Tick())) return; @@ -809,13 +809,13 @@ void CGameContext::OnMessage(int MsgID, CUnpacker *pUnpacker, int ClientID) pPlayer->m_SpectatorID = pMsg->m_SpectatorID; } else if (MsgID == NETMSGTYPE_CL_STARTINFO) - { + { if(pPlayer->m_IsReady) return; - CNetMsg_Cl_StartInfo *pMsg = (CNetMsg_Cl_StartInfo *)pRawMsg; + CNetMsg_Cl_StartInfo *pMsg = (CNetMsg_Cl_StartInfo *)pRawMsg; pPlayer->m_LastChangeInfo = Server()->Tick(); - + // set start infos Server()->SetClientName(ClientID, pMsg->m_pName); Server()->SetClientClan(ClientID, pMsg->m_pClan); @@ -829,7 +829,7 @@ void CGameContext::OnMessage(int MsgID, CUnpacker *pUnpacker, int ClientID) // send vote options CNetMsg_Sv_VoteClearOptions ClearMsg; Server()->SendPackMsg(&ClearMsg, MSGFLAG_VITAL, ClientID); - + CNetMsg_Sv_VoteOptionListAdd OptionMsg; int NumOptions = 0; OptionMsg.m_pDescription0 = ""; @@ -897,7 +897,7 @@ void CGameContext::OnMessage(int MsgID, CUnpacker *pUnpacker, int ClientID) Server()->SendPackMsg(&OptionMsg, MSGFLAG_VITAL, ClientID); NumOptions = 0; } - + // send tuning parameters to client SendTuningParams(ClientID); @@ -907,16 +907,16 @@ void CGameContext::OnMessage(int MsgID, CUnpacker *pUnpacker, int ClientID) Server()->SendPackMsg(&m, MSGFLAG_VITAL|MSGFLAG_FLUSH, ClientID); } else if (MsgID == NETMSGTYPE_CL_CHANGEINFO) - { + { if(g_Config.m_SvSpamprotection && pPlayer->m_LastChangeInfo && pPlayer->m_LastChangeInfo+Server()->TickSpeed()*5 > Server()->Tick()) return; - + CNetMsg_Cl_ChangeInfo *pMsg = (CNetMsg_Cl_ChangeInfo *)pRawMsg; pPlayer->m_LastChangeInfo = Server()->Tick(); - + // set infos char aOldName[MAX_NAME_LENGTH]; - str_copy(aOldName, Server()->ClientName(ClientID), sizeof(aOldName)); + str_copy(aOldName, Server()->ClientName(ClientID), sizeof(aOldName)); Server()->SetClientName(ClientID, pMsg->m_pName); if(str_comp(aOldName, Server()->ClientName(ClientID)) != 0) { @@ -935,19 +935,19 @@ void CGameContext::OnMessage(int MsgID, CUnpacker *pUnpacker, int ClientID) else if (MsgID == NETMSGTYPE_CL_EMOTICON && !m_World.m_Paused) { CNetMsg_Cl_Emoticon *pMsg = (CNetMsg_Cl_Emoticon *)pRawMsg; - + if(g_Config.m_SvSpamprotection && pPlayer->m_LastEmote && pPlayer->m_LastEmote+Server()->TickSpeed()*3 > Server()->Tick()) return; - + pPlayer->m_LastEmote = Server()->Tick(); - + SendEmoticon(ClientID, pMsg->m_Emoticon); } else if (MsgID == NETMSGTYPE_CL_KILL && !m_World.m_Paused) { if(pPlayer->m_LastKill && pPlayer->m_LastKill+Server()->TickSpeed()*3 > Server()->Tick()) return; - + pPlayer->m_LastKill = Server()->Tick(); pPlayer->KillCharacter(WEAPON_SELF); } @@ -1024,14 +1024,14 @@ void CGameContext::ConSetTeam(IConsole::IResult *pResult, void *pUserData) CGameContext *pSelf = (CGameContext *)pUserData; int ClientID = clamp(pResult->GetInteger(0), 0, (int)MAX_CLIENTS-1); int Team = clamp(pResult->GetInteger(1), -1, 1); - + char aBuf[256]; str_format(aBuf, sizeof(aBuf), "moved client %d to team %d", ClientID, Team); pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", aBuf); - + if(!pSelf->m_apPlayers[ClientID]) return; - + pSelf->m_apPlayers[ClientID]->SetTeam(Team); (void)pSelf->m_pController->CheckTeamBalance(); } @@ -1040,15 +1040,15 @@ void CGameContext::ConSetTeamAll(IConsole::IResult *pResult, void *pUserData) { CGameContext *pSelf = (CGameContext *)pUserData; int Team = clamp(pResult->GetInteger(0), -1, 1); - + char aBuf[256]; str_format(aBuf, sizeof(aBuf), "moved all clients to team %d", Team); pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", aBuf); - + for(int i = 0; i < MAX_CLIENTS; ++i) if(pSelf->m_apPlayers[i]) pSelf->m_apPlayers[i]->SetTeam(Team); - + (void)pSelf->m_pController->CheckTeamBalance(); } @@ -1063,7 +1063,7 @@ void CGameContext::ConAddVote(IConsole::IResult *pResult, void *pUserData) pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", "maximum number of vote options reached"); return; } - + // check for valid option if(!pSelf->Console()->LineIsValid(pCommand) || str_length(pCommand) >= VOTE_CMD_LENGTH) { @@ -1081,7 +1081,7 @@ void CGameContext::ConAddVote(IConsole::IResult *pResult, void *pUserData) pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", aBuf); return; } - + // check for duplicate entry CVoteOptionServer *pOption = pSelf->m_pVoteOptionFirst; while(pOption) @@ -1095,11 +1095,11 @@ void CGameContext::ConAddVote(IConsole::IResult *pResult, void *pUserData) } pOption = pOption->m_pNext; } - + // add the option ++pSelf->m_NumVoteOptions; int Len = str_length(pCommand); - + pOption = (CVoteOptionServer *)pSelf->m_pVoteOptionHeap->Allocate(sizeof(CVoteOptionServer) + Len); pOption->m_pNext = 0; pOption->m_pPrev = pSelf->m_pVoteOptionLast; @@ -1108,7 +1108,7 @@ void CGameContext::ConAddVote(IConsole::IResult *pResult, void *pUserData) pSelf->m_pVoteOptionLast = pOption; if(!pSelf->m_pVoteOptionFirst) pSelf->m_pVoteOptionFirst = pOption; - + str_copy(pOption->m_aDescription, pDescription, sizeof(pOption->m_aDescription)); mem_copy(pOption->m_aCommand, pCommand, Len+1); char aBuf[256]; @@ -1125,7 +1125,7 @@ void CGameContext::ConRemoveVote(IConsole::IResult *pResult, void *pUserData) { CGameContext *pSelf = (CGameContext *)pUserData; const char *pDescription = pResult->GetString(0); - + // check for valid option CVoteOptionServer *pOption = pSelf->m_pVoteOptionFirst; while(pOption) @@ -1146,7 +1146,7 @@ void CGameContext::ConRemoveVote(IConsole::IResult *pResult, void *pUserData) CNetMsg_Sv_VoteOptionRemove OptionMsg; OptionMsg.m_pDescription = pOption->m_aDescription; pSelf->Server()->SendPackMsg(&OptionMsg, MSGFLAG_VITAL, -1); - + // TODO: improve this // remove the option --pSelf->m_NumVoteOptions; @@ -1173,7 +1173,7 @@ void CGameContext::ConRemoveVote(IConsole::IResult *pResult, void *pUserData) pVoteOptionLast = pDst; if(!pVoteOptionFirst) pVoteOptionFirst = pDst; - + str_copy(pDst->m_aDescription, pSrc->m_aDescription, sizeof(pDst->m_aDescription)); mem_copy(pDst->m_aCommand, pSrc->m_aCommand, Len+1); } @@ -1209,7 +1209,7 @@ void CGameContext::ConForceVote(IConsole::IResult *pResult, void *pUserData) pOption = pOption->m_pNext; } - + if(!pOption) { str_format(aBuf, sizeof(aBuf), "'%s' isn't an option on this server", pValue); @@ -1247,7 +1247,7 @@ void CGameContext::ConForceVote(IConsole::IResult *pResult, void *pUserData) pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", "Invalid client id to move"); return; } - + str_format(aBuf, sizeof(aBuf), "set_team %d -1", SpectateID); pSelf->Console()->ExecuteLine(aBuf); } @@ -1323,10 +1323,10 @@ void CGameContext::OnInit(/*class IKernel *pKernel*/) m_pConsole = Kernel()->RequestInterface<IConsole>(); m_World.SetGameServer(this); m_Events.SetGameServer(this); - + //if(!data) // only load once //data = load_data_from_memory(internal_data); - + for(int i = 0; i < NUM_NETOBJTYPES; i++) Server()->SnapSetStaticsize(i, m_NetObjHandler.GetObjSize(i)); @@ -1354,22 +1354,22 @@ void CGameContext::OnInit(/*class IKernel *pKernel*/) // create all entities from the game layer CMapItemLayerTilemap *pTileMap = m_Layers.GameLayer(); CTile *pTiles = (CTile *)Kernel()->RequestInterface<IMap>()->GetData(pTileMap->m_Data); - - - - + + + + /* num_spawn_points[0] = 0; num_spawn_points[1] = 0; num_spawn_points[2] = 0; */ - + for(int y = 0; y < pTileMap->m_Height; y++) { for(int x = 0; x < pTileMap->m_Width; x++) { int Index = pTiles[y*pTileMap->m_Width+x].m_Index; - + if(Index >= ENTITY_OFFSET) { vec2 Pos(x*32.0f+16.0f, y*32.0f+16.0f); @@ -1403,7 +1403,7 @@ void CGameContext::OnSnap(int ClientID) m_World.Snap(ClientID); m_pController->Snap(ClientID); m_Events.Snap(ClientID); - + for(int i = 0; i < MAX_CLIENTS; i++) { if(m_apPlayers[i]) diff --git a/src/game/server/gamecontext.h b/src/game/server/gamecontext.h index 576a1b10..6288850d 100644 --- a/src/game/server/gamecontext.h +++ b/src/game/server/gamecontext.h @@ -25,7 +25,7 @@ Remove entities marked for deletion (GAMEWORLD::remove_entities) Game Controller (GAMECONTROLLER::tick) All players (CPlayer::tick) - + Snap Game Context (CGameContext::snap) @@ -60,7 +60,7 @@ class CGameContext : public IGameServer static void ConClearVotes(IConsole::IResult *pResult, void *pUserData); static void ConVote(IConsole::IResult *pResult, void *pUserData); static void ConchainSpecialMotdupdate(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData); - + CGameContext(int Resetting); void Construct(int Resetting); @@ -73,25 +73,25 @@ public: CGameContext(); ~CGameContext(); - + void Clear(); - + CEventHandler m_Events; CPlayer *m_apPlayers[MAX_CLIENTS]; IGameController *m_pController; CGameWorld m_World; - + // helper functions class CCharacter *GetPlayerChar(int ClientID); - + // voting void StartVote(const char *pDesc, const char *pCommand, const char *pReason); void EndVote(); void SendVoteSet(int ClientID); void SendVoteStatus(int ClientID, int Total, int Yes, int No); void AbortVoteKickOnDisconnect(int ClientID); - + int m_VoteCreator; int64 m_VoteCloseTime; bool m_VoteUpdate; @@ -118,7 +118,7 @@ public: void CreatePlayerSpawn(vec2 Pos); void CreateDeath(vec2 Pos, int Who); void CreateSound(vec2 Pos, int Sound, int Mask=-1); - void CreateSoundGlobal(int Sound, int Target=-1); + void CreateSoundGlobal(int Sound, int Target=-1); enum @@ -135,22 +135,22 @@ public: void SendEmoticon(int ClientID, int Emoticon); void SendWeaponPickup(int ClientID, int Weapon); void SendBroadcast(const char *pText, int ClientID); - - + + // void CheckPureTuning(); void SendTuningParams(int ClientID); - + // engine events virtual void OnInit(); virtual void OnConsoleInit(); virtual void OnShutdown(); - + virtual void OnTick(); virtual void OnPreSnap(); virtual void OnSnap(int ClientID); virtual void OnPostSnap(); - + virtual void OnMessage(int MsgID, CUnpacker *pUnpacker, int ClientID); virtual void OnClientConnected(int ClientID); diff --git a/src/game/server/gamecontroller.cpp b/src/game/server/gamecontroller.cpp index c5a96570..6685bba3 100644 --- a/src/game/server/gamecontroller.cpp +++ b/src/game/server/gamecontroller.cpp @@ -15,7 +15,7 @@ IGameController::IGameController(class CGameContext *pGameServer) m_pGameServer = pGameServer; m_pServer = m_pGameServer->Server(); m_pGameType = "unknown"; - + // DoWarmup(g_Config.m_SvWarmup); m_GameOverTick = -1; @@ -26,10 +26,10 @@ IGameController::IGameController(class CGameContext *pGameServer) m_aTeamscore[TEAM_RED] = 0; m_aTeamscore[TEAM_BLUE] = 0; m_aMapWish[0] = 0; - + m_UnbalancedTick = -1; m_ForceBalanced = false; - + m_aNumSpawnPoints[0] = 0; m_aNumSpawnPoints[1] = 0; m_aNumSpawnPoints[2] = 0; @@ -49,18 +49,18 @@ float IGameController::EvaluateSpawnPos(CSpawnEval *pEval, vec2 Pos) float Scoremod = 1.0f; if(pEval->m_FriendlyTeam != -1 && pC->GetPlayer()->GetTeam() == pEval->m_FriendlyTeam) Scoremod = 0.5f; - + float d = distance(Pos, pC->m_Pos); Score += Scoremod * (d == 0 ? 1000000000.0f : 1.0f/d); } - + return Score; } void IGameController::EvaluateSpawnType(CSpawnEval *pEval, int Type) { // get spawn point - for(int i = 0; i < m_aNumSpawnPoints[Type]; i++) + for(int i = 0; i < m_aNumSpawnPoints[Type]; i++) { // check if the position is occupado if(GameServer()->m_World.FindEntities(m_aaSpawnPoints[Type][i], 64, 0, 1, CGameWorld::ENTTYPE_CHARACTER)) @@ -80,7 +80,7 @@ void IGameController::EvaluateSpawnType(CSpawnEval *pEval, int Type) void IGameController::FindFreeSpawn(CSpawnEval *pEval, int Type) { // pick the spawn point that is least occupied and has free space for spawning around it - for(int i = 0; i < m_aNumSpawnPoints[Type]; i++) + for(int i = 0; i < m_aNumSpawnPoints[Type]; i++) { CCharacter *aEnts[MAX_CLIENTS]; @@ -88,7 +88,7 @@ void IGameController::FindFreeSpawn(CSpawnEval *pEval, int Type) float Score = 0.0f; for(int c = 0; c < Num; ++c) Score += 96.0f - distance(aEnts[c]->m_Pos, m_aaSpawnPoints[Type][i]); - + if(!pEval->m_Got || pEval->m_Score > Score) { // start, left, up, right, down @@ -121,15 +121,15 @@ void IGameController::FindFreeSpawn(CSpawnEval *pEval, int Type) bool IGameController::CanSpawn(int Team, vec2 *pOutPos) { CSpawnEval Eval; - + // spectators can't spawn if(Team == TEAM_SPECTATORS) return false; - + if(IsTeamplay()) { Eval.m_FriendlyTeam = Team; - + // first try own team spawn, then normal spawn and then enemy EvaluateSpawnType(&Eval, 1+(Team&1)); if(!Eval.m_Got) @@ -167,7 +167,7 @@ bool IGameController::CanSpawn(int Team, vec2 *pOutPos) FindFreeSpawn(&Eval, 2); } } - + *pOutPos = Eval.m_Pos; return Eval.m_Got; } @@ -177,7 +177,7 @@ bool IGameController::OnEntity(int Index, vec2 Pos) { int Type = -1; int SubType = 0; - + if(Index == ENTITY_SPAWN) m_aaSpawnPoints[0][m_aNumSpawnPoints[0]++] = Pos; else if(Index == ENTITY_SPAWN_RED) @@ -208,7 +208,7 @@ bool IGameController::OnEntity(int Index, vec2 Pos) Type = POWERUP_NINJA; SubType = WEAPON_NINJA; } - + if(Type != -1) { CPickup *pPickup = new CPickup(&GameServer()->m_World, Type, SubType); @@ -223,7 +223,7 @@ void IGameController::EndRound() { if(m_Warmup) // game can't end when we are running warmup return; - + GameServer()->m_World.m_Paused = true; m_GameOverTick = Server()->Tick(); m_SuddenDeath = 0; @@ -248,7 +248,7 @@ const char *IGameController::GetTeamName(int Team) if(Team == 0) return "game"; } - + return "spectators"; } @@ -257,7 +257,7 @@ static bool IsSeparator(char c) { return c == ';' || c == ' ' || c == ',' || c = void IGameController::StartRound() { ResetGame(); - + m_RoundStartTick = Server()->Tick(); m_SuddenDeath = 0; m_GameOverTick = -1; @@ -293,11 +293,11 @@ void IGameController::CycleMap() if(m_RoundCount < g_Config.m_SvRoundsPerMap-1) return; - + // handle maprotation const char *pMapRotation = g_Config.m_SvMaprotation; const char *pCurrentMap = g_Config.m_SvMap; - + int CurrentMapLen = str_length(pCurrentMap); const char *pNextMap = pMapRotation; while(*pNextMap) @@ -305,25 +305,25 @@ void IGameController::CycleMap() int WordLen = 0; while(pNextMap[WordLen] && !IsSeparator(pNextMap[WordLen])) WordLen++; - + if(WordLen == CurrentMapLen && str_comp_num(pNextMap, pCurrentMap, CurrentMapLen) == 0) { // map found pNextMap += CurrentMapLen; while(*pNextMap && IsSeparator(*pNextMap)) pNextMap++; - + break; } - + pNextMap++; } - + // restart rotation if(pNextMap[0] == 0) pNextMap = pMapRotation; - // cut out the next map + // cut out the next map char aBuf[512]; for(int i = 0; i < 512; i++) { @@ -334,14 +334,14 @@ void IGameController::CycleMap() break; } } - + // skip spaces int i = 0; while(IsSeparator(aBuf[i])) i++; - + m_RoundCount = 0; - + char aBufMsg[256]; str_format(aBufMsg, sizeof(aBufMsg), "rotating map to %s", &aBuf[i]); GameServer()->Console()->Print(IConsole::OUTPUT_LEVEL_DEBUG, "game", aBuf); @@ -361,7 +361,7 @@ void IGameController::PostReset() } } } - + void IGameController::OnPlayerInfoChange(class CPlayer *pP) { const int aTeamColors[2] = {65387, 10223467}; @@ -405,7 +405,7 @@ void IGameController::OnCharacterSpawn(class CCharacter *pChr) { // default health pChr->IncreaseHealth(10); - + // give default weapons pChr->GiveWeapon(WEAPON_HAMMER, -1); pChr->GiveWeapon(WEAPON_GUN, 10); @@ -423,16 +423,16 @@ bool IGameController::IsFriendlyFire(int ClientID1, int ClientID2) { if(ClientID1 == ClientID2) return false; - + if(IsTeamplay()) { if(!GameServer()->m_apPlayers[ClientID1] || !GameServer()->m_apPlayers[ClientID2]) return false; - + if(GameServer()->m_apPlayers[ClientID1]->GetTeam() == GameServer()->m_apPlayers[ClientID2]->GetTeam()) return true; } - + return false; } @@ -461,7 +461,7 @@ void IGameController::Tick() if(!m_Warmup) StartRound(); } - + if(m_GameOverTick != -1) { // game over.. wait for restart @@ -472,12 +472,12 @@ void IGameController::Tick() m_RoundCount++; } } - + // do team-balancing if (IsTeamplay() && m_UnbalancedTick != -1 && Server()->Tick() > m_UnbalancedTick+g_Config.m_SvTeambalanceTime*Server()->TickSpeed()*60) { GameServer()->Console()->Print(IConsole::OUTPUT_LEVEL_DEBUG, "game", "Balancing teams"); - + int aT[2] = {0,0}; float aTScore[2] = {0,0}; float aPScore[MAX_CLIENTS] = {0.0f}; @@ -491,13 +491,13 @@ void IGameController::Tick() aTScore[GameServer()->m_apPlayers[i]->GetTeam()] += aPScore[i]; } } - + // are teams unbalanced? if(absolute(aT[0]-aT[1]) >= 2) { int M = (aT[0] > aT[1]) ? 0 : 1; int NumBalance = absolute(aT[0]-aT[1]) / 2; - + do { CPlayer *pP = 0; @@ -513,16 +513,16 @@ void IGameController::Tick() PD = absolute((aTScore[M^1]+aPScore[i]) - (aTScore[M]-aPScore[i])); } } - + // move the player to the other team int Temp = pP->m_LastActionTick; pP->SetTeam(M^1); pP->m_LastActionTick = Temp; - + pP->Respawn(); pP->m_ForceBalanced = true; } while (--NumBalance); - + m_ForceBalanced = true; } m_UnbalancedTick = -1; @@ -595,7 +595,7 @@ void IGameController::Snap(int SnappingClient) pGameInfoObj->m_ScoreLimit = g_Config.m_SvScorelimit; pGameInfoObj->m_TimeLimit = g_Config.m_SvTimelimit; - + pGameInfoObj->m_RoundNum = (str_length(g_Config.m_SvMaprotation) && g_Config.m_SvRoundsPerMap) ? g_Config.m_SvRoundsPerMap : 0; pGameInfoObj->m_RoundCurrent = m_RoundCount+1; } @@ -605,7 +605,7 @@ int IGameController::GetAutoTeam(int NotThisID) // this will force the auto balancer to work overtime aswell if(g_Config.m_DbgStress) return 0; - + int aNumplayers[2] = {0,0}; for(int i = 0; i < MAX_CLIENTS; i++) { @@ -619,7 +619,7 @@ int IGameController::GetAutoTeam(int NotThisID) int Team = 0; if(IsTeamplay()) Team = aNumplayers[TEAM_RED] > aNumplayers[TEAM_BLUE] ? TEAM_BLUE : TEAM_RED; - + if(CanJoinTeam(Team, NotThisID)) return Team; return -1; @@ -639,7 +639,7 @@ bool IGameController::CanJoinTeam(int Team, int NotThisID) aNumplayers[GameServer()->m_apPlayers[i]->GetTeam()]++; } } - + return (aNumplayers[0] + aNumplayers[1]) < g_Config.m_SvMaxClients-g_Config.m_SvSpectatorSlots; } @@ -647,7 +647,7 @@ bool IGameController::CheckTeamBalance() { if(!IsTeamplay() || !g_Config.m_SvTeambalanceTime) return true; - + int aT[2] = {0, 0}; for(int i = 0; i < MAX_CLIENTS; i++) { @@ -655,7 +655,7 @@ bool IGameController::CheckTeamBalance() if(pP && pP->GetTeam() != TEAM_SPECTATORS) aT[pP->GetTeam()]++; } - + char aBuf[256]; if(absolute(aT[0]-aT[1]) >= 2) { @@ -677,22 +677,22 @@ bool IGameController::CheckTeamBalance() bool IGameController::CanChangeTeam(CPlayer *pPlayer, int JoinTeam) { int aT[2] = {0, 0}; - + if (!IsTeamplay() || JoinTeam == TEAM_SPECTATORS || !g_Config.m_SvTeambalanceTime) return true; - + for(int i = 0; i < MAX_CLIENTS; i++) { CPlayer *pP = GameServer()->m_apPlayers[i]; if(pP && pP->GetTeam() != TEAM_SPECTATORS) aT[pP->GetTeam()]++; } - + // simulate what would happen if changed team aT[JoinTeam]++; if (pPlayer->GetTeam() != TEAM_SPECTATORS) aT[JoinTeam^1]--; - + // there is a player-difference of at least 2 if(absolute(aT[0]-aT[1]) >= 2) { @@ -708,7 +708,7 @@ bool IGameController::CanChangeTeam(CPlayer *pPlayer, int JoinTeam) void IGameController::DoPlayerScoreWincheck() { - if(m_GameOverTick == -1 && !m_Warmup) + if(m_GameOverTick == -1 && !m_Warmup) { // gather some stats int Topscore = 0; @@ -726,7 +726,7 @@ void IGameController::DoPlayerScoreWincheck() TopscoreCount++; } } - + // check score win condition if((g_Config.m_SvScorelimit > 0 && Topscore >= g_Config.m_SvScorelimit) || (g_Config.m_SvTimelimit > 0 && (Server()->Tick()-m_RoundStartTick) >= g_Config.m_SvTimelimit*Server()->TickSpeed()*60)) diff --git a/src/game/server/gamecontroller.h b/src/game/server/gamecontroller.h index c999f84e..6ccfe977 100644 --- a/src/game/server/gamecontroller.h +++ b/src/game/server/gamecontroller.h @@ -14,10 +14,10 @@ class IGameController { vec2 m_aaSpawnPoints[3][64]; int m_aNumSpawnPoints[3]; - + class CGameContext *m_pGameServer; class IServer *m_pServer; - + protected: CGameContext *GameServer() const { return m_pGameServer; } IServer *Server() const { return m_pServer; } @@ -30,7 +30,7 @@ protected: m_FriendlyTeam = -1; m_Pos = vec2(100,100); } - + vec2 m_Pos; bool m_Got; int m_FriendlyTeam; @@ -44,80 +44,80 @@ protected: void CycleMap(); void ResetGame(); - + char m_aMapWish[128]; - + int m_RoundStartTick; int m_GameOverTick; int m_SuddenDeath; - + int m_aTeamscore[2]; - + int m_Warmup; int m_RoundCount; - + int m_GameFlags; int m_UnbalancedTick; bool m_ForceBalanced; - + public: const char *m_pGameType; bool IsTeamplay() const; - + IGameController(class CGameContext *pGameServer); virtual ~IGameController(); void DoTeamScoreWincheck(); void DoPlayerScoreWincheck(); - + void DoWarmup(int Seconds); - + void StartRound(); void EndRound(); void ChangeMap(const char *pToMap); - + bool IsFriendlyFire(int ClientID1, int ClientID2); - + bool IsForceBalanced(); /* - - */ + + */ virtual bool CanBeMovedOnBalance(int ClientID); virtual void Tick(); - + virtual void Snap(int SnappingClient); - + /* Function: on_entity Called when the map is loaded to process an entity in the map. - + Arguments: index - Entity index. pos - Where the entity is located in the world. - + Returns: bool? */ virtual bool OnEntity(int Index, vec2 Pos); - + /* Function: on_CCharacter_spawn Called when a CCharacter spawns into the game world. - + Arguments: chr - The CCharacter that was spawned. */ virtual void OnCharacterSpawn(class CCharacter *pChr); - + /* Function: on_CCharacter_death Called when a CCharacter in the world dies. - + Arguments: victim - The CCharacter that died. killer - The player that killed it. @@ -133,8 +133,8 @@ public: virtual bool CanSpawn(int Team, vec2 *pPos); /* - - */ + + */ virtual const char *GetTeamName(int Team); virtual int GetAutoTeam(int NotThisID); virtual bool CanJoinTeam(int Team, int NotThisID); diff --git a/src/game/server/gamemodes/ctf.cpp b/src/game/server/gamemodes/ctf.cpp index fb177d5d..b1d3d2fa 100644 --- a/src/game/server/gamemodes/ctf.cpp +++ b/src/game/server/gamemodes/ctf.cpp @@ -20,13 +20,13 @@ bool CGameControllerCTF::OnEntity(int Index, vec2 Pos) { if(IGameController::OnEntity(Index, Pos)) return true; - + int Team = -1; if(Index == ENTITY_FLAGSTAND_RED) Team = TEAM_RED; if(Index == ENTITY_FLAGSTAND_BLUE) Team = TEAM_BLUE; if(Team == -1 || m_apFlags[Team]) return false; - + CFlag *F = new CFlag(&GameServer()->m_World, Team); F->m_StandPos = Pos; F->m_Pos = Pos; @@ -39,7 +39,7 @@ int CGameControllerCTF::OnCharacterDeath(class CCharacter *pVictim, class CPlaye { IGameController::OnCharacterDeath(pVictim, pKiller, WeaponID); int HadFlag = 0; - + // drop flags for(int i = 0; i < 2; i++) { @@ -52,14 +52,14 @@ int CGameControllerCTF::OnCharacterDeath(class CCharacter *pVictim, class CPlaye F->m_DropTick = Server()->Tick(); F->m_pCarryingCharacter = 0; F->m_Vel = vec2(0,0); - + if(pKiller && pKiller->GetTeam() != pVictim->GetPlayer()->GetTeam()) pKiller->m_Score++; - + HadFlag |= 1; } } - + return HadFlag; } @@ -118,14 +118,14 @@ void CGameControllerCTF::Tick() IGameController::Tick(); DoTeamScoreWincheck(); - + for(int fi = 0; fi < 2; fi++) { CFlag *F = m_apFlags[fi]; - + if(!F) continue; - + // flag hits death-tile or left the game layer, reset it if(GameServer()->Collision()->GetCollisionAt(F->m_Pos.x, F->m_Pos.y)&CCollision::COLFLAG_DEATH || F->GameLayerClipped(F->m_Pos)) { @@ -134,13 +134,13 @@ void CGameControllerCTF::Tick() F->Reset(); continue; } - + // if(F->m_pCarryingCharacter) { // update flag position F->m_Pos = F->m_pCarryingCharacter->m_Pos; - + if(m_apFlags[fi^1] && m_apFlags[fi^1]->m_AtStand) { if(distance(F->m_Pos, m_apFlags[fi^1]->m_Pos) < CFlag::ms_PhysSize + CCharacter::ms_PhysSize) @@ -167,7 +167,7 @@ void CGameControllerCTF::Tick() GameServer()->SendChat(-1, -2, aBuf); for(int i = 0; i < 2; i++) m_apFlags[i]->Reset(); - + GameServer()->CreateSoundGlobal(SOUND_CTF_CAPTURE); } } @@ -180,7 +180,7 @@ void CGameControllerCTF::Tick() { if(!apCloseCCharacters[i]->IsAlive() || apCloseCCharacters[i]->GetPlayer()->GetTeam() == TEAM_SPECTATORS || GameServer()->Collision()->IntersectLine(F->m_Pos, apCloseCCharacters[i]->m_Pos, NULL, NULL)) continue; - + if(apCloseCCharacters[i]->GetPlayer()->GetTeam() == F->m_Team) { // return the flag @@ -207,7 +207,7 @@ void CGameControllerCTF::Tick() m_aTeamscore[fi^1]++; F->m_GrabTick = Server()->Tick(); } - + F->m_AtStand = 0; F->m_pCarryingCharacter = apCloseCCharacters[i]; F->m_pCarryingCharacter->GetPlayer()->m_Score += 1; @@ -217,12 +217,12 @@ void CGameControllerCTF::Tick() F->m_pCarryingCharacter->GetPlayer()->GetCID(), Server()->ClientName(F->m_pCarryingCharacter->GetPlayer()->GetCID())); GameServer()->Console()->Print(IConsole::OUTPUT_LEVEL_DEBUG, "game", aBuf); - + for(int c = 0; c < MAX_CLIENTS; c++) { if(!GameServer()->m_apPlayers[c]) continue; - + if(GameServer()->m_apPlayers[c]->GetTeam() == fi) GameServer()->CreateSoundGlobal(SOUND_CTF_GRAB_EN, GameServer()->m_apPlayers[c]->GetCID()); else @@ -231,7 +231,7 @@ void CGameControllerCTF::Tick() break; } } - + if(!F->m_pCarryingCharacter && !F->m_AtStand) { if(Server()->Tick() > F->m_DropTick + Server()->TickSpeed()*30) diff --git a/src/game/server/gamemodes/ctf.h b/src/game/server/gamemodes/ctf.h index b9868e70..44bd9e8e 100644 --- a/src/game/server/gamemodes/ctf.h +++ b/src/game/server/gamemodes/ctf.h @@ -9,12 +9,12 @@ class CGameControllerCTF : public IGameController { public: class CFlag *m_apFlags[2]; - + CGameControllerCTF(class CGameContext *pGameServer); virtual bool CanBeMovedOnBalance(int ClientID); virtual void Snap(int SnappingClient); virtual void Tick(); - + virtual bool OnEntity(int Index, vec2 Pos); virtual int OnCharacterDeath(class CCharacter *pVictim, class CPlayer *pKiller, int Weapon); }; diff --git a/src/game/server/gamemodes/mod.cpp b/src/game/server/gamemodes/mod.cpp index ecf06e48..127be2bc 100644 --- a/src/game/server/gamemodes/mod.cpp +++ b/src/game/server/gamemodes/mod.cpp @@ -8,7 +8,7 @@ CGameControllerMOD::CGameControllerMOD(class CGameContext *pGameServer) // Exchange this to a string that identifies your game mode. // DM, TDM and CTF are reserved for teeworlds original modes. m_pGameType = "MOD"; - + //m_GameFlags = GAMEFLAG_TEAMS; // GAMEFLAG_TEAMS makes it a two-team gamemode } @@ -17,6 +17,6 @@ void CGameControllerMOD::Tick() // this is the main part of the gamemode, this function is run every tick DoPlayerScoreWincheck(); // checks for winners, no teams version //DoTeamScoreWincheck(); // checks for winners, two teams version - + IGameController::Tick(); } diff --git a/src/game/server/gamemodes/tdm.cpp b/src/game/server/gamemodes/tdm.cpp index fb0ff783..54e645b3 100644 --- a/src/game/server/gamemodes/tdm.cpp +++ b/src/game/server/gamemodes/tdm.cpp @@ -15,8 +15,8 @@ CGameControllerTDM::CGameControllerTDM(class CGameContext *pGameServer) : IGameC int CGameControllerTDM::OnCharacterDeath(class CCharacter *pVictim, class CPlayer *pKiller, int Weapon) { IGameController::OnCharacterDeath(pVictim, pKiller, Weapon); - - + + if(Weapon != WEAPON_GAME) { // do team scoring @@ -27,7 +27,7 @@ int CGameControllerTDM::OnCharacterDeath(class CCharacter *pVictim, class CPlaye } pVictim->GetPlayer()->m_RespawnTick = max(pVictim->GetPlayer()->m_RespawnTick, Server()->Tick()+Server()->TickSpeed()*g_Config.m_SvRespawnDelayTDM); - + return 0; } diff --git a/src/game/server/gamemodes/tdm.h b/src/game/server/gamemodes/tdm.h index c8d3f328..297b48c0 100644 --- a/src/game/server/gamemodes/tdm.h +++ b/src/game/server/gamemodes/tdm.h @@ -8,7 +8,7 @@ class CGameControllerTDM : public IGameController { public: CGameControllerTDM(class CGameContext *pGameServer); - + int OnCharacterDeath(class CCharacter *pVictim, class CPlayer *pKiller, int Weapon); virtual void Snap(int SnappingClient); virtual void Tick(); diff --git a/src/game/server/gameworld.cpp b/src/game/server/gameworld.cpp index 8fffabc8..6444cce5 100644 --- a/src/game/server/gameworld.cpp +++ b/src/game/server/gameworld.cpp @@ -12,7 +12,7 @@ CGameWorld::CGameWorld() { m_pGameServer = 0x0; m_pServer = 0x0; - + m_Paused = false; m_ResetRequested = false; for(int i = 0; i < NUM_ENTTYPES; i++) @@ -164,7 +164,7 @@ void CGameWorld::Tick() pEnt->Tick(); pEnt = m_pNextTraverseEntity; } - + for(int i = 0; i < NUM_ENTTYPES; i++) for(CEntity *pEnt = m_apFirstEntityTypes[i]; pEnt; ) { @@ -191,7 +191,7 @@ CCharacter *CGameWorld::IntersectCharacter(vec2 Pos0, vec2 Pos1, float Radius, v { if(p == pNotThis) continue; - + vec2 IntersectPos = closest_point_on_line(Pos0, Pos1, p->m_Pos); float Len = distance(p->m_Pos, IntersectPos); if(Len < p->m_ProximityRadius+Radius) @@ -205,7 +205,7 @@ CCharacter *CGameWorld::IntersectCharacter(vec2 Pos0, vec2 Pos1, float Radius, v } } } - + return pClosest; } @@ -215,13 +215,13 @@ CCharacter *CGameWorld::ClosestCharacter(vec2 Pos, float Radius, CEntity *pNotTh // Find other players float ClosestRange = Radius*2; CCharacter *pClosest = 0; - + CCharacter *p = (CCharacter *)GameServer()->m_World.FindFirst(ENTTYPE_CHARACTER); for(; p; p = (CCharacter *)p->TypeNext()) { if(p == pNotThis) continue; - + float Len = distance(Pos, p->m_Pos); if(Len < p->m_ProximityRadius+Radius) { @@ -232,6 +232,6 @@ CCharacter *CGameWorld::ClosestCharacter(vec2 Pos, float Radius, CEntity *pNotTh } } } - + return pClosest; } diff --git a/src/game/server/gameworld.h b/src/game/server/gameworld.h index 38002b87..a2fdbce0 100644 --- a/src/game/server/gameworld.h +++ b/src/game/server/gameworld.h @@ -32,7 +32,7 @@ private: CEntity *m_pNextTraverseEntity; CEntity *m_apFirstEntityTypes[NUM_ENTTYPES]; - + class CGameContext *m_pGameServer; class IServer *m_pServer; @@ -43,18 +43,18 @@ public: bool m_ResetRequested; bool m_Paused; CWorldCore m_Core; - + CGameWorld(); ~CGameWorld(); - + void SetGameServer(CGameContext *pGameServer); - + CEntity *FindFirst(int Type); - + /* Function: find_entities Finds entities close to a position and returns them in a list. - + Arguments: pos - Position. radius - How close the entities have to be. @@ -62,37 +62,37 @@ public: to the entities. max - Number of entities that fits into the ents array. type - Type of the entities to find. - + Returns: Number of entities found and added to the ents array. */ int FindEntities(vec2 Pos, float Radius, CEntity **ppEnts, int Max, int Type); - + /* Function: interserct_CCharacter Finds the closest CCharacter that intersects the line. - + Arguments: pos0 - Start position pos2 - End position radius - How for from the line the CCharacter is allowed to be. new_pos - Intersection position notthis - Entity to ignore intersecting with - + Returns: Returns a pointer to the closest hit or NULL of there is no intersection. */ class CCharacter *IntersectCharacter(vec2 Pos0, vec2 Pos1, float Radius, vec2 &NewPos, class CEntity *pNotThis = 0); - + /* Function: closest_CCharacter Finds the closest CCharacter to a specific point. - + Arguments: pos - The center position. radius - How far off the CCharacter is allowed to be notthis - Entity to ignore - + Returns: Returns a pointer to the closest CCharacter or NULL if no CCharacter is close enough. */ @@ -101,7 +101,7 @@ public: /* Function: insert_entity Adds an entity to the world. - + Arguments: entity - Entity to add */ @@ -110,7 +110,7 @@ public: /* Function: remove_entity Removes an entity from the world. - + Arguments: entity - Entity to remove */ @@ -119,28 +119,28 @@ public: /* Function: destroy_entity Destroys an entity in the world. - + Arguments: entity - Entity to destroy */ void DestroyEntity(CEntity *pEntity); - + /* Function: snap Calls snap on all the entities in the world to create the snapshot. - + Arguments: snapping_client - ID of the client which snapshot is being created. */ void Snap(int SnappingClient); - + /* Function: tick Calls tick on all the entities in the world to progress the world to the next tick. - + */ void Tick(); }; diff --git a/src/game/server/player.cpp b/src/game/server/player.cpp index cf0e6683..aeafe3a4 100644 --- a/src/game/server/player.cpp +++ b/src/game/server/player.cpp @@ -8,7 +8,7 @@ MACRO_ALLOC_POOL_ID_IMPL(CPlayer, MAX_CLIENTS) IServer *CPlayer::Server() const { return m_pGameServer->Server(); } - + CPlayer::CPlayer(CGameContext *pGameServer, int ClientID, int Team) { m_pGameServer = pGameServer; @@ -58,7 +58,7 @@ void CPlayer::Tick() m_Latency.m_AccumMax = 0; } } - + if(!Character && m_DieTick+Server()->TickSpeed()*3 <= Server()->Tick()) m_Spawning = true; @@ -148,9 +148,9 @@ void CPlayer::OnDisconnect(const char *pReason) { char aBuf[512]; if(pReason && *pReason) - str_format(aBuf, sizeof(aBuf), "'%s' has left the game (%s)", Server()->ClientName(m_ClientID), pReason); + str_format(aBuf, sizeof(aBuf), "'%s' has left the game (%s)", Server()->ClientName(m_ClientID), pReason); else - str_format(aBuf, sizeof(aBuf), "'%s' has left the game", Server()->ClientName(m_ClientID)); + str_format(aBuf, sizeof(aBuf), "'%s' has left the game", Server()->ClientName(m_ClientID)); GameServer()->SendChat(-1, CGameContext::CHAT_ALL, aBuf); str_format(aBuf, sizeof(aBuf), "leave player='%d:%s'", m_ClientID, Server()->ClientName(m_ClientID)); @@ -173,7 +173,7 @@ void CPlayer::OnDirectInput(CNetObj_PlayerInput *NewInput) if(!Character && m_Team != TEAM_SPECTATORS && (NewInput->m_Fire&1)) m_Spawning = true; - + if(!Character && m_Team == TEAM_SPECTATORS && m_SpectatorID == SPEC_FREEVIEW) m_ViewPos = vec2(NewInput->m_TargetX, NewInput->m_TargetY); @@ -217,11 +217,11 @@ void CPlayer::SetTeam(int Team) Team = GameServer()->m_pController->ClampTeam(Team); if(m_Team == Team) return; - + char aBuf[512]; str_format(aBuf, sizeof(aBuf), "'%s' joined the %s", Server()->ClientName(m_ClientID), GameServer()->m_pController->GetTeamName(Team)); - GameServer()->SendChat(-1, CGameContext::CHAT_ALL, aBuf); - + GameServer()->SendChat(-1, CGameContext::CHAT_ALL, aBuf); + KillCharacter(); m_Team = Team; @@ -230,7 +230,7 @@ void CPlayer::SetTeam(int Team) m_RespawnTick = Server()->Tick()+Server()->TickSpeed()/2; str_format(aBuf, sizeof(aBuf), "team_join player='%d:%s' m_Team=%d", m_ClientID, Server()->ClientName(m_ClientID), m_Team); GameServer()->Console()->Print(IConsole::OUTPUT_LEVEL_DEBUG, "game", aBuf); - + GameServer()->m_pController->OnPlayerInfoChange(GameServer()->m_apPlayers[m_ClientID]); if(Team == TEAM_SPECTATORS) @@ -247,7 +247,7 @@ void CPlayer::SetTeam(int Team) void CPlayer::TryRespawn() { vec2 SpawnPos; - + if(!GameServer()->m_pController->CanSpawn(m_Team, &SpawnPos)) return; diff --git a/src/game/server/player.h b/src/game/server/player.h index 50f1c1a0..9d5e462c 100644 --- a/src/game/server/player.h +++ b/src/game/server/player.h @@ -11,7 +11,7 @@ class CPlayer { MACRO_ALLOC_POOL_ID() - + public: CPlayer(CGameContext *pGameServer, int ClientID, int Team); ~CPlayer(); @@ -23,7 +23,7 @@ public: void SetTeam(int Team); int GetTeam() const { return m_Team; }; int GetCID() const { return m_ClientID; }; - + void Tick(); void PostTick(); void Snap(int SnappingClient); @@ -31,10 +31,10 @@ public: void OnDirectInput(CNetObj_PlayerInput *NewInput); void OnPredictedInput(CNetObj_PlayerInput *NewInput); void OnDisconnect(const char *pReason); - + void KillCharacter(int Weapon = WEAPON_GAME); CCharacter *GetCharacter(); - + //--------------------------------------------------------- // this is used for snapping so we know how we can clip the view for the player vec2 m_ViewPos; @@ -49,7 +49,7 @@ public: int m_SpectatorID; bool m_IsReady; - + // int m_Vote; int m_VotePos; @@ -62,16 +62,16 @@ public: int m_LastChangeInfo; int m_LastEmote; int m_LastKill; - + // TODO: clean this up - struct + struct { char m_SkinName[64]; int m_UseCustomColor; int m_ColorBody; int m_ColorFeet; } m_TeeInfos; - + int m_RespawnTick; int m_DieTick; int m_Score; @@ -84,7 +84,7 @@ public: int m_TargetY; } m_LatestActivity; - // network latency calculations + // network latency calculations struct { int m_Accum; @@ -92,16 +92,16 @@ public: int m_AccumMax; int m_Avg; int m_Min; - int m_Max; + int m_Max; } m_Latency; - + private: CCharacter *Character; CGameContext *m_pGameServer; - + CGameContext *GameServer() const { return m_pGameServer; } IServer *Server() const; - + // bool m_Spawning; int m_ClientID; diff --git a/src/mastersrv/mastersrv.cpp b/src/mastersrv/mastersrv.cpp index a3da8cd0..862c57af 100644 --- a/src/mastersrv/mastersrv.cpp +++ b/src/mastersrv/mastersrv.cpp @@ -109,7 +109,7 @@ void BuildPackets() m_NumPackets++; } - // copy header + // copy header mem_copy(m_aPackets[m_NumPackets-1].m_Data.m_aHeader, SERVERBROWSE_LIST, sizeof(SERVERBROWSE_LIST)); // copy server addresses @@ -146,9 +146,9 @@ void BuildPackets() m_NumPacketsLegacy++; } - // copy header + // copy header mem_copy(m_aPacketsLegacy[m_NumPacketsLegacy-1].m_Data.m_aHeader, SERVERBROWSE_LIST_LEGACY, sizeof(SERVERBROWSE_LIST_LEGACY)); - + // copy server addresses mem_copy(m_aPacketsLegacy[m_NumPacketsLegacy-1].m_Data.m_aServers[PacketIndexLegacy].m_aIp, pCurrent->m_Address.ip, sizeof(m_aPacketsLegacy[m_NumPacketsLegacy-1].m_Data.m_aServers[PacketIndexLegacy].m_aIp)); @@ -179,7 +179,7 @@ void SendOk(NETADDR *pAddr) p.m_Flags = NETSENDFLAG_CONNLESS; p.m_DataSize = sizeof(SERVERBROWSE_FWOK); p.m_pData = SERVERBROWSE_FWOK; - + // send on both to be sure m_NetChecker.Send(&p); m_NetOp.Send(&p); @@ -215,7 +215,7 @@ void AddCheckserver(NETADDR *pInfo, NETADDR *pAlt, ServerType Type) dbg_msg("mastersrv", "error: mastersrv is full"); return; } - + char aAddrStr[NETADDR_MAXSTRSIZE]; net_addr_str(pInfo, aAddrStr, sizeof(aAddrStr)); char aAltAddrStr[NETADDR_MAXSTRSIZE]; @@ -243,14 +243,14 @@ void AddServer(NETADDR *pInfo, ServerType Type) return; } } - + // add server if(m_NumServers == MAX_SERVERS) { dbg_msg("mastersrv", "error: mastersrv is full"); return; } - + char aAddrStr[NETADDR_MAXSTRSIZE]; net_addr_str(pInfo, aAddrStr, sizeof(aAddrStr)); dbg_msg("mastersrv", "added: %s", aAddrStr); @@ -275,7 +275,7 @@ void UpdateServers() char aAltAddrStr[NETADDR_MAXSTRSIZE]; net_addr_str(&m_aCheckServers[i].m_AltAddress, aAltAddrStr, sizeof(aAltAddrStr)); dbg_msg("mastersrv", "check failed: %s (%s)", aAddrStr, aAltAddrStr); - + // FAIL!! SendError(&m_aCheckServers[i].m_Address); m_aCheckServers[i] = m_aCheckServers[m_NumCheckServers-1]; @@ -342,19 +342,19 @@ void ConAddBan(IConsole::IResult *pResult, void *pUser) dbg_msg("mastersrv", "error: banlist is full"); return; } - + if(net_addr_from_str(&m_aBans[m_NumBans].m_Address, pResult->GetString(0)) != 0) { dbg_msg("mastersrv", "error: invalid address"); return; } - + if(CheckBan(m_aBans[m_NumBans].m_Address)) { dbg_msg("mastersrv", "duplicate ban: %s", pResult->GetString(0)); return; } - + dbg_msg("mastersrv", "ban added: %s", pResult->GetString(0)); m_NumBans++; } @@ -377,7 +377,7 @@ int main(int argc, const char **argv) // ignore_convention mem_zero(&BindAddr, sizeof(BindAddr)); BindAddr.type = NETTYPE_ALL; BindAddr.port = MASTERSERVER_PORT; - + if(!m_NetOp.Open(BindAddr, 0)) { dbg_msg("mastersrv", "couldn't start network (op)"); @@ -390,7 +390,7 @@ int main(int argc, const char **argv) // ignore_convention dbg_msg("mastersrv", "couldn't start network (checker)"); return -1; } - + mem_copy(m_CountData.m_Header, SERVERBROWSE_COUNT, sizeof(SERVERBROWSE_COUNT)); mem_copy(m_CountDataLegacy.m_Header, SERVERBROWSE_COUNT_LEGACY, sizeof(SERVERBROWSE_COUNT_LEGACY)); @@ -405,14 +405,14 @@ int main(int argc, const char **argv) // ignore_convention if(RegisterFail) return -1; - + dbg_msg("mastersrv", "started"); - + while(1) { m_NetOp.Update(); m_NetChecker.Update(); - + // process m_aPackets CNetChunk Packet; while(m_NetOp.Recv(&Packet)) @@ -442,7 +442,7 @@ int main(int argc, const char **argv) // ignore_convention Alt.port = (d[sizeof(SERVERBROWSE_HEARTBEAT)]<<8) | d[sizeof(SERVERBROWSE_HEARTBEAT)+1]; - + // add it AddCheckserver(&Packet.m_Address, &Alt, SERVERTYPE_LEGACY); } @@ -466,7 +466,7 @@ int main(int argc, const char **argv) // ignore_convention mem_comp(Packet.m_pData, SERVERBROWSE_GETCOUNT_LEGACY, sizeof(SERVERBROWSE_GETCOUNT_LEGACY)) == 0) { dbg_msg("mastersrv", "count requested, responding with %d", m_NumServers); - + CNetChunk p; p.m_ClientID = -1; p.m_Address = Packet.m_Address; @@ -500,12 +500,12 @@ int main(int argc, const char **argv) // ignore_convention { // someone requested the list dbg_msg("mastersrv", "requested, responding with %d m_aServers", m_NumServers); - + CNetChunk p; p.m_ClientID = -1; p.m_Address = Packet.m_Address; p.m_Flags = NETSENDFLAG_CONNLESS; - + for(int i = 0; i < m_NumPacketsLegacy; i++) { p.m_DataSize = m_aPacketsLegacy[i].m_Size; @@ -520,7 +520,7 @@ int main(int argc, const char **argv) // ignore_convention { // check if the server is banned if(CheckBan(Packet.m_Address)) continue; - + if(Packet.m_DataSize == sizeof(SERVERBROWSE_FWRESPONSE) && mem_comp(Packet.m_pData, SERVERBROWSE_FWRESPONSE, sizeof(SERVERBROWSE_FWRESPONSE)) == 0) { @@ -546,7 +546,7 @@ int main(int argc, const char **argv) // ignore_convention SendOk(&Packet.m_Address); } } - + if(time_get()-LastBanReload > time_freq()*300) { LastBanReload = time_get(); @@ -557,15 +557,15 @@ int main(int argc, const char **argv) // ignore_convention if(time_get()-LastBuild > time_freq()*5) { LastBuild = time_get(); - + PurgeServers(); UpdateServers(); BuildPackets(); } - + // be nice to the CPU thread_sleep(1); } - + return 0; } diff --git a/src/osxlaunch/client.h b/src/osxlaunch/client.h index be59d0b9..450b8543 100644 --- a/src/osxlaunch/client.h +++ b/src/osxlaunch/client.h @@ -1,10 +1,10 @@ #ifndef OSXLAUNCH_CLIENT_H #define OSXLAUNCH_CLIENT_H -/* SDLMain.m - main entry point for our Cocoa-ized SDL app - Initial Version: Darrell Walisser <dwaliss1@purdue.edu> - Non-NIB-Code & other changes: Max Horn <max@quendi.de> +/* SDLMain.m - main entry point for our Cocoa-ized SDL app + Initial Version: Darrell Walisser <dwaliss1@purdue.edu> + Non-NIB-Code & other changes: Max Horn <max@quendi.de> - Feel free to customize this file to suit your needs + Feel free to customize this file to suit your needs */ #import <Cocoa/Cocoa.h> diff --git a/src/osxlaunch/client.m b/src/osxlaunch/client.m index c6e6203e..6de919e2 100644 --- a/src/osxlaunch/client.m +++ b/src/osxlaunch/client.m @@ -1,8 +1,8 @@ -/* SDLMain.m - main entry point for our Cocoa-ized SDL app - Initial Version: Darrell Walisser <dwaliss1@purdue.edu> - Non-NIB-Code & other changes: Max Horn <max@quendi.de> +/* SDLMain.m - main entry point for our Cocoa-ized SDL app + Initial Version: Darrell Walisser <dwaliss1@purdue.edu> + Non-NIB-Code & other changes: Max Horn <max@quendi.de> - Feel free to customize this file to suit your needs + Feel free to customize this file to suit your needs */ #import <SDL.h> @@ -36,25 +36,25 @@ extern OSErr CPSSetFrontProcess( CPSProcessSerNum *psn); #endif /* SDL_USE_CPS */ -static int gArgc; -static char **gArgv; -static BOOL gFinderLaunch; -static BOOL gCalledAppMainline = FALSE; +static int gArgc; +static char **gArgv; +static BOOL gFinderLaunch; +static BOOL gCalledAppMainline = FALSE; static NSString *getApplicationName(void) { - NSDictionary *dict; - NSString *appName = 0; - - /* Determine the application name */ - dict = (NSDictionary *)CFBundleGetInfoDictionary(CFBundleGetMainBundle()); - if (dict) - appName = [dict objectForKey: @"CFBundleName"]; - - if (![appName length]) - appName = [[NSProcessInfo processInfo] processName]; - - return appName; + NSDictionary *dict; + NSString *appName = 0; + + /* Determine the application name */ + dict = (NSDictionary *)CFBundleGetInfoDictionary(CFBundleGetMainBundle()); + if (dict) + appName = [dict objectForKey: @"CFBundleName"]; + + if (![appName length]) + appName = [[NSProcessInfo processInfo] processName]; + + return appName; } #if SDL_USE_NIB_FILE @@ -71,10 +71,10 @@ static NSString *getApplicationName(void) /* Invoked from the Quit menu item */ - (void)terminate:(id)sender { - /* Post a SDL_QUIT event */ - SDL_Event event; - event.type = SDL_QUIT; - SDL_PushEvent(&event); + /* Post a SDL_QUIT event */ + SDL_Event event; + event.type = SDL_QUIT; + SDL_PushEvent(&event); } @end @@ -93,133 +93,133 @@ static NSString *getApplicationName(void) /* Fix menu to contain the real app name instead of "SDL App" */ - (void)fixMenu:(NSMenu *)aMenu withAppName:(NSString *)appName { - NSRange aRange; - NSEnumerator *enumerator; - NSMenuItem *menuItem; - - aRange = [[aMenu title] rangeOfString:@"SDL App"]; - if (aRange.length != 0) - [aMenu setTitle: [[aMenu title] stringByReplacingRange:aRange with:appName]]; - - enumerator = [[aMenu itemArray] objectEnumerator]; - while ((menuItem = [enumerator nextObject])) - { - aRange = [[menuItem title] rangeOfString:@"SDL App"]; - if (aRange.length != 0) - [menuItem setTitle: [[menuItem title] stringByReplacingRange:aRange with:appName]]; - if ([menuItem hasSubmenu]) - [self fixMenu:[menuItem submenu] withAppName:appName]; - } - [ aMenu sizeToFit ]; + NSRange aRange; + NSEnumerator *enumerator; + NSMenuItem *menuItem; + + aRange = [[aMenu title] rangeOfString:@"SDL App"]; + if (aRange.length != 0) + [aMenu setTitle: [[aMenu title] stringByReplacingRange:aRange with:appName]]; + + enumerator = [[aMenu itemArray] objectEnumerator]; + while ((menuItem = [enumerator nextObject])) + { + aRange = [[menuItem title] rangeOfString:@"SDL App"]; + if (aRange.length != 0) + [menuItem setTitle: [[menuItem title] stringByReplacingRange:aRange with:appName]]; + if ([menuItem hasSubmenu]) + [self fixMenu:[menuItem submenu] withAppName:appName]; + } + [ aMenu sizeToFit ]; } #else static void setApplicationMenu(void) { - /* warning: this code is very odd */ - NSMenu *appleMenu; - NSMenuItem *menuItem; - NSString *title; - NSString *appName; - - appName = getApplicationName(); - appleMenu = [[NSMenu alloc] initWithTitle:@""]; - - /* Add menu items */ - title = [@"About " stringByAppendingString:appName]; - [appleMenu addItemWithTitle:title action:@selector(orderFrontStandardAboutPanel:) keyEquivalent:@""]; - - [appleMenu addItem:[NSMenuItem separatorItem]]; - - title = [@"Hide " stringByAppendingString:appName]; - [appleMenu addItemWithTitle:title action:@selector(hide:) keyEquivalent:@"h"]; - - menuItem = (NSMenuItem *)[appleMenu addItemWithTitle:@"Hide Others" action:@selector(hideOtherApplications:) keyEquivalent:@"h"]; - [menuItem setKeyEquivalentModifierMask:(NSAlternateKeyMask|NSCommandKeyMask)]; - - [appleMenu addItemWithTitle:@"Show All" action:@selector(unhideAllApplications:) keyEquivalent:@""]; - - [appleMenu addItem:[NSMenuItem separatorItem]]; - - title = [@"Quit " stringByAppendingString:appName]; - [appleMenu addItemWithTitle:title action:@selector(terminate:) keyEquivalent:@"q"]; - - - /* Put menu into the menubar */ - menuItem = [[NSMenuItem alloc] initWithTitle:@"" action:nil keyEquivalent:@""]; - [menuItem setSubmenu:appleMenu]; - [[NSApp mainMenu] addItem:menuItem]; - - /* Tell the application object that this is now the application menu */ - [NSApp setAppleMenu:appleMenu]; - - /* Finally give up our references to the objects */ - [appleMenu release]; - [menuItem release]; + /* warning: this code is very odd */ + NSMenu *appleMenu; + NSMenuItem *menuItem; + NSString *title; + NSString *appName; + + appName = getApplicationName(); + appleMenu = [[NSMenu alloc] initWithTitle:@""]; + + /* Add menu items */ + title = [@"About " stringByAppendingString:appName]; + [appleMenu addItemWithTitle:title action:@selector(orderFrontStandardAboutPanel:) keyEquivalent:@""]; + + [appleMenu addItem:[NSMenuItem separatorItem]]; + + title = [@"Hide " stringByAppendingString:appName]; + [appleMenu addItemWithTitle:title action:@selector(hide:) keyEquivalent:@"h"]; + + menuItem = (NSMenuItem *)[appleMenu addItemWithTitle:@"Hide Others" action:@selector(hideOtherApplications:) keyEquivalent:@"h"]; + [menuItem setKeyEquivalentModifierMask:(NSAlternateKeyMask|NSCommandKeyMask)]; + + [appleMenu addItemWithTitle:@"Show All" action:@selector(unhideAllApplications:) keyEquivalent:@""]; + + [appleMenu addItem:[NSMenuItem separatorItem]]; + + title = [@"Quit " stringByAppendingString:appName]; + [appleMenu addItemWithTitle:title action:@selector(terminate:) keyEquivalent:@"q"]; + + + /* Put menu into the menubar */ + menuItem = [[NSMenuItem alloc] initWithTitle:@"" action:nil keyEquivalent:@""]; + [menuItem setSubmenu:appleMenu]; + [[NSApp mainMenu] addItem:menuItem]; + + /* Tell the application object that this is now the application menu */ + [NSApp setAppleMenu:appleMenu]; + + /* Finally give up our references to the objects */ + [appleMenu release]; + [menuItem release]; } /* Create a window menu */ static void setupWindowMenu(void) { - NSMenu *windowMenu; - NSMenuItem *windowMenuItem; - NSMenuItem *menuItem; - - windowMenu = [[NSMenu alloc] initWithTitle:@"Window"]; - - /* "Minimize" item */ - menuItem = [[NSMenuItem alloc] initWithTitle:@"Minimize" action:@selector(performMiniaturize:) keyEquivalent:@"m"]; - [windowMenu addItem:menuItem]; - [menuItem release]; - - /* Put menu into the menubar */ - windowMenuItem = [[NSMenuItem alloc] initWithTitle:@"Window" action:nil keyEquivalent:@""]; - [windowMenuItem setSubmenu:windowMenu]; - [[NSApp mainMenu] addItem:windowMenuItem]; - - /* Tell the application object that this is now the window menu */ - [NSApp setWindowsMenu:windowMenu]; - - /* Finally give up our references to the objects */ - [windowMenu release]; - [windowMenuItem release]; + NSMenu *windowMenu; + NSMenuItem *windowMenuItem; + NSMenuItem *menuItem; + + windowMenu = [[NSMenu alloc] initWithTitle:@"Window"]; + + /* "Minimize" item */ + menuItem = [[NSMenuItem alloc] initWithTitle:@"Minimize" action:@selector(performMiniaturize:) keyEquivalent:@"m"]; + [windowMenu addItem:menuItem]; + [menuItem release]; + + /* Put menu into the menubar */ + windowMenuItem = [[NSMenuItem alloc] initWithTitle:@"Window" action:nil keyEquivalent:@""]; + [windowMenuItem setSubmenu:windowMenu]; + [[NSApp mainMenu] addItem:windowMenuItem]; + + /* Tell the application object that this is now the window menu */ + [NSApp setWindowsMenu:windowMenu]; + + /* Finally give up our references to the objects */ + [windowMenu release]; + [windowMenuItem release]; } /* Replacement for NSApplicationMain */ static void CustomApplicationMain (int argc, char **argv) { - NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; - SDLMain *sdlMain; + NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; + SDLMain *sdlMain; + + /* Ensure the application object is initialised */ + [SDLApplication sharedApplication]; - /* Ensure the application object is initialised */ - [SDLApplication sharedApplication]; - #ifdef SDL_USE_CPS - { - CPSProcessSerNum PSN; - /* Tell the dock about us */ - if (!CPSGetCurrentProcess(&PSN)) - if (!CPSEnableForegroundOperation(&PSN,0x03,0x3C,0x2C,0x1103)) - if (!CPSSetFrontProcess(&PSN)) - [SDLApplication sharedApplication]; - } + { + CPSProcessSerNum PSN; + /* Tell the dock about us */ + if (!CPSGetCurrentProcess(&PSN)) + if (!CPSEnableForegroundOperation(&PSN,0x03,0x3C,0x2C,0x1103)) + if (!CPSSetFrontProcess(&PSN)) + [SDLApplication sharedApplication]; + } #endif /* SDL_USE_CPS */ - /* Set up the menubar */ - [NSApp setMainMenu:[[NSMenu alloc] init]]; - setApplicationMenu(); - setupWindowMenu(); - - /* Create SDLMain and make it the app delegate */ - sdlMain = [[SDLMain alloc] init]; - [NSApp setDelegate:sdlMain]; - - /* Start the main event loop */ - [NSApp run]; - - [sdlMain release]; - [pool release]; + /* Set up the menubar */ + [NSApp setMainMenu:[[NSMenu alloc] init]]; + setApplicationMenu(); + setupWindowMenu(); + + /* Create SDLMain and make it the app delegate */ + sdlMain = [[SDLMain alloc] init]; + [NSApp setDelegate:sdlMain]; + + /* Start the main event loop */ + [NSApp run]; + + [sdlMain release]; + [pool release]; } #endif @@ -227,14 +227,14 @@ static void CustomApplicationMain (int argc, char **argv) /* * Catch document open requests...this lets us notice files when the app - * was launched by double-clicking a document, or when a document was - * dragged/dropped on the app's icon. You need to have a - * CFBundleDocumentsType section in your Info.plist to get this message, - * apparently. + * was launched by double-clicking a document, or when a document was + * dragged/dropped on the app's icon. You need to have a + * CFBundleDocumentsType section in your Info.plist to get this message, + * apparently. * * Files are added to gArgv, so to the app, they'll look like command line - * arguments. Previously, apps launched from the finder had nothing but - * an argv[0]. + * arguments. Previously, apps launched from the finder had nothing but + * an argv[0]. * * This message may be received multiple times to open several docs on launch. * @@ -242,57 +242,57 @@ static void CustomApplicationMain (int argc, char **argv) */ - (BOOL)application:(NSApplication *)theApplication openFile:(NSString *)filename { - const char *temparg; - size_t arglen; - char *arg; - char **newargv; - - if (!gFinderLaunch) /* MacOS is passing command line args. */ - return FALSE; - - if (gCalledAppMainline) /* app has started, ignore this document. */ - return FALSE; - - temparg = [filename UTF8String]; - arglen = SDL_strlen(temparg) + 1; - arg = (char *) SDL_malloc(arglen); - if (arg == NULL) - return FALSE; - - newargv = (char **) realloc(gArgv, sizeof (char *) * (gArgc + 2)); - if (newargv == NULL) - { - SDL_free(arg); - return FALSE; - } - gArgv = newargv; - - SDL_strlcpy(arg, temparg, arglen); - gArgv[gArgc++] = arg; - gArgv[gArgc] = NULL; - return TRUE; + const char *temparg; + size_t arglen; + char *arg; + char **newargv; + + if (!gFinderLaunch) /* MacOS is passing command line args. */ + return FALSE; + + if (gCalledAppMainline) /* app has started, ignore this document. */ + return FALSE; + + temparg = [filename UTF8String]; + arglen = SDL_strlen(temparg) + 1; + arg = (char *) SDL_malloc(arglen); + if (arg == NULL) + return FALSE; + + newargv = (char **) realloc(gArgv, sizeof (char *) * (gArgc + 2)); + if (newargv == NULL) + { + SDL_free(arg); + return FALSE; + } + gArgv = newargv; + + SDL_strlcpy(arg, temparg, arglen); + gArgv[gArgc++] = arg; + gArgv[gArgc] = NULL; + return TRUE; } /* Called when the internal event loop has just started running */ - (void) applicationDidFinishLaunching: (NSNotification *) note { - int status; + int status; - /* Set the working directory to the .app's parent directory */ - [self setupWorkingDirectory:gFinderLaunch]; + /* Set the working directory to the .app's parent directory */ + [self setupWorkingDirectory:gFinderLaunch]; #if SDL_USE_NIB_FILE - /* Set the main menu to contain the real app name instead of "SDL App" */ - [self fixMenu:[NSApp mainMenu] withAppName:getApplicationName()]; + /* Set the main menu to contain the real app name instead of "SDL App" */ + [self fixMenu:[NSApp mainMenu] withAppName:getApplicationName()]; #endif - /* Hand off to main application code */ - gCalledAppMainline = TRUE; - status = SDL_main (gArgc, gArgv); + /* Hand off to main application code */ + gCalledAppMainline = TRUE; + status = SDL_main (gArgc, gArgv); - /* We're done, thank you for playing */ - exit(status); + /* We're done, thank you for playing */ + exit(status); } @end @@ -301,65 +301,65 @@ static void CustomApplicationMain (int argc, char **argv) - (NSString *)stringByReplacingRange:(NSRange)aRange with:(NSString *)aString { - unsigned int bufferSize; - unsigned int selfLen = [self length]; - unsigned int aStringLen = [aString length]; - unichar *buffer; - NSRange localRange; - NSString *result; - - bufferSize = selfLen + aStringLen - aRange.length; - buffer = NSAllocateMemoryPages(bufferSize*sizeof(unichar)); - - /* Get first part into buffer */ - localRange.location = 0; - localRange.length = aRange.location; - [self getCharacters:buffer range:localRange]; - - /* Get middle part into buffer */ - localRange.location = 0; - localRange.length = aStringLen; - [aString getCharacters:(buffer+aRange.location) range:localRange]; - - /* Get last part into buffer */ - localRange.location = aRange.location + aRange.length; - localRange.length = selfLen - localRange.location; - [self getCharacters:(buffer+aRange.location+aStringLen) range:localRange]; - - /* Build output string */ - result = [NSString stringWithCharacters:buffer length:bufferSize]; - - NSDeallocateMemoryPages(buffer, bufferSize); - - return result; + unsigned int bufferSize; + unsigned int selfLen = [self length]; + unsigned int aStringLen = [aString length]; + unichar *buffer; + NSRange localRange; + NSString *result; + + bufferSize = selfLen + aStringLen - aRange.length; + buffer = NSAllocateMemoryPages(bufferSize*sizeof(unichar)); + + /* Get first part into buffer */ + localRange.location = 0; + localRange.length = aRange.location; + [self getCharacters:buffer range:localRange]; + + /* Get middle part into buffer */ + localRange.location = 0; + localRange.length = aStringLen; + [aString getCharacters:(buffer+aRange.location) range:localRange]; + + /* Get last part into buffer */ + localRange.location = aRange.location + aRange.length; + localRange.length = selfLen - localRange.location; + [self getCharacters:(buffer+aRange.location+aStringLen) range:localRange]; + + /* Build output string */ + result = [NSString stringWithCharacters:buffer length:bufferSize]; + + NSDeallocateMemoryPages(buffer, bufferSize); + + return result; } @end #ifdef main -# undef main +#undef main #endif /* Main entry point to executable - should *not* be SDL_main! */ int main (int argc, char **argv) { - /* Copy the arguments into a global variable */ - /* This is passed if we are launched by double-clicking */ - if ( argc >= 2 && strncmp (argv[1], "-psn", 4) == 0 ) { - gArgv = (char **) SDL_malloc(sizeof (char *) * 2); - gArgv[0] = argv[0]; - gArgv[1] = NULL; - gArgc = 1; - gFinderLaunch = YES; - } else { - int i; - gArgc = argc; - gArgv = (char **) SDL_malloc(sizeof (char *) * (argc+1)); - for (i = 0; i <= argc; i++) - gArgv[i] = argv[i]; - gFinderLaunch = NO; - } + /* Copy the arguments into a global variable */ + /* This is passed if we are launched by double-clicking */ + if ( argc >= 2 && strncmp (argv[1], "-psn", 4) == 0 ) { + gArgv = (char **) SDL_malloc(sizeof (char *) * 2); + gArgv[0] = argv[0]; + gArgv[1] = NULL; + gArgc = 1; + gFinderLaunch = YES; + } else { + int i; + gArgc = argc; + gArgv = (char **) SDL_malloc(sizeof (char *) * (argc+1)); + for (i = 0; i <= argc; i++) + gArgv[i] = argv[i]; + gFinderLaunch = NO; + } #if SDL_USE_NIB_FILE [SDLApplication poseAsClass:[NSApplication class]]; @@ -368,6 +368,6 @@ int main (int argc, char **argv) CustomApplicationMain (argc, argv); #endif - return 0; + return 0; } diff --git a/src/osxlaunch/server.m b/src/osxlaunch/server.m index 6c22efc5..5ae32c6f 100644 --- a/src/osxlaunch/server.m +++ b/src/osxlaunch/server.m @@ -13,9 +13,9 @@ { NSPipe *pipe; task = t; - pipe = [NSPipe pipe]; - [task setStandardOutput: pipe]; - file = [pipe fileHandleForReading]; + pipe = [NSPipe pipe]; + [task setStandardOutput: pipe]; + file = [pipe fileHandleForReading]; [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(outputNotification:) name: NSFileHandleReadCompletionNotification object: file]; @@ -30,8 +30,8 @@ [[self textStorage] appendAttributedString: attrstr]; int length = [[self textStorage] length]; - NSRange range = NSMakeRange(length, 0); - [self scrollRangeToVisible: range]; + NSRange range = NSMakeRange(length, 0); + [self scrollRangeToVisible: range]; [attrstr release]; [string release]; @@ -41,18 +41,18 @@ -(void)windowWillClose:(NSNotification *)notification { [task terminate]; - [NSApp terminate:self]; + [NSApp terminate:self]; } @end void runServer() { - NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; - NSApp = [NSApplication sharedApplication]; + NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; + NSApp = [NSApplication sharedApplication]; NSBundle* mainBundle = [NSBundle mainBundle]; NSTask *task; - task = [[NSTask alloc] init]; - [task setCurrentDirectoryPath: [mainBundle resourcePath]]; + task = [[NSTask alloc] init]; + [task setCurrentDirectoryPath: [mainBundle resourcePath]]; // get a server config NSOpenPanel* openDlg = [NSOpenPanel openPanel]; @@ -77,8 +77,8 @@ void runServer() window = [[NSWindow alloc] initWithContentRect: graphicsRect - styleMask: NSTitledWindowMask - | NSClosableWindowMask + styleMask: NSTitledWindowMask + | NSClosableWindowMask | NSMiniaturizableWindowMask backing: NSBackingStoreBuffered defer: NO]; @@ -100,8 +100,8 @@ void runServer() [NSApp run]; [task terminate]; - [NSApp release]; - [pool release]; + [NSApp release]; + [pool release]; } int main (int argc, char **argv) diff --git a/src/tools/crapnet.cpp b/src/tools/crapnet.cpp index 35ca09bc..98b6c0a7 100644 --- a/src/tools/crapnet.cpp +++ b/src/tools/crapnet.cpp @@ -8,7 +8,7 @@ struct CPacket { CPacket *m_pPrev; CPacket *m_pNext; - + NETADDR m_SendTo; int64 m_Timestamp; int m_ID; @@ -46,21 +46,21 @@ void Run(int Port, NETADDR Dest) { NETADDR Src = {NETTYPE_IPV4, {0,0,0,0}, Port}; NETSOCKET Socket = net_udp_create(Src); - + char aBuffer[1024*2]; int ID = 0; int Delaycounter = 0; - + while(1) { static int Lastcfg = 0; int n = ((time_get()/time_freq())/m_ConfigInterval) % m_ConfigNumpingconfs; CPingConfig Ping = m_aConfigPings[n]; - + if(n != Lastcfg) dbg_msg("crapnet", "cfg = %d", n); Lastcfg = n; - + // handle incomming packets while(1) { @@ -70,7 +70,7 @@ void Run(int Port, NETADDR Dest) int Bytes = net_udp_recv(Socket, &From, aBuffer, 1024*2); if(Bytes <= 0) break; - + if((rand()%100) < Ping.m_Loss) // drop the packet { if(m_ConfigLog) @@ -78,7 +78,7 @@ void Run(int Port, NETADDR Dest) continue; } - // create new packet + // create new packet CPacket *p = (CPacket *)mem_alloc(sizeof(CPacket)+Bytes, 1); if(net_addr_comp(&From, &Dest) == 0) @@ -106,7 +106,7 @@ void Run(int Port, NETADDR Dest) p->m_DataSize = Bytes; p->m_ID = ID++; mem_copy(p->m_aData, aBuffer, Bytes); - + if(ID > 20 && Bytes > 6 && DataTrash) { p->m_aData[6+(rand()%(Bytes-6))] = rand()&255; // modify a byte @@ -117,7 +117,7 @@ void Run(int Port, NETADDR Dest) p->m_DataSize = 6; } } - + if(Delaycounter <= 0) { if(Ping.m_Delay) @@ -125,7 +125,7 @@ void Run(int Port, NETADDR Dest) Delaycounter = Ping.m_DelayFreq; } Delaycounter--; - + if(m_ConfigLog) { char aAddrStr[NETADDR_MAXSTRSIZE]; @@ -133,7 +133,7 @@ void Run(int Port, NETADDR Dest) dbg_msg("crapnet", "<< %08d %s (%d)", p->m_ID, aAddrStr, p->m_DataSize); } } - + // /*while(1) {*/ @@ -145,7 +145,7 @@ void Run(int Port, NETADDR Dest) if(!p) break; pNext = p->m_pNext; - + if((time_get()-p->m_Timestamp) > m_CurrentLatency) { char aFlags[] = " "; @@ -155,35 +155,35 @@ void Run(int Port, NETADDR Dest) aFlags[0] = 'R'; p = m_pFirst->m_pNext; } - + if(p->m_pNext) p->m_pNext->m_pPrev = p->m_pPrev; else m_pLast = p->m_pPrev; - + if(p->m_pPrev) p->m_pPrev->m_pNext = p->m_pNext; else m_pFirst = p->m_pNext; - + /*CPacket *cur = first; while(cur) { dbg_assert(cur != p, "p still in list"); cur = cur->next; }*/ - + // send and remove packet //if((rand()%20) != 0) // heavy packetloss net_udp_send(Socket, &p->m_SendTo, p->m_aData, p->m_DataSize); - + // update lag double Flux = rand()/(double)RAND_MAX; int MsSpike = Ping.m_Spike; int MsFlux = Ping.m_Flux; int MsPing = Ping.m_Base; m_CurrentLatency = ((time_freq()*MsPing)/1000) + (int64)(((time_freq()*MsFlux)/1000)*Flux); // 50ms - + if(MsSpike && (p->m_ID%100) == 0) { m_CurrentLatency += (time_freq()*MsSpike)/1000; @@ -196,12 +196,12 @@ void Run(int Port, NETADDR Dest) net_addr_str(&p->m_SendTo, aAddrStr, sizeof(aAddrStr)); dbg_msg("crapnet", ">> %08d %s (%d) %s", p->m_ID, aAddrStr, p->m_DataSize, aFlags); } - + mem_free(p); } } - + thread_sleep(1); } } diff --git a/src/tools/dilate.cpp b/src/tools/dilate.cpp index b1b60ac3..ef862270 100644 --- a/src/tools/dilate.cpp +++ b/src/tools/dilate.cpp @@ -14,7 +14,7 @@ static void Dilate(int w, int h, CPixel *pSrc, CPixel *pDest) int ix, iy; const int xo[] = {0, -1, 1, 0}; const int yo[] = {-1, 0, 0, 1}; - + int m = 0; for(int y = 0; y < h; y++) { @@ -23,7 +23,7 @@ static void Dilate(int w, int h, CPixel *pSrc, CPixel *pDest) pDest[m] = pSrc[m]; if(pSrc[m].a) continue; - + for(int c = 0; c < 4; c++) { ix = clamp(x + xo[c], 0, w-1); @@ -52,38 +52,38 @@ int main(int argc, char **argv) { png_t Png; CPixel *pBuffer[3] = {0,0,0}; - + png_init(0, 0); png_open_file(&Png, argv[1]); - + if(Png.color_type != PNG_TRUECOLOR_ALPHA) { dbg_msg("dilate", "not an RGBA image"); return -1; } - + pBuffer[0] = (CPixel*)mem_alloc(Png.width*Png.height*sizeof(CPixel), 1); pBuffer[1] = (CPixel*)mem_alloc(Png.width*Png.height*sizeof(CPixel), 1); pBuffer[2] = (CPixel*)mem_alloc(Png.width*Png.height*sizeof(CPixel), 1); png_get_data(&Png, (unsigned char *)pBuffer[0]); png_close_file(&Png); - + int w = Png.width; int h = Png.height; - + Dilate(w, h, pBuffer[0], pBuffer[1]); for(int i = 0; i < 5; i++) { Dilate(w, h, pBuffer[1], pBuffer[2]); Dilate(w, h, pBuffer[2], pBuffer[1]); } - + CopyAlpha(w, h, pBuffer[0], pBuffer[1]); - + // save here png_open_file_write(&Png, argv[1]); png_set_data(&Png, w, h, 8, PNG_TRUECOLOR_ALPHA, (unsigned char *)pBuffer[1]); png_close_file(&Png); - + return 0; } diff --git a/src/tools/fake_server.cpp b/src/tools/fake_server.cpp index ac7a8ed9..68c47659 100644 --- a/src/tools/fake_server.cpp +++ b/src/tools/fake_server.cpp @@ -31,18 +31,18 @@ static void SendHeartBeats() { static unsigned char aData[sizeof(SERVERBROWSE_HEARTBEAT) + 2]; CNetChunk Packet; - + mem_copy(aData, SERVERBROWSE_HEARTBEAT, sizeof(SERVERBROWSE_HEARTBEAT)); - + Packet.m_ClientID = -1; Packet.m_Flags = NETSENDFLAG_CONNLESS; Packet.m_DataSize = sizeof(SERVERBROWSE_HEARTBEAT) + 2; Packet.m_pData = &aData; - /* supply the set port that the master can use if it has problems */ + /* supply the set port that the master can use if it has problems */ aData[sizeof(SERVERBROWSE_HEARTBEAT)] = 0; aData[sizeof(SERVERBROWSE_HEARTBEAT)+1] = 0; - + for(int i = 0; i < NumMasters; i++) { Packet.m_Address = aMasterServers[i]; @@ -78,7 +78,7 @@ static void BuildInfoMsg() WriteInt(Progression); WriteInt(NumPlayers); WriteInt(MaxPlayers); - + for(int i = 0; i < NumPlayers; i++) { WriteStr(PlayerNames[i]); @@ -112,10 +112,10 @@ static int Run() { int64 NextHeartBeat = 0; NETADDR BindAddr = {NETTYPE_IPV4, {0},0}; - + if(!pNet->Open(BindAddr, 0, 0, 0)) return 0; - + while(1) { CNetChunk p; @@ -136,14 +136,14 @@ static int Run() } } } - + /* send heartbeats if needed */ if(NextHeartBeat < time_get()) { NextHeartBeat = time_get()+time_freq()*(15+(rand()%15)); SendHeartBeats(); } - + thread_sleep(100); } } @@ -151,7 +151,7 @@ static int Run() int main(int argc, char **argv) { pNet = new CNetServer; - + while(argc) { // ? @@ -200,13 +200,13 @@ int main(int argc, char **argv) argc--; argv++; pServerName = *argv; } - + argc--; argv++; } - + BuildInfoMsg(); int RunReturn = Run(); - + delete pNet; return RunReturn; } diff --git a/src/tools/map_resave.cpp b/src/tools/map_resave.cpp index d97f0323..a536f021 100644 --- a/src/tools/map_resave.cpp +++ b/src/tools/map_resave.cpp @@ -25,7 +25,7 @@ int main(int argc, const char **argv) // add all items for(Index = 0; Index < DataFile.NumItems(); Index++) - { + { pPtr = DataFile.GetItem(Index, &Type, &ID); Size = DataFile.GetItemSize(Index); df.AddItem(Type, ID, Size, pPtr); diff --git a/src/tools/map_version.cpp b/src/tools/map_version.cpp index d995f478..4acc51e0 100644 --- a/src/tools/map_version.cpp +++ b/src/tools/map_version.cpp @@ -29,7 +29,7 @@ int MaplistCallback(const char *pName, int IsDir, int DirType, void *pUser) IOHANDLE MapFile = s_pStorage->OpenFile(aBuf, IOFLAG_READ, DirType); unsigned MapSize = io_length(MapFile); io_close(MapFile); - + char aMapName[8]; str_copy(aMapName, pName, min((int)sizeof(aMapName),l-3)); @@ -52,7 +52,7 @@ int main(int argc, const char **argv) // ignore_convention if(RegisterFail) return -1; - + s_File = s_pStorage->OpenFile("map_version.txt", IOFLAG_WRITE, 1); if(s_File) { @@ -61,6 +61,6 @@ int main(int argc, const char **argv) // ignore_convention io_write(s_File, "};\n", str_length("};\n")); io_close(s_File); } - + return 0; } diff --git a/src/tools/packetgen.cpp b/src/tools/packetgen.cpp index 7e9a8a19..9b52aadc 100644 --- a/src/tools/packetgen.cpp +++ b/src/tools/packetgen.cpp @@ -7,13 +7,13 @@ enum { NUM_SOCKETS = 64 }; void Run(NETADDR Dest) { NETSOCKET aSockets[NUM_SOCKETS]; - + for(int i = 0; i < NUM_SOCKETS; i++) { NETADDR BindAddr = {NETTYPE_IPV4, {0}, 0}; aSockets[i] = net_udp_create(BindAddr); } - + while(1) { unsigned char aData[1024]; diff --git a/src/tools/tileset_borderfix.cpp b/src/tools/tileset_borderfix.cpp index d28e3074..b5eef77a 100644 --- a/src/tools/tileset_borderfix.cpp +++ b/src/tools/tileset_borderfix.cpp @@ -20,9 +20,9 @@ static void TilesetBorderfix(int w, int h, CPixel *pSrc, CPixel *pDest) { int TileW = w/16; int TileH = h/16; - + mem_zero(pDest, sizeof(CPixel)*w*h); - + for(int ty = 0; ty < 16; ty++) { for(int tx = 0; tx < 16; tx++) @@ -35,12 +35,12 @@ static void TilesetBorderfix(int w, int h, CPixel *pSrc, CPixel *pDest) float v = 0.5f/TileH + y/(float)(TileH-2); int k = (ty*TileH+1+y)*w + tx*TileW+x+1; pDest[k] = Sample(tx*TileW, ty*TileH, TileW, TileH, pSrc, w, u, v); - + if(x == 0) pDest[k-1] = pDest[k]; if(x == TileW-2-1) pDest[k+1] = pDest[k]; if(y == 0) pDest[k-w] = pDest[k]; if(y == TileH-2-1) pDest[k+w] = pDest[k]; - + if(x == 0 && y == 0) pDest[k-w-1] = pDest[k]; if(x == TileW-2-1 && y == 0) pDest[k-w+1] = pDest[k]; if(x == 0 && y == TileH-2-1) pDest[k+w-1] = pDest[k]; @@ -56,30 +56,30 @@ int main(int argc, char **argv) { png_t Png; CPixel *pBuffer[2] = {0,0}; - + png_init(0, 0); png_open_file(&Png, argv[1]); - + if(Png.color_type != PNG_TRUECOLOR_ALPHA) { dbg_msg("dilate", "not an RGBA image"); return -1; } - + int w = Png.width; int h = Png.height; - + pBuffer[0] = (CPixel*)mem_alloc(w*h*sizeof(CPixel), 1); pBuffer[1] = (CPixel*)mem_alloc(w*h*sizeof(CPixel), 1); png_get_data(&Png, (unsigned char *)pBuffer[0]); png_close_file(&Png); - + TilesetBorderfix(w, h, pBuffer[0], pBuffer[1]); - + // save here png_open_file_write(&Png, argv[1]); png_set_data(&Png, w, h, 8, PNG_TRUECOLOR_ALPHA, (unsigned char *)pBuffer[1]); png_close_file(&Png); - + return 0; } diff --git a/src/versionsrv/versionsrv.cpp b/src/versionsrv/versionsrv.cpp index d36fba3b..ac5883f9 100644 --- a/src/versionsrv/versionsrv.cpp +++ b/src/versionsrv/versionsrv.cpp @@ -37,19 +37,19 @@ void BuildPackets() if(Chunk > MAX_MAPS_PER_PACKET) Chunk = MAX_MAPS_PER_PACKET; ServersLeft -= Chunk; - - // copy header + + // copy header mem_copy(m_aPackets[m_NumPackets].m_Data.m_aHeader, VERSIONSRV_MAPLIST, sizeof(VERSIONSRV_MAPLIST)); - + // copy map versions for(int i = 0; i < Chunk; i++) { m_aPackets[m_NumPackets].m_Data.m_aMaplist[i] = *pCurrent; pCurrent++; } - + m_aPackets[m_NumPackets].m_Size = sizeof(VERSIONSRV_MAPLIST) + sizeof(CMapVersion)*Chunk; - + m_NumPackets++; } } @@ -58,10 +58,10 @@ void SendVer(NETADDR *pAddr) { CNetChunk p; unsigned char aData[sizeof(VERSIONSRV_VERSION) + sizeof(VERSION_DATA)]; - + mem_copy(aData, VERSIONSRV_VERSION, sizeof(VERSIONSRV_VERSION)); mem_copy(aData + sizeof(VERSIONSRV_VERSION), VERSION_DATA, sizeof(VERSION_DATA)); - + p.m_ClientID = -1; p.m_Address = *pAddr; p.m_Flags = NETSENDFLAG_CONNLESS; @@ -88,13 +88,13 @@ int main(int argc, char **argv) // ignore_convention } BuildPackets(); - + dbg_msg("versionsrv", "started"); - + while(1) { g_NetOp.Update(); - + // process packets CNetChunk Packet; while(g_NetOp.Recv(&Packet)) @@ -112,7 +112,7 @@ int main(int argc, char **argv) // ignore_convention p.m_ClientID = -1; p.m_Address = Packet.m_Address; p.m_Flags = NETSENDFLAG_CONNLESS; - + for(int i = 0; i < m_NumPackets; i++) { p.m_DataSize = m_aPackets[i].m_Size; @@ -121,10 +121,10 @@ int main(int argc, char **argv) // ignore_convention } } } - + // be nice to the CPU thread_sleep(1); } - + return 0; } |